Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
61
// Tokens could not be issued.
throw;
throw;
42,409
12
// Base contract of Strategy.This contact defines common properties and functions shared by all strategies.One strategy is bound to one vault and cannot be changed. /
abstract contract StrategyBase is IStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; event PerformanceFeeUpdated(uint256 oldPerformanceFee, uint256 newPerformanceFee); event WithdrawalFeeUpdated(uint256 oldWithdrawFee, uint256 newWithdrawFee); address public override vault; uint256 public override performanceFee; uint256 public override withdrawalFee; uint256 public constant PERCENT_MAX = 10000; // 0.01% constructor(address _vault) internal { require(_vault != address(0x0), "vault not set"); vault = _vault; } modifier authorized() { require(msg.sender == vault || msg.sender == governance() || msg.sender == strategist(), "not authorized"); _; } /** * @dev Returns the token that the vault pools to seek yield. * Should be the same as Vault.token(). */ function token() public override view returns (address) { return IVault(vault).token(); } /** * @dev Returns the Controller that manages the vault. * Should be the same as Vault.controler(). */ function controller() public override view returns (address) { return IVault(vault).controller(); } /** * @dev Returns the governance of the Strategy. * Controller and its underlying vaults and strategies should share the same governance. */ function governance() public override view returns (address) { return IVault(vault).governance(); } /** * @dev Return the strategist which performs daily permissioned operations. * Vault and its underlying strategies should share the same strategist. */ function strategist() public override view returns (address) { return IVault(vault).strategist(); } modifier onlyGovernance() { require(msg.sender == governance(), "not governance"); _; } modifier onlyStrategist() { require(msg.sender == governance() || msg.sender == strategist(), "not strategist"); _; } /** * @dev Updates the performance fee. Only governance can update the performance fee. */ function setPerformanceFee(uint256 _performanceFee) public onlyGovernance { require(_performanceFee <= PERCENT_MAX, "overflow"); uint256 oldPerformanceFee = performanceFee; performanceFee = _performanceFee; emit PerformanceFeeUpdated(oldPerformanceFee, _performanceFee); } /** * @dev Updates the withdrawal fee. Only governance can update the withdrawal fee. */ function setWithdrawalFee(uint256 _withdrawalFee) public onlyGovernance { require(_withdrawalFee <= PERCENT_MAX, "overflow"); uint256 oldWithdrawalFee = withdrawalFee; withdrawalFee = _withdrawalFee; emit WithdrawalFeeUpdated(oldWithdrawalFee, _withdrawalFee); } /** * @dev Used to salvage any ETH deposited into the vault by mistake. * Only governance or strategist can salvage ETH from the vault. * The salvaged ETH is transferred to treasury for futher operation. */ function salvage() public onlyStrategist { uint256 amount = address(this).balance; address payable target = payable(IController(controller()).treasury()); (bool success, ) = target.call{value: amount}(new bytes(0)); require(success, 'ETH salvage failed'); } /** * @dev Used to salvage any token deposited into the vault by mistake. * The want token cannot be salvaged. * Only governance or strategist can salvage token from the vault. * The salvaged token is transferred to treasury for futhuer operation. * @param _tokenAddress Token address to salvage. */ function salvageToken(address _tokenAddress) public onlyStrategist { address[] memory protected = _getProtectedTokens(); for (uint256 i = 0; i < protected.length; i++) { require(_tokenAddress != protected[i], "cannot salvage"); } IERC20Upgradeable target = IERC20Upgradeable(_tokenAddress); target.safeTransfer(IController(controller()).treasury(), target.balanceOf(address(this))); } /** * @dev Return the list of tokens that should not be salvaged. */ function _getProtectedTokens() internal virtual view returns (address[] memory); }
abstract contract StrategyBase is IStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; event PerformanceFeeUpdated(uint256 oldPerformanceFee, uint256 newPerformanceFee); event WithdrawalFeeUpdated(uint256 oldWithdrawFee, uint256 newWithdrawFee); address public override vault; uint256 public override performanceFee; uint256 public override withdrawalFee; uint256 public constant PERCENT_MAX = 10000; // 0.01% constructor(address _vault) internal { require(_vault != address(0x0), "vault not set"); vault = _vault; } modifier authorized() { require(msg.sender == vault || msg.sender == governance() || msg.sender == strategist(), "not authorized"); _; } /** * @dev Returns the token that the vault pools to seek yield. * Should be the same as Vault.token(). */ function token() public override view returns (address) { return IVault(vault).token(); } /** * @dev Returns the Controller that manages the vault. * Should be the same as Vault.controler(). */ function controller() public override view returns (address) { return IVault(vault).controller(); } /** * @dev Returns the governance of the Strategy. * Controller and its underlying vaults and strategies should share the same governance. */ function governance() public override view returns (address) { return IVault(vault).governance(); } /** * @dev Return the strategist which performs daily permissioned operations. * Vault and its underlying strategies should share the same strategist. */ function strategist() public override view returns (address) { return IVault(vault).strategist(); } modifier onlyGovernance() { require(msg.sender == governance(), "not governance"); _; } modifier onlyStrategist() { require(msg.sender == governance() || msg.sender == strategist(), "not strategist"); _; } /** * @dev Updates the performance fee. Only governance can update the performance fee. */ function setPerformanceFee(uint256 _performanceFee) public onlyGovernance { require(_performanceFee <= PERCENT_MAX, "overflow"); uint256 oldPerformanceFee = performanceFee; performanceFee = _performanceFee; emit PerformanceFeeUpdated(oldPerformanceFee, _performanceFee); } /** * @dev Updates the withdrawal fee. Only governance can update the withdrawal fee. */ function setWithdrawalFee(uint256 _withdrawalFee) public onlyGovernance { require(_withdrawalFee <= PERCENT_MAX, "overflow"); uint256 oldWithdrawalFee = withdrawalFee; withdrawalFee = _withdrawalFee; emit WithdrawalFeeUpdated(oldWithdrawalFee, _withdrawalFee); } /** * @dev Used to salvage any ETH deposited into the vault by mistake. * Only governance or strategist can salvage ETH from the vault. * The salvaged ETH is transferred to treasury for futher operation. */ function salvage() public onlyStrategist { uint256 amount = address(this).balance; address payable target = payable(IController(controller()).treasury()); (bool success, ) = target.call{value: amount}(new bytes(0)); require(success, 'ETH salvage failed'); } /** * @dev Used to salvage any token deposited into the vault by mistake. * The want token cannot be salvaged. * Only governance or strategist can salvage token from the vault. * The salvaged token is transferred to treasury for futhuer operation. * @param _tokenAddress Token address to salvage. */ function salvageToken(address _tokenAddress) public onlyStrategist { address[] memory protected = _getProtectedTokens(); for (uint256 i = 0; i < protected.length; i++) { require(_tokenAddress != protected[i], "cannot salvage"); } IERC20Upgradeable target = IERC20Upgradeable(_tokenAddress); target.safeTransfer(IController(controller()).treasury(), target.balanceOf(address(this))); } /** * @dev Return the list of tokens that should not be salvaged. */ function _getProtectedTokens() internal virtual view returns (address[] memory); }
23,141
9
// Set the royalties rate in basis points
function setRoyaltyRate(uint96 _royaltyRate) external onlyOwner { royaltyRate = _royaltyRate; }
function setRoyaltyRate(uint96 _royaltyRate) external onlyOwner { royaltyRate = _royaltyRate; }
73,155
0
// to store token price
mapping(uint256 => uint256) public tokenPrice;
mapping(uint256 => uint256) public tokenPrice;
45,042
17
// set staking state (in terms of STM)_isStakeAvailable block stake_isUnstakeAvailable block unstake_isClaimAvailable block claim /
function setAvailability( bool _isStakeAvailable, bool _isUnstakeAvailable, bool _isClaimAvailable
function setAvailability( bool _isStakeAvailable, bool _isUnstakeAvailable, bool _isClaimAvailable
2,010
0
// a simple counter
uint256 private tokenId; constructor( string memory _name, string memory _symbol
uint256 private tokenId; constructor( string memory _name, string memory _symbol
22,442
51
// 1. Get how many tokens this contract has with a token instance and check this token balance
uint256 tokenBalance = Token(levAddress).balanceOf(disbursement);
uint256 tokenBalance = Token(levAddress).balanceOf(disbursement);
30,876
240
// In some circumstance, we should not burn OX on transfer, eg: Transfer from owner to distribute bounty, from depositing to swap for liquidity
function addTransferBurnExceptAddress(address _transferBurnExceptAddress) public onlyOwner { ox.addTransferBurnExceptAddress(_transferBurnExceptAddress); }
function addTransferBurnExceptAddress(address _transferBurnExceptAddress) public onlyOwner { ox.addTransferBurnExceptAddress(_transferBurnExceptAddress); }
12,025
96
// sBTC uses pool2
estimate = pool2.get_dy_underlying(tokenList[0].curveID, tokenList[i].curveID, renBTCAmount);
estimate = pool2.get_dy_underlying(tokenList[0].curveID, tokenList[i].curveID, renBTCAmount);
3,902
128
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
bytes memory result = abi.encodePacked(input);
35,304
85
// <CHK> 個人情報登録済みチェック 発行体への移転の場合はチェックを行わない
if (_to != owner) { require(PersonalInfo(personalInfoAddress).isRegistered(_to, owner) == true); }
if (_to != owner) { require(PersonalInfo(personalInfoAddress).isRegistered(_to, owner) == true); }
48,882
1,053
// Allows the Owner to set a slashing penalty in SKL tokens for agiven offense. /
function setPenalty(string calldata offense, uint penalty) external { require(hasRole(PENALTY_SETTER_ROLE, msg.sender), "PENALTY_SETTER_ROLE is required"); _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty;
function setPenalty(string calldata offense, uint penalty) external { require(hasRole(PENALTY_SETTER_ROLE, msg.sender), "PENALTY_SETTER_ROLE is required"); _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty;
29,169
64
// Deposit and withdraw
function deposit(uint _amount) public
function deposit(uint _amount) public
49,059
128
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total }else{
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total }else{
2,573
0
// Implementation: https:etherscan.io/address/0x0000000022d53366457f9d5e68ec105046fc4383readContract
interface ICurveAddressProvider { function get_registry() external view returns(address); function get_address(uint256 _id) external view returns(address); }
interface ICurveAddressProvider { function get_registry() external view returns(address); function get_address(uint256 _id) external view returns(address); }
13,812
137
// CEther / CErc20 ===============
function borrowBalanceCurrent(address account) external returns (uint256) { address _avatar = registry.getAvatar(account); return IAvatar(_avatar).borrowBalanceCurrent(cToken); }
function borrowBalanceCurrent(address account) external returns (uint256) { address _avatar = registry.getAvatar(account); return IAvatar(_avatar).borrowBalanceCurrent(cToken); }
37,340
354
// Returns an array of token IDs owned by `owner`. This function scans the ownership mapping and is O(`totalSupply`) in complexity.It is meant to be called off-chain.
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into * multiple smaller scans if the collection is large enough to cause * an out-of-gas error (10K collections should be fine). */ function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownershipAt(i); if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } return tokenIds; } }
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into * multiple smaller scans if the collection is large enough to cause * an out-of-gas error (10K collections should be fine). */ function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownershipAt(i); if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } return tokenIds; } }
9,134
189
// make sure _deposit is more than minDeposit and smaller than unstaked deposit
require(_deposit >= minDeposit && _deposit <= listing.unstakedDeposit);
require(_deposit >= minDeposit && _deposit <= listing.unstakedDeposit);
11,843
47
// Burns a specific amount of tokens._value The amount of token to be burned./
function burn( uint256 _value ) public whenNotPaused
function burn( uint256 _value ) public whenNotPaused
20,437
198
// WOMANOID ERC-721 Contract DegenDeveloper.eth The contract owner has the following permissions:- Toggle whitelist minting- Toggle public minting- Set the URI for the revealed tokens- Set the merkle root for the whitelist- Withdraw the funds from the contract /
contract Womanoid is ERC721, Ownable, ReentrancyGuard { /// ============ SETUP ============ /// using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private totalMinted; string private URI; bytes32 private merkleRoot; bool private WHITELIST_SALE_ACTIVE = false; bool private PUBLIC_SALE_ACTIVE = false; bool private REVEALED = false; /// mapping from each address to number of white list claims minted mapping(address => Counters.Counter) private whitelistClaims; uint256 private constant WL_PRICE = 80000000000000000; // 0.08 ETH uint256 private constant P_PRICE = 90000000000000000; // 0.09 ETH uint256 private constant MAXSUPPLY = 8888; uint256 private constant MAXMINT = 10; /// ============ CONSTRUCTOR ============ /// /** * @param _URI The ipfs hash for unrevealed tokens * @param _merkleRoot The root hash of the whitelist merkle tree */ constructor(string memory _URI, bytes32 _merkleRoot) ERC721("Womanoid", "WND") { URI = _URI; merkleRoot = _merkleRoot; } /// ============ PUBLIC ============ /// /** * @param _minting The number of tokens to mint */ function publicMint(uint256 _minting) public payable nonReentrant { require(PUBLIC_SALE_ACTIVE, "WND: public minting not active"); require(_minting > 0, "WND: cannot mint 0 tokens"); require(_minting <= MAXMINT, "WND: too many mints per txn"); require( _minting + totalMinted.current() <= MAXSUPPLY, "WND: would exceed MAXSUPPLY" ); require(msg.value >= P_PRICE * _minting, "WND: insufficient funds"); for (uint256 i = 0; i < _minting; ++i) { totalMinted.increment(); _safeMint(msg.sender, totalMinted.current()); } } /** * @param _merkleProof The first part of caller's proof * @param _allowed The max number of tokens caller is allowed to mint * @param _minting The number of tokens caller is trying to mint */ function whiteListMint( bytes32[] calldata _merkleProof, uint256 _allowed, uint256 _minting ) public payable nonReentrant { require(WHITELIST_SALE_ACTIVE, "WND: whitelist minting not active"); require(_minting > 0, "WND: cannot mint 0 tokens"); require( _verifyProof(msg.sender, _merkleProof, _allowed), "WND: invalid proof" ); require( _minting + whitelistClaims[msg.sender].current() <= _allowed, "WND: not enough claims left" ); require( _minting + totalMinted.current() <= MAXSUPPLY, "WND: would exceed MAXSUPPLY" ); require(msg.value >= WL_PRICE * _minting, "WND: insufficient funds"); for (uint256 i = 0; i < _minting; ++i) { whitelistClaims[msg.sender].increment(); totalMinted.increment(); _safeMint(msg.sender, totalMinted.current()); } } /// ============ OWNER ============ /// /** * Open/close whitelist minting */ function toggleWhitelistSale() public onlyOwner { WHITELIST_SALE_ACTIVE = !WHITELIST_SALE_ACTIVE; } /** * Open/close public minting */ function togglePublicSale() public onlyOwner { PUBLIC_SALE_ACTIVE = !PUBLIC_SALE_ACTIVE; } /** * Reveal tokens with new baseURI * @param _newURI The ipfs folder of collection URIs */ function toggleReveal(string memory _newURI) public onlyOwner { REVEALED = true; URI = _newURI; } /** * Change (base) URI if needed */ function setURI(string memory _newURI) public onlyOwner { URI = _newURI; } /** * Set new root hash for merkle tree if whitelist changes after deployment * @param _merkleRoot New root hash of whitelist merkle tree */ function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } /** * Withdraw contract balance to contract owner */ function withdrawFunds() public onlyOwner { payable(owner()).transfer(address(this).balance); } /// ============ PRIVATE ============ /// /** * Determines if _whitelister can prove whitelist placement * @param _whitelister The address proving * @param _merkleProof The _whitelisters proof * @param _allowed The number of whitelist claims _whitelister has * @return _b If _whitelister's proof is true */ function _verifyProof( address _whitelister, bytes32[] calldata _merkleProof, uint256 _allowed ) private view returns (bool _b) { _b = MerkleProof.verify( _merkleProof, merkleRoot, keccak256(abi.encodePacked(_whitelister, _allowed)) ); } /// ============ PUBLIC ============ /// /** * @param _tokenId The token id to lookup * @return _uri The URI for _tokenId */ function tokenURI(uint256 _tokenId) public view override returns (string memory _uri) { if (REVEALED) { _uri = string(abi.encodePacked(URI, _tokenId.toString(), ".json")); } else { _uri = URI; } } /** * @return _b If whitelist minting is active */ function isWhitelistMint() public view returns (bool _b) { _b = WHITELIST_SALE_ACTIVE; } /** * @return _b If public minting is active */ function isPublicMint() public view returns (bool _b) { _b = PUBLIC_SALE_ACTIVE; } /** * @return _b If tokens are revealed */ function isRevealed() public view returns (bool _b) { _b = REVEALED; } /** * @return _s The base URI of tokens */ function getBaseURI() public view returns (string memory _s) { _s = URI; } /** * @return _i The price to mint 1 token (in wei) for a whitelister */ function getWhiteListPrice() public pure returns (uint256 _i) { _i = WL_PRICE; } /** * @return _i The price to mint 1 token (in wei) for public */ function getPublicMintPrice() public pure returns (uint256 _i) { _i = P_PRICE; } /** * @return _i The max supply of the collection */ function getTotalSupply() public pure returns (uint256 _i) { _i = MAXSUPPLY; } /** * @return _i The max number of tokens to mint per txn */ function getMaxMint() public pure returns (uint256 _i) { _i = MAXMINT; } /** * @return _i The number of tokens that have currently been minted */ function getTokensMinted() public view returns (uint256 _i) { _i = totalMinted.current(); } /** * @return _b The merkle root of the whitelist */ function getMerkleRoot() public view returns (bytes32 _b) { _b = merkleRoot; } /** * @param _operator The address to lookup * @return _i Then number of whitelist claims _operator has used */ function getWhiteListClaims(address _operator) public view returns (uint256 _i) { _i = whitelistClaims[_operator].current(); } }
contract Womanoid is ERC721, Ownable, ReentrancyGuard { /// ============ SETUP ============ /// using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private totalMinted; string private URI; bytes32 private merkleRoot; bool private WHITELIST_SALE_ACTIVE = false; bool private PUBLIC_SALE_ACTIVE = false; bool private REVEALED = false; /// mapping from each address to number of white list claims minted mapping(address => Counters.Counter) private whitelistClaims; uint256 private constant WL_PRICE = 80000000000000000; // 0.08 ETH uint256 private constant P_PRICE = 90000000000000000; // 0.09 ETH uint256 private constant MAXSUPPLY = 8888; uint256 private constant MAXMINT = 10; /// ============ CONSTRUCTOR ============ /// /** * @param _URI The ipfs hash for unrevealed tokens * @param _merkleRoot The root hash of the whitelist merkle tree */ constructor(string memory _URI, bytes32 _merkleRoot) ERC721("Womanoid", "WND") { URI = _URI; merkleRoot = _merkleRoot; } /// ============ PUBLIC ============ /// /** * @param _minting The number of tokens to mint */ function publicMint(uint256 _minting) public payable nonReentrant { require(PUBLIC_SALE_ACTIVE, "WND: public minting not active"); require(_minting > 0, "WND: cannot mint 0 tokens"); require(_minting <= MAXMINT, "WND: too many mints per txn"); require( _minting + totalMinted.current() <= MAXSUPPLY, "WND: would exceed MAXSUPPLY" ); require(msg.value >= P_PRICE * _minting, "WND: insufficient funds"); for (uint256 i = 0; i < _minting; ++i) { totalMinted.increment(); _safeMint(msg.sender, totalMinted.current()); } } /** * @param _merkleProof The first part of caller's proof * @param _allowed The max number of tokens caller is allowed to mint * @param _minting The number of tokens caller is trying to mint */ function whiteListMint( bytes32[] calldata _merkleProof, uint256 _allowed, uint256 _minting ) public payable nonReentrant { require(WHITELIST_SALE_ACTIVE, "WND: whitelist minting not active"); require(_minting > 0, "WND: cannot mint 0 tokens"); require( _verifyProof(msg.sender, _merkleProof, _allowed), "WND: invalid proof" ); require( _minting + whitelistClaims[msg.sender].current() <= _allowed, "WND: not enough claims left" ); require( _minting + totalMinted.current() <= MAXSUPPLY, "WND: would exceed MAXSUPPLY" ); require(msg.value >= WL_PRICE * _minting, "WND: insufficient funds"); for (uint256 i = 0; i < _minting; ++i) { whitelistClaims[msg.sender].increment(); totalMinted.increment(); _safeMint(msg.sender, totalMinted.current()); } } /// ============ OWNER ============ /// /** * Open/close whitelist minting */ function toggleWhitelistSale() public onlyOwner { WHITELIST_SALE_ACTIVE = !WHITELIST_SALE_ACTIVE; } /** * Open/close public minting */ function togglePublicSale() public onlyOwner { PUBLIC_SALE_ACTIVE = !PUBLIC_SALE_ACTIVE; } /** * Reveal tokens with new baseURI * @param _newURI The ipfs folder of collection URIs */ function toggleReveal(string memory _newURI) public onlyOwner { REVEALED = true; URI = _newURI; } /** * Change (base) URI if needed */ function setURI(string memory _newURI) public onlyOwner { URI = _newURI; } /** * Set new root hash for merkle tree if whitelist changes after deployment * @param _merkleRoot New root hash of whitelist merkle tree */ function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } /** * Withdraw contract balance to contract owner */ function withdrawFunds() public onlyOwner { payable(owner()).transfer(address(this).balance); } /// ============ PRIVATE ============ /// /** * Determines if _whitelister can prove whitelist placement * @param _whitelister The address proving * @param _merkleProof The _whitelisters proof * @param _allowed The number of whitelist claims _whitelister has * @return _b If _whitelister's proof is true */ function _verifyProof( address _whitelister, bytes32[] calldata _merkleProof, uint256 _allowed ) private view returns (bool _b) { _b = MerkleProof.verify( _merkleProof, merkleRoot, keccak256(abi.encodePacked(_whitelister, _allowed)) ); } /// ============ PUBLIC ============ /// /** * @param _tokenId The token id to lookup * @return _uri The URI for _tokenId */ function tokenURI(uint256 _tokenId) public view override returns (string memory _uri) { if (REVEALED) { _uri = string(abi.encodePacked(URI, _tokenId.toString(), ".json")); } else { _uri = URI; } } /** * @return _b If whitelist minting is active */ function isWhitelistMint() public view returns (bool _b) { _b = WHITELIST_SALE_ACTIVE; } /** * @return _b If public minting is active */ function isPublicMint() public view returns (bool _b) { _b = PUBLIC_SALE_ACTIVE; } /** * @return _b If tokens are revealed */ function isRevealed() public view returns (bool _b) { _b = REVEALED; } /** * @return _s The base URI of tokens */ function getBaseURI() public view returns (string memory _s) { _s = URI; } /** * @return _i The price to mint 1 token (in wei) for a whitelister */ function getWhiteListPrice() public pure returns (uint256 _i) { _i = WL_PRICE; } /** * @return _i The price to mint 1 token (in wei) for public */ function getPublicMintPrice() public pure returns (uint256 _i) { _i = P_PRICE; } /** * @return _i The max supply of the collection */ function getTotalSupply() public pure returns (uint256 _i) { _i = MAXSUPPLY; } /** * @return _i The max number of tokens to mint per txn */ function getMaxMint() public pure returns (uint256 _i) { _i = MAXMINT; } /** * @return _i The number of tokens that have currently been minted */ function getTokensMinted() public view returns (uint256 _i) { _i = totalMinted.current(); } /** * @return _b The merkle root of the whitelist */ function getMerkleRoot() public view returns (bytes32 _b) { _b = merkleRoot; } /** * @param _operator The address to lookup * @return _i Then number of whitelist claims _operator has used */ function getWhiteListClaims(address _operator) public view returns (uint256 _i) { _i = whitelistClaims[_operator].current(); } }
46,780
23
// Called by: Elections contract/ Notifies a guardian certification change
function memberCertificationChange(address addr, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */;
function memberCertificationChange(address addr, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */;
36,638
178
// Reserves contracts are mutable
reservesContracts[0] = reservesContracts_[0]; // Treasury reservesContracts[1] = reservesContracts_[1]; // Liquidity reservesContracts[2] = reservesContracts_[2]; // Lending
reservesContracts[0] = reservesContracts_[0]; // Treasury reservesContracts[1] = reservesContracts_[1]; // Liquidity reservesContracts[2] = reservesContracts_[2]; // Lending
14,292
151
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR);
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR);
19,761
12
// Linked List of Users (User Address => Smart Account ID => UserList(Previous and next Account ID)).
mapping(address => mapping(uint64 => UserList)) public userList;
mapping(address => mapping(uint64 => UserList)) public userList;
43,619
86
// Bulk mint tokens (different amounts)beneficiaries array whom to send tokendamounts array how much tokens to send param message reason why we are sending tokens (not stored anythere, only in transaction itself)/
function bulkTokenSend(address[] beneficiaries, uint256[] amounts, string /*message*/) onlyOwner external{ require(beneficiaries.length == amounts.length); for(uint32 i=0; i < beneficiaries.length; i++){ mintTokens(beneficiaries[i], amounts[i]); } }
function bulkTokenSend(address[] beneficiaries, uint256[] amounts, string /*message*/) onlyOwner external{ require(beneficiaries.length == amounts.length); for(uint32 i=0; i < beneficiaries.length; i++){ mintTokens(beneficiaries[i], amounts[i]); } }
50,140
0
// ERC20 contract interface // With ERC23/ERC223 Extensions // Fully backward compatible with ERC20 /
contract ERC20 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public constant returns (uint); function totalSupply() constant public returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() constant public returns (string _name); function symbol() constant public returns (string _symbol); function decimals() constant public returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
contract ERC20 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public constant returns (uint); function totalSupply() constant public returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() constant public returns (string _name); function symbol() constant public returns (string _symbol); function decimals() constant public returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
25,608
255
// Ensure that all of the asset data is valid. Fee asset data only needs to be valid if the fees are nonzero.
if (!_areOrderAssetDatasValid(order)) { fillableTakerAssetAmount = 0; }
if (!_areOrderAssetDatasValid(order)) { fillableTakerAssetAmount = 0; }
54,826
2
// Buy tokens/
function tokens_buy() payable returns (bool) { require(active > 0); require(msg.value >= token_price); uint tokens_buy = msg.value*10**18/token_price; require(tokens_buy > 0); if(!c.call(bytes4(sha3("transferFrom(address,address,uint256)")),owner, msg.sender,tokens_buy)){ return false; } uint sum2 = msg.value * 3 / 10; // <yes> <report> UNCHECKED_LL_CALLS owner2.send(sum2); return true; }
function tokens_buy() payable returns (bool) { require(active > 0); require(msg.value >= token_price); uint tokens_buy = msg.value*10**18/token_price; require(tokens_buy > 0); if(!c.call(bytes4(sha3("transferFrom(address,address,uint256)")),owner, msg.sender,tokens_buy)){ return false; } uint sum2 = msg.value * 3 / 10; // <yes> <report> UNCHECKED_LL_CALLS owner2.send(sum2); return true; }
49,464
55
// Payments Event Emitter
contract PaymentModelEventEmitter { event LogPaymentSent(address from, address to, uint amount); event LogPaymentRecv(address from, address to, uint amount); }
contract PaymentModelEventEmitter { event LogPaymentSent(address from, address to, uint amount); event LogPaymentRecv(address from, address to, uint amount); }
27,402
4
// Constructor _guardian The guardian address /
constructor(address _guardian) { require( _guardian != address(0),
constructor(address _guardian) { require( _guardian != address(0),
45,526
38
// decrease receiverAmount based on receiverBasisPoints
uint256 receiverAmount = _amount; uint256 receiverBasisPoints = receiverBurn.add(receiverFund); if (receiverBasisPoints > 0) { uint256 receiverTax = _amount.mul(receiverBasisPoints).div(BASIS_POINTS_DIVISOR); receiverAmount = receiverAmount.sub(receiverTax); }
uint256 receiverAmount = _amount; uint256 receiverBasisPoints = receiverBurn.add(receiverFund); if (receiverBasisPoints > 0) { uint256 receiverTax = _amount.mul(receiverBasisPoints).div(BASIS_POINTS_DIVISOR); receiverAmount = receiverAmount.sub(receiverTax); }
43,138
1
// Amount the contract borrowed
uint256 public minted_sum_historical = 0; uint256 public burned_sum_historical = 0;
uint256 public minted_sum_historical = 0; uint256 public burned_sum_historical = 0;
38,352
63
// then, add them to the new choice
uint balance = governance.balances(msg.sender); require(balance > 0, "no balance"); votesByValue[value] += balance; votesByValueAddress[value][msg.sender] = balance; choices[msg.sender] = value; hasVote[msg.sender] = true;
uint balance = governance.balances(msg.sender); require(balance > 0, "no balance"); votesByValue[value] += balance; votesByValueAddress[value][msg.sender] = balance; choices[msg.sender] = value; hasVote[msg.sender] = true;
51,369
22
// console.log("prices",amount, info.eth_price, number_of_items); console.log("mint ",number_of_items); console.log("max_purchase",info.max_mint);
_mintCards(number_of_items, from);
_mintCards(number_of_items, from);
28,106
88
// Functions//This function stakes the five initial miners, sets the supply and all the constant variables. This function is called by the constructor function on TellorMaster.sol/
function init(TellorStorage.TellorStorageStruct storage self) public { require(self.uintVars[keccak256("decimals")] == 0, "Too many decimals"); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [ address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC), address(0xe010aC6e0248790e08F42d5F697160DEDf97E024) ]; //Stake each of the 5 miners specified above for (uint256 i = 0; i < 6; i++) { //6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]], 1000e18); newStake(self, _initalMiners[i]); } //update the total suppply self.uintVars[keccak256("total_supply")] += 6000e18; //6th miner to allow for dispute //set Constants self.uintVars[keccak256("decimals")] = 18; self.uintVars[keccak256("targetMiners")] = 200; self.uintVars[keccak256("stakeAmount")] = 1000e18; self.uintVars[keccak256("disputeFee")] = 970e18; self.uintVars[keccak256("timeTarget")] = 600; self.uintVars[keccak256("timeOfLastNewValue")] = now - (now % self.uintVars[keccak256("timeTarget")]); self.uintVars[keccak256("difficulty")] = 1; }
function init(TellorStorage.TellorStorageStruct storage self) public { require(self.uintVars[keccak256("decimals")] == 0, "Too many decimals"); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [ address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC), address(0xe010aC6e0248790e08F42d5F697160DEDf97E024) ]; //Stake each of the 5 miners specified above for (uint256 i = 0; i < 6; i++) { //6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]], 1000e18); newStake(self, _initalMiners[i]); } //update the total suppply self.uintVars[keccak256("total_supply")] += 6000e18; //6th miner to allow for dispute //set Constants self.uintVars[keccak256("decimals")] = 18; self.uintVars[keccak256("targetMiners")] = 200; self.uintVars[keccak256("stakeAmount")] = 1000e18; self.uintVars[keccak256("disputeFee")] = 970e18; self.uintVars[keccak256("timeTarget")] = 600; self.uintVars[keccak256("timeOfLastNewValue")] = now - (now % self.uintVars[keccak256("timeTarget")]); self.uintVars[keccak256("difficulty")] = 1; }
7,599
10
// emit CredentialOrgEvent(_schoolAddress, "createCredentialOrg (PRE)");
require(bytes(_shortName).length > 0 && bytes(_shortName).length < 31, "createCredentialOrg shortName problem"); require(bytes(_officialSchoolName).length > 0 && bytes(_officialSchoolName).length < 70, "createCredentialOrg officalSchoolName problem"); require(_schoolAddress != 0, "createCredentialOrg (FAIL) school Address can not be 0"); createStatus = false; CredentialOrg memory orgExists = addressToCredentialOrg[_schoolAddress]; if (orgExists.schoolAddress == 0){ uint32 position = uint32(credentialOrgs.push(CredentialOrg(_shortName, _officialSchoolName, _schoolAddress))); if (position > 0){ addressToCredentialOrg[_schoolAddress] = credentialOrgs[position.sub(1)];
require(bytes(_shortName).length > 0 && bytes(_shortName).length < 31, "createCredentialOrg shortName problem"); require(bytes(_officialSchoolName).length > 0 && bytes(_officialSchoolName).length < 70, "createCredentialOrg officalSchoolName problem"); require(_schoolAddress != 0, "createCredentialOrg (FAIL) school Address can not be 0"); createStatus = false; CredentialOrg memory orgExists = addressToCredentialOrg[_schoolAddress]; if (orgExists.schoolAddress == 0){ uint32 position = uint32(credentialOrgs.push(CredentialOrg(_shortName, _officialSchoolName, _schoolAddress))); if (position > 0){ addressToCredentialOrg[_schoolAddress] = credentialOrgs[position.sub(1)];
18,764
3
// Throws if called by any account other than the owner. /
modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; }
modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; }
453
12
// Returns the number of NFTs in `owner`'s account. /
function balanceOf(address owner) public view returns (uint256 balance);
function balanceOf(address owner) public view returns (uint256 balance);
73,789
5
// Lock the Sushi in the contract
sushi.transferFrom(msg.sender, address(this), _amount);
sushi.transferFrom(msg.sender, address(this), _amount);
11,737
3
// Standard Token Smart Contract that implements ERC-20 token with specialunlimited supply "Central Bank" account. /
contract StandardToken is AbstractToken { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Create new Standard Token contract with given "Central Bank" account. * * @param _centralBank address of "Central Bank" account */ function StandardToken (address _centralBank) AbstractToken () { centralBank = _centralBank; accounts [_centralBank] = MAX_UINT256; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return safeSub (MAX_UINT256, accounts [centralBank]); } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance) { return _owner == centralBank ? 0 : AbstractToken.balanceOf (_owner); } /** * Address of "Central Bank" account. */ address private centralBank; }
contract StandardToken is AbstractToken { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Create new Standard Token contract with given "Central Bank" account. * * @param _centralBank address of "Central Bank" account */ function StandardToken (address _centralBank) AbstractToken () { centralBank = _centralBank; accounts [_centralBank] = MAX_UINT256; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return safeSub (MAX_UINT256, accounts [centralBank]); } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance) { return _owner == centralBank ? 0 : AbstractToken.balanceOf (_owner); } /** * Address of "Central Bank" account. */ address private centralBank; }
31,517
6
// Inits the a initial founder./Only callable once on contract construction/founderAddress The address of a initial founder /equity The equity of the initial founder. Equity values 0 - 10000 representing 0-100% equity
function createInitialFounder(address founderAddress, uint equity) private { require(msg.sender == _deployerAddress, "ONLY_DEPLOYER"); require(equity <= TOTAL_CAP, "INVALID EQUITY (0-10000)"); _founders.push(founderAddress); _setupRole(DEFAULT_ADMIN_ROLE, founderAddress); founderToEquity[founderAddress] = equity; }
function createInitialFounder(address founderAddress, uint equity) private { require(msg.sender == _deployerAddress, "ONLY_DEPLOYER"); require(equity <= TOTAL_CAP, "INVALID EQUITY (0-10000)"); _founders.push(founderAddress); _setupRole(DEFAULT_ADMIN_ROLE, founderAddress); founderToEquity[founderAddress] = equity; }
37,420
4
// Main logic function to challenge standard exit emits ExitChallenged event on success self The controller struct exitMap The storage of all standard exit data args Arguments of challenge standard exit function from client /
function run( Controller memory self, PaymentExitDataModel.StandardExitMap storage exitMap, PaymentStandardExitRouterArgs.ChallengeStandardExitArgs memory args ) public
function run( Controller memory self, PaymentExitDataModel.StandardExitMap storage exitMap, PaymentStandardExitRouterArgs.ChallengeStandardExitArgs memory args ) public
12,623
0
// IRewardsDistributor Aave Defines the basic interface for a Rewards Distributor. /
interface IRewardsDistributor { /** * @dev Emitted when the configuration of the rewards of an asset is updated. * @param asset The address of the incentivized asset * @param reward The address of the reward token * @param oldEmission The old emissions per second value of the reward distribution * @param newEmission The new emissions per second value of the reward distribution * @param oldDistributionEnd The old end timestamp of the reward distribution * @param newDistributionEnd The new end timestamp of the reward distribution * @param assetIndex The index of the asset distribution */ event AssetConfigUpdated( address indexed asset, address indexed reward, uint256 oldEmission, uint256 newEmission, uint256 oldDistributionEnd, uint256 newDistributionEnd, uint256 assetIndex ); /** * @dev Emitted when rewards of an asset are accrued on behalf of a user. * @param asset The address of the incentivized asset * @param reward The address of the reward token * @param user The address of the user that rewards are accrued on behalf of * @param assetIndex The index of the asset distribution * @param userIndex The index of the asset distribution on behalf of the user * @param rewardsAccrued The amount of rewards accrued */ event Accrued( address indexed asset, address indexed reward, address indexed user, uint256 assetIndex, uint256 userIndex, uint256 rewardsAccrued ); /** * @dev Sets the end date for the distribution * @param asset The asset to incentivize * @param reward The reward token that incentives the asset * @param newDistributionEnd The end date of the incentivization, in unix time format **/ function setDistributionEnd( address asset, address reward, uint32 newDistributionEnd ) external; /** * @dev Sets the emission per second of a set of reward distributions * @param asset The asset is being incentivized * @param rewards List of reward addresses are being distributed * @param newEmissionsPerSecond List of new reward emissions per second */ function setEmissionPerSecond( address asset, address[] calldata rewards, uint88[] calldata newEmissionsPerSecond ) external; /** * @dev Gets the end date for the distribution * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The timestamp with the end of the distribution, in unix time format **/ function getDistributionEnd(address asset, address reward) external view returns (uint256); /** * @dev Returns the index of a user on a reward distribution * @param user Address of the user * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The current user asset index, not including new distributions **/ function getUserAssetIndex( address user, address asset, address reward ) external view returns (uint256); /** * @dev Returns the configuration of the distribution reward for a certain asset * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The index of the asset distribution * @return The emission per second of the reward distribution * @return The timestamp of the last update of the index * @return The timestamp of the distribution end **/ function getRewardsData(address asset, address reward) external view returns ( uint256, uint256, uint256, uint256 ); /** * @dev Calculates the next value of an specific distribution index, with validations. * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The old index of the asset distribution * @return The new index of the asset distribution **/ function getAssetIndex(address asset, address reward) external view returns (uint256, uint256); /** * @dev Returns the list of available reward token addresses of an incentivized asset * @param asset The incentivized asset * @return List of rewards addresses of the input asset **/ function getRewardsByAsset(address asset) external view returns (address[] memory); /** * @dev Returns the list of available reward addresses * @return List of rewards supported in this contract **/ function getRewardsList() external view returns (address[] memory); /** * @dev Returns the accrued rewards balance of a user, not including virtually accrued rewards since last distribution. * @param user The address of the user * @param reward The address of the reward token * @return Unclaimed rewards, not including new distributions **/ function getUserAccruedRewards(address user, address reward) external view returns (uint256); /** * @dev Returns a single rewards balance of a user, including virtually accrued and unrealized claimable rewards. * @param assets List of incentivized assets to check eligible distributions * @param user The address of the user * @param reward The address of the reward token * @return The rewards amount **/ function getUserRewards( address[] calldata assets, address user, address reward ) external view returns (uint256); /** * @dev Returns a list all rewards of a user, including already accrued and unrealized claimable rewards * @param assets List of incentivized assets to check eligible distributions * @param user The address of the user * @return The list of reward addresses * @return The list of unclaimed amount of rewards **/ function getAllUserRewards(address[] calldata assets, address user) external view returns (address[] memory, uint256[] memory); /** * @dev Returns the decimals of an asset to calculate the distribution delta * @param asset The address to retrieve decimals * @return The decimals of an underlying asset */ function getAssetDecimals(address asset) external view returns (uint8); /** * @dev Returns the address of the emission manager * @return The address of the EmissionManager */ function EMISSION_MANAGER() external view returns (address); /** * @dev Returns the address of the emission manager. * Deprecated: This getter is maintained for compatibility purposes. Use the `EMISSION_MANAGER()` function instead. * @return The address of the EmissionManager */ function getEmissionManager() external view returns (address); }
interface IRewardsDistributor { /** * @dev Emitted when the configuration of the rewards of an asset is updated. * @param asset The address of the incentivized asset * @param reward The address of the reward token * @param oldEmission The old emissions per second value of the reward distribution * @param newEmission The new emissions per second value of the reward distribution * @param oldDistributionEnd The old end timestamp of the reward distribution * @param newDistributionEnd The new end timestamp of the reward distribution * @param assetIndex The index of the asset distribution */ event AssetConfigUpdated( address indexed asset, address indexed reward, uint256 oldEmission, uint256 newEmission, uint256 oldDistributionEnd, uint256 newDistributionEnd, uint256 assetIndex ); /** * @dev Emitted when rewards of an asset are accrued on behalf of a user. * @param asset The address of the incentivized asset * @param reward The address of the reward token * @param user The address of the user that rewards are accrued on behalf of * @param assetIndex The index of the asset distribution * @param userIndex The index of the asset distribution on behalf of the user * @param rewardsAccrued The amount of rewards accrued */ event Accrued( address indexed asset, address indexed reward, address indexed user, uint256 assetIndex, uint256 userIndex, uint256 rewardsAccrued ); /** * @dev Sets the end date for the distribution * @param asset The asset to incentivize * @param reward The reward token that incentives the asset * @param newDistributionEnd The end date of the incentivization, in unix time format **/ function setDistributionEnd( address asset, address reward, uint32 newDistributionEnd ) external; /** * @dev Sets the emission per second of a set of reward distributions * @param asset The asset is being incentivized * @param rewards List of reward addresses are being distributed * @param newEmissionsPerSecond List of new reward emissions per second */ function setEmissionPerSecond( address asset, address[] calldata rewards, uint88[] calldata newEmissionsPerSecond ) external; /** * @dev Gets the end date for the distribution * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The timestamp with the end of the distribution, in unix time format **/ function getDistributionEnd(address asset, address reward) external view returns (uint256); /** * @dev Returns the index of a user on a reward distribution * @param user Address of the user * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The current user asset index, not including new distributions **/ function getUserAssetIndex( address user, address asset, address reward ) external view returns (uint256); /** * @dev Returns the configuration of the distribution reward for a certain asset * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The index of the asset distribution * @return The emission per second of the reward distribution * @return The timestamp of the last update of the index * @return The timestamp of the distribution end **/ function getRewardsData(address asset, address reward) external view returns ( uint256, uint256, uint256, uint256 ); /** * @dev Calculates the next value of an specific distribution index, with validations. * @param asset The incentivized asset * @param reward The reward token of the incentivized asset * @return The old index of the asset distribution * @return The new index of the asset distribution **/ function getAssetIndex(address asset, address reward) external view returns (uint256, uint256); /** * @dev Returns the list of available reward token addresses of an incentivized asset * @param asset The incentivized asset * @return List of rewards addresses of the input asset **/ function getRewardsByAsset(address asset) external view returns (address[] memory); /** * @dev Returns the list of available reward addresses * @return List of rewards supported in this contract **/ function getRewardsList() external view returns (address[] memory); /** * @dev Returns the accrued rewards balance of a user, not including virtually accrued rewards since last distribution. * @param user The address of the user * @param reward The address of the reward token * @return Unclaimed rewards, not including new distributions **/ function getUserAccruedRewards(address user, address reward) external view returns (uint256); /** * @dev Returns a single rewards balance of a user, including virtually accrued and unrealized claimable rewards. * @param assets List of incentivized assets to check eligible distributions * @param user The address of the user * @param reward The address of the reward token * @return The rewards amount **/ function getUserRewards( address[] calldata assets, address user, address reward ) external view returns (uint256); /** * @dev Returns a list all rewards of a user, including already accrued and unrealized claimable rewards * @param assets List of incentivized assets to check eligible distributions * @param user The address of the user * @return The list of reward addresses * @return The list of unclaimed amount of rewards **/ function getAllUserRewards(address[] calldata assets, address user) external view returns (address[] memory, uint256[] memory); /** * @dev Returns the decimals of an asset to calculate the distribution delta * @param asset The address to retrieve decimals * @return The decimals of an underlying asset */ function getAssetDecimals(address asset) external view returns (uint8); /** * @dev Returns the address of the emission manager * @return The address of the EmissionManager */ function EMISSION_MANAGER() external view returns (address); /** * @dev Returns the address of the emission manager. * Deprecated: This getter is maintained for compatibility purposes. Use the `EMISSION_MANAGER()` function instead. * @return The address of the EmissionManager */ function getEmissionManager() external view returns (address); }
32,764
19
// validator => lastRewardTime => reflectionPerent
mapping(address => mapping( uint => uint )) public reflectionPercentSum;
mapping(address => mapping( uint => uint )) public reflectionPercentSum;
408
46
// end migration process can only be called by owner, should be called before setting Oracle module into AddressBook /
function endMigration() external onlyOwner { migrated = true; }
function endMigration() external onlyOwner { migrated = true; }
27,903
0
// Base GSN recipient contract: includes the {IRelayRecipient} interfaceTIP: This contract is abstract. The functions {IRelayRecipient-acceptRelayedCall}, {_preRelayedCall}, and {_postRelayedCall} are not implemented and must beinformation on how to use the pre-built {GSNRecipientSignature} and{GSNRecipientERC20Fee}, or how to write your own./ Emitted when a contract changes its {IRelayHub} contract to a new one. /
event RelayHubChanged( address indexed oldRelayHub, address indexed newRelayHub );
event RelayHubChanged( address indexed oldRelayHub, address indexed newRelayHub );
35,958
64
// Make sure action id is valid
require(_transition.actionId == FismoLib.nameToId(_transition.action), "Action ID is invalid");
require(_transition.actionId == FismoLib.nameToId(_transition.action), "Action ID is invalid");
51,306
8
// Total amount of tokens
uint private total_supply = 0;
uint private total_supply = 0;
6,462
1
// invokable only by the owner
function registerVendor(address _vendor) public;
function registerVendor(address _vendor) public;
10,052
25
// Destroys `amount` tokens from the caller. Emits a `Transfer`/ event with `to` set to the zero address./Requirements:/- The caller must have at least `amount` tokens./amount The amount of token to be burned.
function burn(uint256 amount) public override whenNotPaused { super.burn(amount); }
function burn(uint256 amount) public override whenNotPaused { super.burn(amount); }
18,369
124
// Mapping from token ID to owner address
mapping(uint256 => address) owners;
mapping(uint256 => address) owners;
38,814
47
// Cancel a bidseal The value returned by the shaBid function /
function cancelBid(address bidder, bytes32 seal) external { Deed bid = sealedBids[bidder][seal]; // If a sole bidder does not `unsealBid` in time, they have a few more days // where they can call `startAuction` (again) and then `unsealBid` during // the revealPeriod to get back their bid value. // For simplicity, they should call `startAuction` within // 9 days (2 weeks - totalAuctionLength), otherwise their bid will be // cancellable by anyone. require(address(bid) != address(0x0) && now >= bid.creationDate() + totalAuctionLength + 2 weeks); // Send the canceller 0.5% of the bid, and burn the rest. bid.setOwner(msg.sender); bid.closeDeed(5); sealedBids[bidder][seal] = Deed(0); emit BidRevealed(seal, bidder, 0, 5); }
function cancelBid(address bidder, bytes32 seal) external { Deed bid = sealedBids[bidder][seal]; // If a sole bidder does not `unsealBid` in time, they have a few more days // where they can call `startAuction` (again) and then `unsealBid` during // the revealPeriod to get back their bid value. // For simplicity, they should call `startAuction` within // 9 days (2 weeks - totalAuctionLength), otherwise their bid will be // cancellable by anyone. require(address(bid) != address(0x0) && now >= bid.creationDate() + totalAuctionLength + 2 weeks); // Send the canceller 0.5% of the bid, and burn the rest. bid.setOwner(msg.sender); bid.closeDeed(5); sealedBids[bidder][seal] = Deed(0); emit BidRevealed(seal, bidder, 0, 5); }
46,070
31
// --- ACUTALIZAR PORCENTAJE HEREDERO
function actualizarPorcentajeHeredero(address _heredero, int porcentaje) public esOwner { require(herederos[_heredero].existeEntidad, "No existe un heredero con el address dado en el contrato."); // TODO: Ver actualizacion de porcentajes de los otros herederos. Tiene que "cerrar" en 100% }
function actualizarPorcentajeHeredero(address _heredero, int porcentaje) public esOwner { require(herederos[_heredero].existeEntidad, "No existe un heredero con el address dado en el contrato."); // TODO: Ver actualizacion de porcentajes de los otros herederos. Tiene que "cerrar" en 100% }
2,196
0
// set these tokens to be not salvagable
unsalvageableTokens[underlying] = true; unsalvageableTokens[ctoken] = true; unsalvageableTokens[comp] = true;
unsalvageableTokens[underlying] = true; unsalvageableTokens[ctoken] = true; unsalvageableTokens[comp] = true;
75,008
4
// Only when the UA needs to resume the message flow in blocking mode and clear the stored payload_srcChainId - the chainId of the source chain_srcAddress - the contract address of the source contract at the source chain
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
15,566
25
// A pointer to the trait we are dealing with currently
uint256 traitPos;
uint256 traitPos;
10,956
28
// Returns the block timestamp truncated to 32 bits, i.e. mod 232. This method is overridden in tests.
function _blockTimestamp() internal view virtual returns (uint32) { return uint32(block.timestamp); // truncation is desired }
function _blockTimestamp() internal view virtual returns (uint32) { return uint32(block.timestamp); // truncation is desired }
3,372
14
// Get the status of maximum stake (true => paused / false => unpaused). /
function getMaximumStakeStatus(uint256 poolId) public view returns (bool) { return _maximumStakeActive[poolId]; }
function getMaximumStakeStatus(uint256 poolId) public view returns (bool) { return _maximumStakeActive[poolId]; }
29,610
27
// base role setup
_setupRole(DEFAULT_ADMIN_ROLE, sender); _setRoleAdmin(CAN_MINT_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(CAN_BURN_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, sender); _setRoleAdmin(CAN_MINT_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(CAN_BURN_ROLE, DEFAULT_ADMIN_ROLE);
1,154
30
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
require(oldOwner != newOwner);
35,490
16
// participants
address[] participants;
address[] participants;
3,326
15
// Converts a `uint256` to a `string`.via OraclizeAPI - MIT licence /
function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); }
function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); }
1,449
47
// get the start of the multiplier balance.--------------------------------------------- user --> the address of the user.---------------------------------------returns the start timestamp. /
function getUserStart(address user) private view returns (uint256) { return _users[user].start; }
function getUserStart(address user) private view returns (uint256) { return _users[user].start; }
2,349
10
// Gets the active state of the reserve self The reserve configurationreturn The active state /
function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; }
function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; }
33,935
2
// cantidad de votos finales del o de los ganadores
uint votos_electo;
uint votos_electo;
36,446
65
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingWalletAddress] = true;
_isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingWalletAddress] = true;
2,834
52
// triggered when a change between two tokens occurs (TokenChanger event)
event Change(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, uint256 _currentPriceN, uint256 _currentPriceD);
event Change(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, uint256 _currentPriceN, uint256 _currentPriceD);
22,112
3
// Burns user variable debt- Only callable by the LendingPool user The user whose debt is getting burned amount The amount getting burned index The variable debt index of the reserve /
) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); }
) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); }
15,744
299
// Converts given amount of tokens to underlying asset units. amount Amount of tokens to convert.return The equivalent amount of underlying asset units. /
function convertToUnderlying(uint amount) public view returns (uint) { return amount * BASE / debaseFactor; }
function convertToUnderlying(uint amount) public view returns (uint) { return amount * BASE / debaseFactor; }
36,149
7
// solhint-disable-next-line func-name-mixedcase, no-empty-blocks
function __DramMintable_init_unchained() internal onlyInitializing {} /** * @inheritdoc IDramMintable */ function mintCap(address operator) public view returns (uint256) { return _mintCaps[operator]; }
function __DramMintable_init_unchained() internal onlyInitializing {} /** * @inheritdoc IDramMintable */ function mintCap(address operator) public view returns (uint256) { return _mintCaps[operator]; }
14,580
1
// Destroys tokens for an accountaccount Account whose tokens are destroyedvalue Amount of tokens to destroy
function burnTokens(address account, uint value) internal; event Burned(address account, uint value);
function burnTokens(address account, uint value) internal; event Burned(address account, uint value);
17,823
526
// Determine if the given moon exists. /
function moonExists(int16 sectorX, int16 sectorY, int16 sectorZ, uint16 system, uint16 planet, uint16 moon) public view returns (bool) { // Get only the existence flag (bool exists, , ) = moonExistsVerbose(sectorX, sectorY, sectorZ, system, planet, moon); // Return it return exists; }
function moonExists(int16 sectorX, int16 sectorY, int16 sectorZ, uint16 system, uint16 planet, uint16 moon) public view returns (bool) { // Get only the existence flag (bool exists, , ) = moonExistsVerbose(sectorX, sectorY, sectorZ, system, planet, moon); // Return it return exists; }
21,659
4
// ========== Admin Setters ========== // Intitialise the protocol with the appropriate parameters. Can only be called once._collateralDecimalsHow many decimals does the collateral contain _collateralAddress The address of the collateral to be used _syntheticAddressThe address of the synthetic token proxy _oracleAddress Address of the IOracle conforming contract _interestSetterAddress which can update interest rates _collateralRatio How much colalteral is needed to borrow _liquidationUserFeeHow much is a user penalised if they go below their c-ratio _liquidationArcRatio How much of the liquidation profit should ARC take /
function init( uint8 _collateralDecimals, address _collateralAddress, address _syntheticAddress, address _oracleAddress, address _interestSetter, Decimal.D256 memory _collateralRatio, Decimal.D256 memory _liquidationUserFee, Decimal.D256 memory _liquidationArcRatio )
function init( uint8 _collateralDecimals, address _collateralAddress, address _syntheticAddress, address _oracleAddress, address _interestSetter, Decimal.D256 memory _collateralRatio, Decimal.D256 memory _liquidationUserFee, Decimal.D256 memory _liquidationArcRatio )
38,485
51
// lock team coin /
function lockTeam(uint256 lockId,uint256 _amount) public onlyOwner returns (bool){ lockedAt = block.timestamp; timeLocks[msg.sender][lockId][0] = lockedAt.add(teamTimeLock); timeLocks[msg.sender][lockId][1] = lockedAt.add(teamTimeLock.mul(2)); allocations[msg.sender][lockId][0] = _amount; allocations[msg.sender][lockId][1] = 0; Locked(lockId,lockedAt,_amount); }
function lockTeam(uint256 lockId,uint256 _amount) public onlyOwner returns (bool){ lockedAt = block.timestamp; timeLocks[msg.sender][lockId][0] = lockedAt.add(teamTimeLock); timeLocks[msg.sender][lockId][1] = lockedAt.add(teamTimeLock.mul(2)); allocations[msg.sender][lockId][0] = _amount; allocations[msg.sender][lockId][1] = 0; Locked(lockId,lockedAt,_amount); }
40,919
194
// Adds new address equivalent to holder./_externalHolderId external holder identifier./_newAddress adding address./ return error code.
function addHolderAddress( bytes32 _externalHolderId, address _newAddress ) onlyOracleOrOwner external returns (uint)
function addHolderAddress( bytes32 _externalHolderId, address _newAddress ) onlyOracleOrOwner external returns (uint)
73,360
10
// ================================================ CONSTANTS ================================================
string public constant STANDARD = "ERC20"; string public constant NAME = "cortex"; string public constant SYMBOL = "ctx"; uint8 public constant DECIMALS = 10; uint256 constant public _totalSupply = (2**64) * (1000000000); // create 2^64 cortex = (2^64) * 1 billion neurons
string public constant STANDARD = "ERC20"; string public constant NAME = "cortex"; string public constant SYMBOL = "ctx"; uint8 public constant DECIMALS = 10; uint256 constant public _totalSupply = (2**64) * (1000000000); // create 2^64 cortex = (2^64) * 1 billion neurons
16,446
182
// Get the users status from the DB contract
uint _userstatus = wrapperdb(dbcontract).getFeesStatus(msg.sender); //Will wrap to DB contract later require(tokenIds_[0] != 0, "ERR(Q)"); //Ensures 0 is not entered in for Token Number!
uint _userstatus = wrapperdb(dbcontract).getFeesStatus(msg.sender); //Will wrap to DB contract later require(tokenIds_[0] != 0, "ERR(Q)"); //Ensures 0 is not entered in for Token Number!
2,476
51
// First 5,000 ETH (soft cap) hold on contract address until ICO end.
addBeneficiary(0x1f7672D49eEEE0dfEB971207651A42392e0ed1c5, 5000 ether); addBeneficiary(0x7ADCE5a8CDC22b65A07b29Fb9F90ebe16F450aB1, 15000 ether); addBeneficiary(0xa406b97666Ea3D2093bDE9644794F8809B0F58Cc, 10000 ether); addBeneficiary(0x3Be990A4031D6A6a9f44c686ccD8B194Bdeea790, 10000 ether); addBeneficiary(0x80E94901ba1f6661A75aFC19f6E2A6CEe29Ff77a, 10000 ether);
addBeneficiary(0x1f7672D49eEEE0dfEB971207651A42392e0ed1c5, 5000 ether); addBeneficiary(0x7ADCE5a8CDC22b65A07b29Fb9F90ebe16F450aB1, 15000 ether); addBeneficiary(0xa406b97666Ea3D2093bDE9644794F8809B0F58Cc, 10000 ether); addBeneficiary(0x3Be990A4031D6A6a9f44c686ccD8B194Bdeea790, 10000 ether); addBeneficiary(0x80E94901ba1f6661A75aFC19f6E2A6CEe29Ff77a, 10000 ether);
14,449
38
// Increment the counter of hosts that have revealed their secret number.
num_hosts_revealed += 1;
num_hosts_revealed += 1;
47,826
31
// marginUsd = margintoken.price
uint marginUsd = ot.margin * token.price * 1e10 / (10 ** token.decimals);
uint marginUsd = ot.margin * token.price * 1e10 / (10 ** token.decimals);
27,578
12
// removes `account` from {roleMembers}, for `role`
function _removeMember(bytes32 role, address account) internal { uint256 idx = roleMembers[role].indexOf[account]; delete roleMembers[role].members[idx]; delete roleMembers[role].indexOf[account]; }
function _removeMember(bytes32 role, address account) internal { uint256 idx = roleMembers[role].indexOf[account]; delete roleMembers[role].members[idx]; delete roleMembers[role].indexOf[account]; }
599
34
// Magic value to be returned upon successful reception of an NFT Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` /
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
59,231
16
// Check if player is still alive.
function isAlive(address player) public view returns (bool alive) { alive = balanceOf[player] > 0; }
function isAlive(address player) public view returns (bool alive) { alive = balanceOf[player] > 0; }
21,206
63
// The value of the global index at the end of a given epoch.
mapping(uint256 => uint256) internal _EPOCH_INDEXES_;
mapping(uint256 => uint256) internal _EPOCH_INDEXES_;
29,937
421
// See IMedia This method is loosely based on the permit for ERC-20 tokens inEIP-2612, but modifiedfor ERC-721. /
function permit( address spender, uint256 tokenId, EIP712Signature memory sig
function permit( address spender, uint256 tokenId, EIP712Signature memory sig
24,847
70
// Transfer Gateway contract address
address public gateway;
address public gateway;
15,624
45
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
uint256[] memory amounts = new uint256[](2); amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12( quotedTokenAmount, daiAmount, path, msg.sender, deadline ); totalDaiSold = amounts[0];
uint256[] memory amounts = new uint256[](2); amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12( quotedTokenAmount, daiAmount, path, msg.sender, deadline ); totalDaiSold = amounts[0];
14,294
23
// Status that an order may hold
enum ORDER_STATUS { OPEN, TAKEN, CANCELED } // Maps makers to orders by nonce as TAKEN (0x01) or CANCELED (0x02) mapping (address => mapping (uint256 => ORDER_STATUS)) public makerOrderStatus; // Maps makers to an optionally set minimum valid nonce mapping (address => uint256) public makerMinimumNonce; // Emitted on Swap event Swap( uint256 indexed nonce, uint256 timestamp, address indexed makerWallet, uint256 makerParam, address makerToken, address indexed takerWallet, uint256 takerParam, address takerToken, address affiliateWallet, uint256 affiliateParam, address affiliateToken ); // Emitted on Cancel event Cancel( uint256 indexed nonce, address indexed makerWallet ); // Emitted on SetMinimumNonce event SetMinimumNonce( uint256 indexed nonce, address indexed makerWallet ); /** * @notice Atomic Token Swap * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param order Order * @param signature Signature */ function swap( Order calldata order, Signature calldata signature ) external payable { // Ensure the order is not expired require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.TAKEN, "ORDER_ALREADY_TAKEN"); // Ensure the order has not already been canceled require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.CANCELED, "ORDER_ALREADY_CANCELED"); require(order.nonce >= makerMinimumNonce[order.maker.wallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (order.taker.wallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != order.taker.wallet) { require(isAuthorized(order.taker.wallet, msg.sender), "SENDER_UNAUTHORIZED"); } // Set the taker to be the specified taker finalTakerWallet = order.taker.wallet; } // Ensure the order signer is authorized require(isAuthorized(order.maker.wallet, signature.signer), "SIGNER_UNAUTHORIZED"); // Ensure the order signature is valid require(isValid(order, signature), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[order.maker.wallet][order.nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (order.taker.token == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == order.taker.param, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(order.maker.wallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker safeTransferAny( "TAKER", finalTakerWallet, order.maker.wallet, order.taker.param, order.taker.token ); } // Transfer token from maker to taker safeTransferAny( "MAKER", order.maker.wallet, finalTakerWallet, order.maker.param, order.maker.token ); // Transfer token from maker to affiliate if specified if (order.affiliate.wallet != address(0)) { safeTransferAny( "MAKER", order.maker.wallet, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } emit Swap(order.nonce, block.timestamp, order.maker.wallet, order.maker.param, order.maker.token, finalTakerWallet, order.taker.param, order.taker.token, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); }
enum ORDER_STATUS { OPEN, TAKEN, CANCELED } // Maps makers to orders by nonce as TAKEN (0x01) or CANCELED (0x02) mapping (address => mapping (uint256 => ORDER_STATUS)) public makerOrderStatus; // Maps makers to an optionally set minimum valid nonce mapping (address => uint256) public makerMinimumNonce; // Emitted on Swap event Swap( uint256 indexed nonce, uint256 timestamp, address indexed makerWallet, uint256 makerParam, address makerToken, address indexed takerWallet, uint256 takerParam, address takerToken, address affiliateWallet, uint256 affiliateParam, address affiliateToken ); // Emitted on Cancel event Cancel( uint256 indexed nonce, address indexed makerWallet ); // Emitted on SetMinimumNonce event SetMinimumNonce( uint256 indexed nonce, address indexed makerWallet ); /** * @notice Atomic Token Swap * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param order Order * @param signature Signature */ function swap( Order calldata order, Signature calldata signature ) external payable { // Ensure the order is not expired require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.TAKEN, "ORDER_ALREADY_TAKEN"); // Ensure the order has not already been canceled require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.CANCELED, "ORDER_ALREADY_CANCELED"); require(order.nonce >= makerMinimumNonce[order.maker.wallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (order.taker.wallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != order.taker.wallet) { require(isAuthorized(order.taker.wallet, msg.sender), "SENDER_UNAUTHORIZED"); } // Set the taker to be the specified taker finalTakerWallet = order.taker.wallet; } // Ensure the order signer is authorized require(isAuthorized(order.maker.wallet, signature.signer), "SIGNER_UNAUTHORIZED"); // Ensure the order signature is valid require(isValid(order, signature), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[order.maker.wallet][order.nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (order.taker.token == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == order.taker.param, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(order.maker.wallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker safeTransferAny( "TAKER", finalTakerWallet, order.maker.wallet, order.taker.param, order.taker.token ); } // Transfer token from maker to taker safeTransferAny( "MAKER", order.maker.wallet, finalTakerWallet, order.maker.param, order.maker.token ); // Transfer token from maker to affiliate if specified if (order.affiliate.wallet != address(0)) { safeTransferAny( "MAKER", order.maker.wallet, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } emit Swap(order.nonce, block.timestamp, order.maker.wallet, order.maker.param, order.maker.token, finalTakerWallet, order.taker.param, order.taker.token, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); }
5,565
97
// Remove a migrator address
function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == true,"address doesn't exist already"); // Delete from the mapping delete valid_migrators[migrator_address]; // 'Delete' from the array by setting the address to 0x0 for (uint256 i = 0; i < valid_migrators_array.length; i++) { if (valid_migrators_array[i] == migrator_address) { valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } }
function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == true,"address doesn't exist already"); // Delete from the mapping delete valid_migrators[migrator_address]; // 'Delete' from the array by setting the address to 0x0 for (uint256 i = 0; i < valid_migrators_array.length; i++) { if (valid_migrators_array[i] == migrator_address) { valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } }
17,995
70
// u2 Instance
U2Legacy public u2;
U2Legacy public u2;
43,469
584
// if a majority is in favor of the upgrade, it happens as definedin the ecliptic base contract
if (majority) { upgrade(_proposal); }
if (majority) { upgrade(_proposal); }
52,106
3
// Decode and loads CEGTerms /
function decodeAndGetCEGTerms(Asset storage asset) external view returns (CEGTerms memory) { return CEGTerms( ContractType(uint8(uint256(asset.packedTerms["enums"] >> 248))), Calendar(uint8(uint256(asset.packedTerms["enums"] >> 240))), ContractRole(uint8(uint256(asset.packedTerms["enums"] >> 232))), DayCountConvention(uint8(uint256(asset.packedTerms["enums"] >> 224))), BusinessDayConvention(uint8(uint256(asset.packedTerms["enums"] >> 216))), EndOfMonthConvention(uint8(uint256(asset.packedTerms["enums"] >> 208))), FeeBasis(uint8(uint256(asset.packedTerms["enums"] >> 200))), ContractPerformance(uint8(uint256(asset.packedTerms["enums"] >> 192))), address(uint160(uint256(asset.packedTerms["currency"]) >> 96)), address(uint160(uint256(asset.packedTerms["settlementCurrency"]) >> 96)), uint256(asset.packedTerms["contractDealDate"]), uint256(asset.packedTerms["statusDate"]), uint256(asset.packedTerms["maturityDate"]), uint256(asset.packedTerms["purchaseDate"]), uint256(asset.packedTerms["cycleAnchorDateOfFee"]), int256(asset.packedTerms["notionalPrincipal"]), int256(asset.packedTerms["delinquencyRate"]), int256(asset.packedTerms["feeRate"]), int256(asset.packedTerms["feeAccrued"]), int256(asset.packedTerms["priceAtPurchaseDate"]), int256(asset.packedTerms["coverageOfCreditEnhancement"]), IP( uint256(asset.packedTerms["gracePeriod"] >> 24), P(uint8(uint256(asset.packedTerms["gracePeriod"] >> 16))), (asset.packedTerms["gracePeriod"] >> 8 & bytes32(uint256(1)) == bytes32(uint256(1))) ? true : false ), IP( uint256(asset.packedTerms["delinquencyPeriod"] >> 24), P(uint8(uint256(asset.packedTerms["delinquencyPeriod"] >> 16))), (asset.packedTerms["delinquencyPeriod"] >> 8 & bytes32(uint256(1)) == bytes32(uint256(1))) ? true : false ), IPS( uint256(asset.packedTerms["cycleOfFee"] >> 24), P(uint8(uint256(asset.packedTerms["cycleOfFee"] >> 16))), S(uint8(uint256(asset.packedTerms["cycleOfFee"] >> 8))), (asset.packedTerms["cycleOfFee"] & bytes32(uint256(1)) == bytes32(uint256(1))) ? true : false ), ContractReference( asset.packedTerms["contractReference_1_object"], asset.packedTerms["contractReference_1_object2"], ContractReferenceType(uint8(uint256(asset.packedTerms["contractReference_1_type_role"] >> 16))), ContractReferenceRole(uint8(uint256(asset.packedTerms["contractReference_1_type_role"] >> 8))) ), ContractReference( asset.packedTerms["contractReference_2_object"], asset.packedTerms["contractReference_2_object2"], ContractReferenceType(uint8(uint256(asset.packedTerms["contractReference_2_type_role"] >> 16))), ContractReferenceRole(uint8(uint256(asset.packedTerms["contractReference_2_type_role"] >> 8))) ) ); }
function decodeAndGetCEGTerms(Asset storage asset) external view returns (CEGTerms memory) { return CEGTerms( ContractType(uint8(uint256(asset.packedTerms["enums"] >> 248))), Calendar(uint8(uint256(asset.packedTerms["enums"] >> 240))), ContractRole(uint8(uint256(asset.packedTerms["enums"] >> 232))), DayCountConvention(uint8(uint256(asset.packedTerms["enums"] >> 224))), BusinessDayConvention(uint8(uint256(asset.packedTerms["enums"] >> 216))), EndOfMonthConvention(uint8(uint256(asset.packedTerms["enums"] >> 208))), FeeBasis(uint8(uint256(asset.packedTerms["enums"] >> 200))), ContractPerformance(uint8(uint256(asset.packedTerms["enums"] >> 192))), address(uint160(uint256(asset.packedTerms["currency"]) >> 96)), address(uint160(uint256(asset.packedTerms["settlementCurrency"]) >> 96)), uint256(asset.packedTerms["contractDealDate"]), uint256(asset.packedTerms["statusDate"]), uint256(asset.packedTerms["maturityDate"]), uint256(asset.packedTerms["purchaseDate"]), uint256(asset.packedTerms["cycleAnchorDateOfFee"]), int256(asset.packedTerms["notionalPrincipal"]), int256(asset.packedTerms["delinquencyRate"]), int256(asset.packedTerms["feeRate"]), int256(asset.packedTerms["feeAccrued"]), int256(asset.packedTerms["priceAtPurchaseDate"]), int256(asset.packedTerms["coverageOfCreditEnhancement"]), IP( uint256(asset.packedTerms["gracePeriod"] >> 24), P(uint8(uint256(asset.packedTerms["gracePeriod"] >> 16))), (asset.packedTerms["gracePeriod"] >> 8 & bytes32(uint256(1)) == bytes32(uint256(1))) ? true : false ), IP( uint256(asset.packedTerms["delinquencyPeriod"] >> 24), P(uint8(uint256(asset.packedTerms["delinquencyPeriod"] >> 16))), (asset.packedTerms["delinquencyPeriod"] >> 8 & bytes32(uint256(1)) == bytes32(uint256(1))) ? true : false ), IPS( uint256(asset.packedTerms["cycleOfFee"] >> 24), P(uint8(uint256(asset.packedTerms["cycleOfFee"] >> 16))), S(uint8(uint256(asset.packedTerms["cycleOfFee"] >> 8))), (asset.packedTerms["cycleOfFee"] & bytes32(uint256(1)) == bytes32(uint256(1))) ? true : false ), ContractReference( asset.packedTerms["contractReference_1_object"], asset.packedTerms["contractReference_1_object2"], ContractReferenceType(uint8(uint256(asset.packedTerms["contractReference_1_type_role"] >> 16))), ContractReferenceRole(uint8(uint256(asset.packedTerms["contractReference_1_type_role"] >> 8))) ), ContractReference( asset.packedTerms["contractReference_2_object"], asset.packedTerms["contractReference_2_object2"], ContractReferenceType(uint8(uint256(asset.packedTerms["contractReference_2_type_role"] >> 16))), ContractReferenceRole(uint8(uint256(asset.packedTerms["contractReference_2_type_role"] >> 8))) ) ); }
41,456
188
// _amount in `token`
function redeemUnderlying(uint256 _amount) external returns(uint256); function getApr() external view returns(uint256);
function redeemUnderlying(uint256 _amount) external returns(uint256); function getApr() external view returns(uint256);
45,644
113
// Returns `max(0, x - y)`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(gt(x, y), sub(x, y)) } }
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(gt(x, y), sub(x, y)) } }
19,900
338
// Max BPS for limiting flash loan fee settings.
uint256 public constant MAX_BPS = 10000;
uint256 public constant MAX_BPS = 10000;
3,780
27
// Standard ERC20 token Implementation of the basic standard token. /
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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]; } /** * @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 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(_value <= balances_[msg.sender],"Invalid value"); require(_to != address(0),"Invalid address"); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed_[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev 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(_value <= balances_[_from],"Value is more than balance"); require(_value <= allowed_[_from][msg.sender],"Value is more than alloved"); require(_to != address(0),"Invalid address"); 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 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; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); require(_amount <= balances_[_account],"Amount is more than balance"); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed_[_account][msg.sender],"Amount is more than alloved"); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub(_amount); _burn(_account, _amount); } }
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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]; } /** * @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 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(_value <= balances_[msg.sender],"Invalid value"); require(_to != address(0),"Invalid address"); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed_[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev 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(_value <= balances_[_from],"Value is more than balance"); require(_value <= allowed_[_from][msg.sender],"Value is more than alloved"); require(_to != address(0),"Invalid address"); 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 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; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); require(_amount <= balances_[_account],"Amount is more than balance"); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed_[_account][msg.sender],"Amount is more than alloved"); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub(_amount); _burn(_account, _amount); } }
12,013
29
// This is used by Last Chance function
lastExpenseTime = now;
lastExpenseTime = now;
32,823
11
// Checks if user is valid
if(!userInfo[msg.sender].active) { require(userInfo[msg.sender].endTime >= block.timestamp, "buy: invalid user"); }
if(!userInfo[msg.sender].active) { require(userInfo[msg.sender].endTime >= block.timestamp, "buy: invalid user"); }
26,168
30
// Normal orders usually cannot serve as their own previous order. For further discussion see Heinlein&39;s &39;—All You Zombies—&39;.
require(orderId != updatedPrevId); uint32 nextId;
require(orderId != updatedPrevId); uint32 nextId;
41,466
351
// https:docs.pynthetix.io/contracts/source/contracts/feepool
contract FeePool is Owned, Proxyable, LimitedSetup, MixinSystemSettings, IFeePool { using SafeMath for uint; using SafeDecimalMath for uint; // Where fees are pooled in sUSD. address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; // sUSD currencyKey. Fees stored and paid in sUSD bytes32 private sUSD = "sUSD"; // This struct represents the issuance activity that's happened in a fee period. struct FeePeriod { uint64 feePeriodId; uint64 startingDebtIndex; uint64 startTime; uint feesToDistribute; uint feesClaimed; uint rewardsToDistribute; uint rewardsClaimed; } // A staker(mintr) can claim from the previous fee period (7 days) only. // Fee Periods stored and managed from [0], such that [0] is always // the current active fee period which is not claimable until the // public function closeCurrentFeePeriod() is called closing the // current weeks collected fees. [1] is last weeks feeperiod uint8 public constant FEE_PERIOD_LENGTH = 2; FeePeriod[FEE_PERIOD_LENGTH] private _recentFeePeriods; uint256 private _currentFeePeriod; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_PYNTHETIX = "Pynthetix"; bytes32 private constant CONTRACT_FEEPOOLSTATE = "FeePoolState"; bytes32 private constant CONTRACT_FEEPOOLETERNALSTORAGE = "FeePoolEternalStorage"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_PYNTHETIXSTATE = "PynthetixState"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals"; bytes32 private constant CONTRACT_ETH_COLLATERAL_SUSD = "EtherCollateralsUSD"; bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager"; bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution"; /* ========== ETERNAL STORAGE CONSTANTS ========== */ bytes32 private constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal"; constructor( address payable _proxy, address _owner, address _resolver ) public Owned(_owner) Proxyable(_proxy) LimitedSetup(3 weeks) MixinSystemSettings(_resolver) { // Set our initial fee period _recentFeePeriodsStorage(0).feePeriodId = 1; _recentFeePeriodsStorage(0).startTime = uint64(now); } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](12); newAddresses[0] = CONTRACT_SYSTEMSTATUS; newAddresses[1] = CONTRACT_PYNTHETIX; newAddresses[2] = CONTRACT_FEEPOOLSTATE; newAddresses[3] = CONTRACT_FEEPOOLETERNALSTORAGE; newAddresses[4] = CONTRACT_EXCHANGER; newAddresses[5] = CONTRACT_ISSUER; newAddresses[6] = CONTRACT_PYNTHETIXSTATE; newAddresses[7] = CONTRACT_REWARDESCROW_V2; newAddresses[8] = CONTRACT_DELEGATEAPPROVALS; newAddresses[9] = CONTRACT_ETH_COLLATERAL_SUSD; newAddresses[10] = CONTRACT_REWARDSDISTRIBUTION; newAddresses[11] = CONTRACT_COLLATERALMANAGER; addresses = combineArrays(existingAddresses, newAddresses); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function pynthetix() internal view returns (IPynthetix) { return IPynthetix(requireAndGetAddress(CONTRACT_PYNTHETIX)); } function feePoolState() internal view returns (FeePoolState) { return FeePoolState(requireAndGetAddress(CONTRACT_FEEPOOLSTATE)); } function feePoolEternalStorage() internal view returns (FeePoolEternalStorage) { return FeePoolEternalStorage(requireAndGetAddress(CONTRACT_FEEPOOLETERNALSTORAGE)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function etherCollateralsUSD() internal view returns (IEtherCollateralsUSD) { return IEtherCollateralsUSD(requireAndGetAddress(CONTRACT_ETH_COLLATERAL_SUSD)); } function collateralManager() internal view returns (ICollateralManager) { return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function pynthetixState() internal view returns (IPynthetixState) { return IPynthetixState(requireAndGetAddress(CONTRACT_PYNTHETIXSTATE)); } function rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2)); } function delegateApprovals() internal view returns (IDelegateApprovals) { return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS)); } function rewardsDistribution() internal view returns (IRewardsDistribution) { return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION)); } function issuanceRatio() external view returns (uint) { return getIssuanceRatio(); } function feePeriodDuration() external view returns (uint) { return getFeePeriodDuration(); } function targetThreshold() external view returns (uint) { return getTargetThreshold(); } function recentFeePeriods(uint index) external view returns ( uint64 feePeriodId, uint64 startingDebtIndex, uint64 startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed ) { FeePeriod memory feePeriod = _recentFeePeriodsStorage(index); return ( feePeriod.feePeriodId, feePeriod.startingDebtIndex, feePeriod.startTime, feePeriod.feesToDistribute, feePeriod.feesClaimed, feePeriod.rewardsToDistribute, feePeriod.rewardsClaimed ); } function _recentFeePeriodsStorage(uint index) internal view returns (FeePeriod storage) { return _recentFeePeriods[(_currentFeePeriod + index) % FEE_PERIOD_LENGTH]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Logs an accounts issuance data per fee period * @param account Message.Senders account address * @param debtRatio Debt percentage this account has locked after minting or burning their pynth * @param debtEntryIndex The index in the global debt ledger. pynthetixState.issuanceData(account) * @dev onlyIssuer to call me on pynthetix.issue() & pynthetix.burn() calls to store the locked PNX * per fee period so we know to allocate the correct proportions of fees and rewards per period */ function appendAccountIssuanceRecord( address account, uint debtRatio, uint debtEntryIndex ) external onlyIssuer { feePoolState().appendAccountIssuanceRecord( account, debtRatio, debtEntryIndex, _recentFeePeriodsStorage(0).startingDebtIndex ); emitIssuanceDebtRatioEntry(account, debtRatio, debtEntryIndex, _recentFeePeriodsStorage(0).startingDebtIndex); } /** * @notice The Exchanger contract informs us when fees are paid. * @param amount susd amount in fees being paid. */ function recordFeePaid(uint amount) external onlyInternalContracts { // Keep track off fees in sUSD in the open fee pool period. _recentFeePeriodsStorage(0).feesToDistribute = _recentFeePeriodsStorage(0).feesToDistribute.add(amount); } /** * @notice The RewardsDistribution contract informs us how many PNX rewards are sent to RewardEscrow to be claimed. */ function setRewardsToDistribute(uint amount) external { address rewardsAuthority = address(rewardsDistribution()); require(messageSender == rewardsAuthority || msg.sender == rewardsAuthority, "Caller is not rewardsAuthority"); // Add the amount of PNX rewards to distribute on top of any rolling unclaimed amount _recentFeePeriodsStorage(0).rewardsToDistribute = _recentFeePeriodsStorage(0).rewardsToDistribute.add(amount); } /** * @notice Close the current fee period and start a new one. */ function closeCurrentFeePeriod() external issuanceActive { require(getFeePeriodDuration() > 0, "Fee Period Duration not set"); require(_recentFeePeriodsStorage(0).startTime <= (now - getFeePeriodDuration()), "Too early to close fee period"); // Note: when FEE_PERIOD_LENGTH = 2, periodClosing is the current period & periodToRollover is the last open claimable period FeePeriod storage periodClosing = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2); FeePeriod storage periodToRollover = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 1); // Any unclaimed fees from the last period in the array roll back one period. // Because of the subtraction here, they're effectively proportionally redistributed to those who // have already claimed from the old period, available in the new period. // The subtraction is important so we don't create a ticking time bomb of an ever growing // number of fees that can never decrease and will eventually overflow at the end of the fee pool. _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).feesToDistribute = periodToRollover .feesToDistribute .sub(periodToRollover.feesClaimed) .add(periodClosing.feesToDistribute); _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).rewardsToDistribute = periodToRollover .rewardsToDistribute .sub(periodToRollover.rewardsClaimed) .add(periodClosing.rewardsToDistribute); // Shift the previous fee periods across to make room for the new one. _currentFeePeriod = _currentFeePeriod.add(FEE_PERIOD_LENGTH).sub(1).mod(FEE_PERIOD_LENGTH); // Clear the first element of the array to make sure we don't have any stale values. delete _recentFeePeriods[_currentFeePeriod]; // Open up the new fee period. // Increment periodId from the recent closed period feePeriodId _recentFeePeriodsStorage(0).feePeriodId = uint64(uint256(_recentFeePeriodsStorage(1).feePeriodId).add(1)); _recentFeePeriodsStorage(0).startingDebtIndex = uint64(pynthetixState().debtLedgerLength()); _recentFeePeriodsStorage(0).startTime = uint64(now); emitFeePeriodClosed(_recentFeePeriodsStorage(1).feePeriodId); } /** * @notice Claim fees for last period when available or not already withdrawn. */ function claimFees() external issuanceActive optionalProxy returns (bool) { return _claimFees(messageSender); } /** * @notice Delegated claimFees(). Call from the deletegated address * and the fees will be sent to the claimingForAddress. * approveClaimOnBehalf() must be called first to approve the deletage address * @param claimingForAddress The account you are claiming fees for */ function claimOnBehalf(address claimingForAddress) external issuanceActive optionalProxy returns (bool) { require(delegateApprovals().canClaimFor(claimingForAddress, messageSender), "Not approved to claim on behalf"); return _claimFees(claimingForAddress); } function _claimFees(address claimingAddress) internal returns (bool) { uint rewardsPaid = 0; uint feesPaid = 0; uint availableFees; uint availableRewards; // Address won't be able to claim fees if it is too far below the target c-ratio. // It will need to burn pynths then try claiming again. (bool feesClaimable, bool anyRateIsInvalid) = _isFeesClaimableAndAnyRatesInvalid(claimingAddress); require(feesClaimable, "C-Ratio below penalty threshold"); require(!anyRateIsInvalid, "A pynth or PNX rate is invalid"); // Get the claimingAddress available fees and rewards (availableFees, availableRewards) = feesAvailable(claimingAddress); require( availableFees > 0 || availableRewards > 0, "No fees or rewards available for period, or fees already claimed" ); // Record the address has claimed for this period _setLastFeeWithdrawal(claimingAddress, _recentFeePeriodsStorage(1).feePeriodId); if (availableFees > 0) { // Record the fee payment in our recentFeePeriods feesPaid = _recordFeePayment(availableFees); // Send them their fees _payFees(claimingAddress, feesPaid); } if (availableRewards > 0) { // Record the reward payment in our recentFeePeriods rewardsPaid = _recordRewardPayment(availableRewards); // Send them their rewards _payRewards(claimingAddress, rewardsPaid); } emitFeesClaimed(claimingAddress, feesPaid, rewardsPaid); return true; } /** * @notice Admin function to import the FeePeriod data from the previous contract */ function importFeePeriod( uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed ) public optionalProxy_onlyOwner onlyDuringSetup { require(startingDebtIndex <= pynthetixState().debtLedgerLength(), "Cannot import bad data"); _recentFeePeriods[_currentFeePeriod.add(feePeriodIndex).mod(FEE_PERIOD_LENGTH)] = FeePeriod({ feePeriodId: uint64(feePeriodId), startingDebtIndex: uint64(startingDebtIndex), startTime: uint64(startTime), feesToDistribute: feesToDistribute, feesClaimed: feesClaimed, rewardsToDistribute: rewardsToDistribute, rewardsClaimed: rewardsClaimed }); } /** * @notice Record the fee payment in our recentFeePeriods. * @param sUSDAmount The amount of fees priced in sUSD. */ function _recordFeePayment(uint sUSDAmount) internal returns (uint) { // Don't assign to the parameter uint remainingToAllocate = sUSDAmount; uint feesPaid; // Start at the oldest period and record the amount, moving to newer periods // until we've exhausted the amount. // The condition checks for overflow because we're going to 0 with an unsigned int. for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) { uint feesAlreadyClaimed = _recentFeePeriodsStorage(i).feesClaimed; uint delta = _recentFeePeriodsStorage(i).feesToDistribute.sub(feesAlreadyClaimed); if (delta > 0) { // Take the smaller of the amount left to claim in the period and the amount we need to allocate uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate; _recentFeePeriodsStorage(i).feesClaimed = feesAlreadyClaimed.add(amountInPeriod); remainingToAllocate = remainingToAllocate.sub(amountInPeriod); feesPaid = feesPaid.add(amountInPeriod); // No need to continue iterating if we've recorded the whole amount; if (remainingToAllocate == 0) return feesPaid; // We've exhausted feePeriods to distribute and no fees remain in last period // User last to claim would in this scenario have their remainder slashed if (i == 0 && remainingToAllocate > 0) { remainingToAllocate = 0; } } } return feesPaid; } /** * @notice Record the reward payment in our recentFeePeriods. * @param snxAmount The amount of PNX tokens. */ function _recordRewardPayment(uint snxAmount) internal returns (uint) { // Don't assign to the parameter uint remainingToAllocate = snxAmount; uint rewardPaid; // Start at the oldest period and record the amount, moving to newer periods // until we've exhausted the amount. // The condition checks for overflow because we're going to 0 with an unsigned int. for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) { uint toDistribute = _recentFeePeriodsStorage(i).rewardsToDistribute.sub( _recentFeePeriodsStorage(i).rewardsClaimed ); if (toDistribute > 0) { // Take the smaller of the amount left to claim in the period and the amount we need to allocate uint amountInPeriod = toDistribute < remainingToAllocate ? toDistribute : remainingToAllocate; _recentFeePeriodsStorage(i).rewardsClaimed = _recentFeePeriodsStorage(i).rewardsClaimed.add(amountInPeriod); remainingToAllocate = remainingToAllocate.sub(amountInPeriod); rewardPaid = rewardPaid.add(amountInPeriod); // No need to continue iterating if we've recorded the whole amount; if (remainingToAllocate == 0) return rewardPaid; // We've exhausted feePeriods to distribute and no rewards remain in last period // User last to claim would in this scenario have their remainder slashed // due to rounding up of PreciseDecimal if (i == 0 && remainingToAllocate > 0) { remainingToAllocate = 0; } } } return rewardPaid; } /** * @notice Send the fees to claiming address. * @param account The address to send the fees to. * @param sUSDAmount The amount of fees priced in sUSD. */ function _payFees(address account, uint sUSDAmount) internal notFeeAddress(account) { // Grab the sUSD Pynth IPynth sUSDPynth = issuer().pynths(sUSD); // NOTE: we do not control the FEE_ADDRESS so it is not possible to do an // ERC20.approve() transaction to allow this feePool to call ERC20.transferFrom // to the accounts address // Burn the source amount sUSDPynth.burn(FEE_ADDRESS, sUSDAmount); // Mint their new pynths sUSDPynth.issue(account, sUSDAmount); } /** * @notice Send the rewards to claiming address - will be locked in rewardEscrow. * @param account The address to send the fees to. * @param snxAmount The amount of PNX. */ function _payRewards(address account, uint snxAmount) internal notFeeAddress(account) { /* Escrow the tokens for 1 year. */ uint escrowDuration = 52 weeks; // Record vesting entry for claiming address and amount // PNX already minted to rewardEscrow balance rewardEscrowV2().appendVestingEntry(account, snxAmount, escrowDuration); } /** * @notice The total fees available in the system to be withdrawnn in sUSD */ function totalFeesAvailable() external view returns (uint) { uint totalFees = 0; // Fees in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute); totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed); } return totalFees; } /** * @notice The total PNX rewards available in the system to be withdrawn */ function totalRewardsAvailable() external view returns (uint) { uint totalRewards = 0; // Rewards in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute); totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed); } return totalRewards; } /** * @notice The fees available to be withdrawn by a specific account, priced in sUSD * @dev Returns two amounts, one for fees and one for PNX rewards */ function feesAvailable(address account) public view returns (uint, uint) { // Add up the fees uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account); uint totalFees = 0; uint totalRewards = 0; // Fees & Rewards in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(userFees[i][0]); totalRewards = totalRewards.add(userFees[i][1]); } // And convert totalFees to sUSD // Return totalRewards as is in PNX amount return (totalFees, totalRewards); } function _isFeesClaimableAndAnyRatesInvalid(address account) internal view returns (bool, bool) { // Threshold is calculated from ratio % above the target ratio (issuanceRatio). // 0 < 10%: Claimable // 10% > above: Unable to claim (uint ratio, bool anyRateIsInvalid) = issuer().collateralisationRatioAndAnyRatesInvalid(account); uint targetRatio = getIssuanceRatio(); // Claimable if collateral ratio below target ratio if (ratio < targetRatio) { return (true, anyRateIsInvalid); } // Calculate the threshold for collateral ratio before fees can't be claimed. uint ratio_threshold = targetRatio.multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold())); // Not claimable if collateral ratio above threshold if (ratio > ratio_threshold) { return (false, anyRateIsInvalid); } return (true, anyRateIsInvalid); } function isFeesClaimable(address account) external view returns (bool feesClaimable) { (feesClaimable, ) = _isFeesClaimableAndAnyRatesInvalid(account); } /** * @notice Calculates fees by period for an account, priced in sUSD * @param account The address you want to query the fees for */ function feesByPeriod(address account) public view returns (uint[2][FEE_PERIOD_LENGTH] memory results) { // What's the user's debt entry index and the debt they owe to the system at current feePeriod uint userOwnershipPercentage; uint debtEntryIndex; FeePoolState _feePoolState = feePoolState(); (userOwnershipPercentage, debtEntryIndex) = _feePoolState.getAccountsDebtEntry(account, 0); // If they don't have any debt ownership and they never minted, they don't have any fees. // User ownership can reduce to 0 if user burns all pynths, // however they could have fees applicable for periods they had minted in before so we check debtEntryIndex. if (debtEntryIndex == 0 && userOwnershipPercentage == 0) { uint[2][FEE_PERIOD_LENGTH] memory nullResults; return nullResults; } // The [0] fee period is not yet ready to claim, but it is a fee period that they can have // fees owing for, so we need to report on it anyway. uint feesFromPeriod; uint rewardsFromPeriod; (feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(0, userOwnershipPercentage, debtEntryIndex); results[0][0] = feesFromPeriod; results[0][1] = rewardsFromPeriod; // Retrieve user's last fee claim by periodId uint lastFeeWithdrawal = getLastFeeWithdrawal(account); // Go through our fee periods from the oldest feePeriod[FEE_PERIOD_LENGTH - 1] and figure out what we owe them. // Condition checks for periods > 0 for (uint i = FEE_PERIOD_LENGTH - 1; i > 0; i--) { uint next = i - 1; uint nextPeriodStartingDebtIndex = _recentFeePeriodsStorage(next).startingDebtIndex; // We can skip the period, as no debt minted during period (next period's startingDebtIndex is still 0) if (nextPeriodStartingDebtIndex > 0 && lastFeeWithdrawal < _recentFeePeriodsStorage(i).feePeriodId) { // We calculate a feePeriod's closingDebtIndex by looking at the next feePeriod's startingDebtIndex // we can use the most recent issuanceData[0] for the current feePeriod // else find the applicableIssuanceData for the feePeriod based on the StartingDebtIndex of the period uint closingDebtIndex = uint256(nextPeriodStartingDebtIndex).sub(1); // Gas optimisation - to reuse debtEntryIndex if found new applicable one // if applicable is 0,0 (none found) we keep most recent one from issuanceData[0] // return if userOwnershipPercentage = 0) (userOwnershipPercentage, debtEntryIndex) = _feePoolState.applicableIssuanceData(account, closingDebtIndex); (feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(i, userOwnershipPercentage, debtEntryIndex); results[i][0] = feesFromPeriod; results[i][1] = rewardsFromPeriod; } } } /** * @notice ownershipPercentage is a high precision decimals uint based on * wallet's debtPercentage. Gives a precise amount of the feesToDistribute * for fees in the period. Precision factor is removed before results are * returned. * @dev The reported fees owing for the current period [0] are just a * running balance until the fee period closes */ function _feesAndRewardsFromPeriod( uint period, uint ownershipPercentage, uint debtEntryIndex ) internal view returns (uint, uint) { // If it's zero, they haven't issued, and they have no fees OR rewards. if (ownershipPercentage == 0) return (0, 0); uint debtOwnershipForPeriod = ownershipPercentage; // If period has closed we want to calculate debtPercentage for the period if (period > 0) { uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1); debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex); } // Calculate their percentage of the fees / rewards in this period // This is a high precision integer. uint feesFromPeriod = _recentFeePeriodsStorage(period).feesToDistribute.multiplyDecimal(debtOwnershipForPeriod); uint rewardsFromPeriod = _recentFeePeriodsStorage(period).rewardsToDistribute.multiplyDecimal( debtOwnershipForPeriod ); return (feesFromPeriod.preciseDecimalToDecimal(), rewardsFromPeriod.preciseDecimalToDecimal()); } function _effectiveDebtRatioForPeriod( uint closingDebtIndex, uint ownershipPercentage, uint debtEntryIndex ) internal view returns (uint) { // Figure out their global debt percentage delta at end of fee Period. // This is a high precision integer. IPynthetixState _pynthetixState = pynthetixState(); uint feePeriodDebtOwnership = _pynthetixState .debtLedger(closingDebtIndex) .divideDecimalRoundPrecise(_pynthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(ownershipPercentage); return feePeriodDebtOwnership; } function effectiveDebtRatioForPeriod(address account, uint period) external view returns (uint) { require(period != 0, "Current period is not closed yet"); require(period < FEE_PERIOD_LENGTH, "Exceeds the FEE_PERIOD_LENGTH"); // If the period being checked is uninitialised then return 0. This is only at the start of the system. if (_recentFeePeriodsStorage(period - 1).startingDebtIndex == 0) return 0; uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1); uint ownershipPercentage; uint debtEntryIndex; (ownershipPercentage, debtEntryIndex) = feePoolState().applicableIssuanceData(account, closingDebtIndex); // internal function will check closingDebtIndex has corresponding debtLedger entry return _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex); } /** * @notice Get the feePeriodID of the last claim this account made * @param _claimingAddress account to check the last fee period ID claim for * @return uint of the feePeriodID this account last claimed */ function getLastFeeWithdrawal(address _claimingAddress) public view returns (uint) { return feePoolEternalStorage().getUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress))); } /** * @notice Calculate the collateral ratio before user is blocked from claiming. */ function getPenaltyThresholdRatio() public view returns (uint) { return getIssuanceRatio().multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold())); } /** * @notice Set the feePeriodID of the last claim this account made * @param _claimingAddress account to set the last feePeriodID claim for * @param _feePeriodID the feePeriodID this account claimed fees for */ function _setLastFeeWithdrawal(address _claimingAddress, uint _feePeriodID) internal { feePoolEternalStorage().setUIntValue( keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress)), _feePeriodID ); } /* ========== Modifiers ========== */ modifier onlyInternalContracts { bool isExchanger = msg.sender == address(exchanger()); bool isPynth = issuer().pynthsByAddress(msg.sender) != bytes32(0); bool isEtherCollateralsUSD = msg.sender == address(etherCollateralsUSD()); bool isCollateral = collateralManager().hasCollateral(msg.sender); require(isExchanger || isPynth || isEtherCollateralsUSD || isCollateral, "Only Internal Contracts"); _; } modifier onlyIssuer { require(msg.sender == address(issuer()), "FeePool: Only Issuer Authorised"); _; } modifier notFeeAddress(address account) { require(account != FEE_ADDRESS, "Fee address not allowed"); _; } modifier issuanceActive() { systemStatus().requireIssuanceActive(); _; } /* ========== Proxy Events ========== */ event IssuanceDebtRatioEntry( address indexed account, uint debtRatio, uint debtEntryIndex, uint feePeriodStartingDebtIndex ); bytes32 private constant ISSUANCEDEBTRATIOENTRY_SIG = keccak256( "IssuanceDebtRatioEntry(address,uint256,uint256,uint256)" ); function emitIssuanceDebtRatioEntry( address account, uint debtRatio, uint debtEntryIndex, uint feePeriodStartingDebtIndex ) internal { proxy._emit( abi.encode(debtRatio, debtEntryIndex, feePeriodStartingDebtIndex), 2, ISSUANCEDEBTRATIOENTRY_SIG, bytes32(uint256(uint160(account))), 0, 0 ); } event FeePeriodClosed(uint feePeriodId); bytes32 private constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)"); function emitFeePeriodClosed(uint feePeriodId) internal { proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0); } event FeesClaimed(address account, uint sUSDAmount, uint snxRewards); bytes32 private constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256,uint256)"); function emitFeesClaimed( address account, uint sUSDAmount, uint snxRewards ) internal { proxy._emit(abi.encode(account, sUSDAmount, snxRewards), 1, FEESCLAIMED_SIG, 0, 0, 0); } }
contract FeePool is Owned, Proxyable, LimitedSetup, MixinSystemSettings, IFeePool { using SafeMath for uint; using SafeDecimalMath for uint; // Where fees are pooled in sUSD. address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; // sUSD currencyKey. Fees stored and paid in sUSD bytes32 private sUSD = "sUSD"; // This struct represents the issuance activity that's happened in a fee period. struct FeePeriod { uint64 feePeriodId; uint64 startingDebtIndex; uint64 startTime; uint feesToDistribute; uint feesClaimed; uint rewardsToDistribute; uint rewardsClaimed; } // A staker(mintr) can claim from the previous fee period (7 days) only. // Fee Periods stored and managed from [0], such that [0] is always // the current active fee period which is not claimable until the // public function closeCurrentFeePeriod() is called closing the // current weeks collected fees. [1] is last weeks feeperiod uint8 public constant FEE_PERIOD_LENGTH = 2; FeePeriod[FEE_PERIOD_LENGTH] private _recentFeePeriods; uint256 private _currentFeePeriod; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_PYNTHETIX = "Pynthetix"; bytes32 private constant CONTRACT_FEEPOOLSTATE = "FeePoolState"; bytes32 private constant CONTRACT_FEEPOOLETERNALSTORAGE = "FeePoolEternalStorage"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_PYNTHETIXSTATE = "PynthetixState"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals"; bytes32 private constant CONTRACT_ETH_COLLATERAL_SUSD = "EtherCollateralsUSD"; bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager"; bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution"; /* ========== ETERNAL STORAGE CONSTANTS ========== */ bytes32 private constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal"; constructor( address payable _proxy, address _owner, address _resolver ) public Owned(_owner) Proxyable(_proxy) LimitedSetup(3 weeks) MixinSystemSettings(_resolver) { // Set our initial fee period _recentFeePeriodsStorage(0).feePeriodId = 1; _recentFeePeriodsStorage(0).startTime = uint64(now); } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](12); newAddresses[0] = CONTRACT_SYSTEMSTATUS; newAddresses[1] = CONTRACT_PYNTHETIX; newAddresses[2] = CONTRACT_FEEPOOLSTATE; newAddresses[3] = CONTRACT_FEEPOOLETERNALSTORAGE; newAddresses[4] = CONTRACT_EXCHANGER; newAddresses[5] = CONTRACT_ISSUER; newAddresses[6] = CONTRACT_PYNTHETIXSTATE; newAddresses[7] = CONTRACT_REWARDESCROW_V2; newAddresses[8] = CONTRACT_DELEGATEAPPROVALS; newAddresses[9] = CONTRACT_ETH_COLLATERAL_SUSD; newAddresses[10] = CONTRACT_REWARDSDISTRIBUTION; newAddresses[11] = CONTRACT_COLLATERALMANAGER; addresses = combineArrays(existingAddresses, newAddresses); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function pynthetix() internal view returns (IPynthetix) { return IPynthetix(requireAndGetAddress(CONTRACT_PYNTHETIX)); } function feePoolState() internal view returns (FeePoolState) { return FeePoolState(requireAndGetAddress(CONTRACT_FEEPOOLSTATE)); } function feePoolEternalStorage() internal view returns (FeePoolEternalStorage) { return FeePoolEternalStorage(requireAndGetAddress(CONTRACT_FEEPOOLETERNALSTORAGE)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function etherCollateralsUSD() internal view returns (IEtherCollateralsUSD) { return IEtherCollateralsUSD(requireAndGetAddress(CONTRACT_ETH_COLLATERAL_SUSD)); } function collateralManager() internal view returns (ICollateralManager) { return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function pynthetixState() internal view returns (IPynthetixState) { return IPynthetixState(requireAndGetAddress(CONTRACT_PYNTHETIXSTATE)); } function rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2)); } function delegateApprovals() internal view returns (IDelegateApprovals) { return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS)); } function rewardsDistribution() internal view returns (IRewardsDistribution) { return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION)); } function issuanceRatio() external view returns (uint) { return getIssuanceRatio(); } function feePeriodDuration() external view returns (uint) { return getFeePeriodDuration(); } function targetThreshold() external view returns (uint) { return getTargetThreshold(); } function recentFeePeriods(uint index) external view returns ( uint64 feePeriodId, uint64 startingDebtIndex, uint64 startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed ) { FeePeriod memory feePeriod = _recentFeePeriodsStorage(index); return ( feePeriod.feePeriodId, feePeriod.startingDebtIndex, feePeriod.startTime, feePeriod.feesToDistribute, feePeriod.feesClaimed, feePeriod.rewardsToDistribute, feePeriod.rewardsClaimed ); } function _recentFeePeriodsStorage(uint index) internal view returns (FeePeriod storage) { return _recentFeePeriods[(_currentFeePeriod + index) % FEE_PERIOD_LENGTH]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Logs an accounts issuance data per fee period * @param account Message.Senders account address * @param debtRatio Debt percentage this account has locked after minting or burning their pynth * @param debtEntryIndex The index in the global debt ledger. pynthetixState.issuanceData(account) * @dev onlyIssuer to call me on pynthetix.issue() & pynthetix.burn() calls to store the locked PNX * per fee period so we know to allocate the correct proportions of fees and rewards per period */ function appendAccountIssuanceRecord( address account, uint debtRatio, uint debtEntryIndex ) external onlyIssuer { feePoolState().appendAccountIssuanceRecord( account, debtRatio, debtEntryIndex, _recentFeePeriodsStorage(0).startingDebtIndex ); emitIssuanceDebtRatioEntry(account, debtRatio, debtEntryIndex, _recentFeePeriodsStorage(0).startingDebtIndex); } /** * @notice The Exchanger contract informs us when fees are paid. * @param amount susd amount in fees being paid. */ function recordFeePaid(uint amount) external onlyInternalContracts { // Keep track off fees in sUSD in the open fee pool period. _recentFeePeriodsStorage(0).feesToDistribute = _recentFeePeriodsStorage(0).feesToDistribute.add(amount); } /** * @notice The RewardsDistribution contract informs us how many PNX rewards are sent to RewardEscrow to be claimed. */ function setRewardsToDistribute(uint amount) external { address rewardsAuthority = address(rewardsDistribution()); require(messageSender == rewardsAuthority || msg.sender == rewardsAuthority, "Caller is not rewardsAuthority"); // Add the amount of PNX rewards to distribute on top of any rolling unclaimed amount _recentFeePeriodsStorage(0).rewardsToDistribute = _recentFeePeriodsStorage(0).rewardsToDistribute.add(amount); } /** * @notice Close the current fee period and start a new one. */ function closeCurrentFeePeriod() external issuanceActive { require(getFeePeriodDuration() > 0, "Fee Period Duration not set"); require(_recentFeePeriodsStorage(0).startTime <= (now - getFeePeriodDuration()), "Too early to close fee period"); // Note: when FEE_PERIOD_LENGTH = 2, periodClosing is the current period & periodToRollover is the last open claimable period FeePeriod storage periodClosing = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2); FeePeriod storage periodToRollover = _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 1); // Any unclaimed fees from the last period in the array roll back one period. // Because of the subtraction here, they're effectively proportionally redistributed to those who // have already claimed from the old period, available in the new period. // The subtraction is important so we don't create a ticking time bomb of an ever growing // number of fees that can never decrease and will eventually overflow at the end of the fee pool. _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).feesToDistribute = periodToRollover .feesToDistribute .sub(periodToRollover.feesClaimed) .add(periodClosing.feesToDistribute); _recentFeePeriodsStorage(FEE_PERIOD_LENGTH - 2).rewardsToDistribute = periodToRollover .rewardsToDistribute .sub(periodToRollover.rewardsClaimed) .add(periodClosing.rewardsToDistribute); // Shift the previous fee periods across to make room for the new one. _currentFeePeriod = _currentFeePeriod.add(FEE_PERIOD_LENGTH).sub(1).mod(FEE_PERIOD_LENGTH); // Clear the first element of the array to make sure we don't have any stale values. delete _recentFeePeriods[_currentFeePeriod]; // Open up the new fee period. // Increment periodId from the recent closed period feePeriodId _recentFeePeriodsStorage(0).feePeriodId = uint64(uint256(_recentFeePeriodsStorage(1).feePeriodId).add(1)); _recentFeePeriodsStorage(0).startingDebtIndex = uint64(pynthetixState().debtLedgerLength()); _recentFeePeriodsStorage(0).startTime = uint64(now); emitFeePeriodClosed(_recentFeePeriodsStorage(1).feePeriodId); } /** * @notice Claim fees for last period when available or not already withdrawn. */ function claimFees() external issuanceActive optionalProxy returns (bool) { return _claimFees(messageSender); } /** * @notice Delegated claimFees(). Call from the deletegated address * and the fees will be sent to the claimingForAddress. * approveClaimOnBehalf() must be called first to approve the deletage address * @param claimingForAddress The account you are claiming fees for */ function claimOnBehalf(address claimingForAddress) external issuanceActive optionalProxy returns (bool) { require(delegateApprovals().canClaimFor(claimingForAddress, messageSender), "Not approved to claim on behalf"); return _claimFees(claimingForAddress); } function _claimFees(address claimingAddress) internal returns (bool) { uint rewardsPaid = 0; uint feesPaid = 0; uint availableFees; uint availableRewards; // Address won't be able to claim fees if it is too far below the target c-ratio. // It will need to burn pynths then try claiming again. (bool feesClaimable, bool anyRateIsInvalid) = _isFeesClaimableAndAnyRatesInvalid(claimingAddress); require(feesClaimable, "C-Ratio below penalty threshold"); require(!anyRateIsInvalid, "A pynth or PNX rate is invalid"); // Get the claimingAddress available fees and rewards (availableFees, availableRewards) = feesAvailable(claimingAddress); require( availableFees > 0 || availableRewards > 0, "No fees or rewards available for period, or fees already claimed" ); // Record the address has claimed for this period _setLastFeeWithdrawal(claimingAddress, _recentFeePeriodsStorage(1).feePeriodId); if (availableFees > 0) { // Record the fee payment in our recentFeePeriods feesPaid = _recordFeePayment(availableFees); // Send them their fees _payFees(claimingAddress, feesPaid); } if (availableRewards > 0) { // Record the reward payment in our recentFeePeriods rewardsPaid = _recordRewardPayment(availableRewards); // Send them their rewards _payRewards(claimingAddress, rewardsPaid); } emitFeesClaimed(claimingAddress, feesPaid, rewardsPaid); return true; } /** * @notice Admin function to import the FeePeriod data from the previous contract */ function importFeePeriod( uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed ) public optionalProxy_onlyOwner onlyDuringSetup { require(startingDebtIndex <= pynthetixState().debtLedgerLength(), "Cannot import bad data"); _recentFeePeriods[_currentFeePeriod.add(feePeriodIndex).mod(FEE_PERIOD_LENGTH)] = FeePeriod({ feePeriodId: uint64(feePeriodId), startingDebtIndex: uint64(startingDebtIndex), startTime: uint64(startTime), feesToDistribute: feesToDistribute, feesClaimed: feesClaimed, rewardsToDistribute: rewardsToDistribute, rewardsClaimed: rewardsClaimed }); } /** * @notice Record the fee payment in our recentFeePeriods. * @param sUSDAmount The amount of fees priced in sUSD. */ function _recordFeePayment(uint sUSDAmount) internal returns (uint) { // Don't assign to the parameter uint remainingToAllocate = sUSDAmount; uint feesPaid; // Start at the oldest period and record the amount, moving to newer periods // until we've exhausted the amount. // The condition checks for overflow because we're going to 0 with an unsigned int. for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) { uint feesAlreadyClaimed = _recentFeePeriodsStorage(i).feesClaimed; uint delta = _recentFeePeriodsStorage(i).feesToDistribute.sub(feesAlreadyClaimed); if (delta > 0) { // Take the smaller of the amount left to claim in the period and the amount we need to allocate uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate; _recentFeePeriodsStorage(i).feesClaimed = feesAlreadyClaimed.add(amountInPeriod); remainingToAllocate = remainingToAllocate.sub(amountInPeriod); feesPaid = feesPaid.add(amountInPeriod); // No need to continue iterating if we've recorded the whole amount; if (remainingToAllocate == 0) return feesPaid; // We've exhausted feePeriods to distribute and no fees remain in last period // User last to claim would in this scenario have their remainder slashed if (i == 0 && remainingToAllocate > 0) { remainingToAllocate = 0; } } } return feesPaid; } /** * @notice Record the reward payment in our recentFeePeriods. * @param snxAmount The amount of PNX tokens. */ function _recordRewardPayment(uint snxAmount) internal returns (uint) { // Don't assign to the parameter uint remainingToAllocate = snxAmount; uint rewardPaid; // Start at the oldest period and record the amount, moving to newer periods // until we've exhausted the amount. // The condition checks for overflow because we're going to 0 with an unsigned int. for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) { uint toDistribute = _recentFeePeriodsStorage(i).rewardsToDistribute.sub( _recentFeePeriodsStorage(i).rewardsClaimed ); if (toDistribute > 0) { // Take the smaller of the amount left to claim in the period and the amount we need to allocate uint amountInPeriod = toDistribute < remainingToAllocate ? toDistribute : remainingToAllocate; _recentFeePeriodsStorage(i).rewardsClaimed = _recentFeePeriodsStorage(i).rewardsClaimed.add(amountInPeriod); remainingToAllocate = remainingToAllocate.sub(amountInPeriod); rewardPaid = rewardPaid.add(amountInPeriod); // No need to continue iterating if we've recorded the whole amount; if (remainingToAllocate == 0) return rewardPaid; // We've exhausted feePeriods to distribute and no rewards remain in last period // User last to claim would in this scenario have their remainder slashed // due to rounding up of PreciseDecimal if (i == 0 && remainingToAllocate > 0) { remainingToAllocate = 0; } } } return rewardPaid; } /** * @notice Send the fees to claiming address. * @param account The address to send the fees to. * @param sUSDAmount The amount of fees priced in sUSD. */ function _payFees(address account, uint sUSDAmount) internal notFeeAddress(account) { // Grab the sUSD Pynth IPynth sUSDPynth = issuer().pynths(sUSD); // NOTE: we do not control the FEE_ADDRESS so it is not possible to do an // ERC20.approve() transaction to allow this feePool to call ERC20.transferFrom // to the accounts address // Burn the source amount sUSDPynth.burn(FEE_ADDRESS, sUSDAmount); // Mint their new pynths sUSDPynth.issue(account, sUSDAmount); } /** * @notice Send the rewards to claiming address - will be locked in rewardEscrow. * @param account The address to send the fees to. * @param snxAmount The amount of PNX. */ function _payRewards(address account, uint snxAmount) internal notFeeAddress(account) { /* Escrow the tokens for 1 year. */ uint escrowDuration = 52 weeks; // Record vesting entry for claiming address and amount // PNX already minted to rewardEscrow balance rewardEscrowV2().appendVestingEntry(account, snxAmount, escrowDuration); } /** * @notice The total fees available in the system to be withdrawnn in sUSD */ function totalFeesAvailable() external view returns (uint) { uint totalFees = 0; // Fees in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute); totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed); } return totalFees; } /** * @notice The total PNX rewards available in the system to be withdrawn */ function totalRewardsAvailable() external view returns (uint) { uint totalRewards = 0; // Rewards in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute); totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed); } return totalRewards; } /** * @notice The fees available to be withdrawn by a specific account, priced in sUSD * @dev Returns two amounts, one for fees and one for PNX rewards */ function feesAvailable(address account) public view returns (uint, uint) { // Add up the fees uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account); uint totalFees = 0; uint totalRewards = 0; // Fees & Rewards in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(userFees[i][0]); totalRewards = totalRewards.add(userFees[i][1]); } // And convert totalFees to sUSD // Return totalRewards as is in PNX amount return (totalFees, totalRewards); } function _isFeesClaimableAndAnyRatesInvalid(address account) internal view returns (bool, bool) { // Threshold is calculated from ratio % above the target ratio (issuanceRatio). // 0 < 10%: Claimable // 10% > above: Unable to claim (uint ratio, bool anyRateIsInvalid) = issuer().collateralisationRatioAndAnyRatesInvalid(account); uint targetRatio = getIssuanceRatio(); // Claimable if collateral ratio below target ratio if (ratio < targetRatio) { return (true, anyRateIsInvalid); } // Calculate the threshold for collateral ratio before fees can't be claimed. uint ratio_threshold = targetRatio.multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold())); // Not claimable if collateral ratio above threshold if (ratio > ratio_threshold) { return (false, anyRateIsInvalid); } return (true, anyRateIsInvalid); } function isFeesClaimable(address account) external view returns (bool feesClaimable) { (feesClaimable, ) = _isFeesClaimableAndAnyRatesInvalid(account); } /** * @notice Calculates fees by period for an account, priced in sUSD * @param account The address you want to query the fees for */ function feesByPeriod(address account) public view returns (uint[2][FEE_PERIOD_LENGTH] memory results) { // What's the user's debt entry index and the debt they owe to the system at current feePeriod uint userOwnershipPercentage; uint debtEntryIndex; FeePoolState _feePoolState = feePoolState(); (userOwnershipPercentage, debtEntryIndex) = _feePoolState.getAccountsDebtEntry(account, 0); // If they don't have any debt ownership and they never minted, they don't have any fees. // User ownership can reduce to 0 if user burns all pynths, // however they could have fees applicable for periods they had minted in before so we check debtEntryIndex. if (debtEntryIndex == 0 && userOwnershipPercentage == 0) { uint[2][FEE_PERIOD_LENGTH] memory nullResults; return nullResults; } // The [0] fee period is not yet ready to claim, but it is a fee period that they can have // fees owing for, so we need to report on it anyway. uint feesFromPeriod; uint rewardsFromPeriod; (feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(0, userOwnershipPercentage, debtEntryIndex); results[0][0] = feesFromPeriod; results[0][1] = rewardsFromPeriod; // Retrieve user's last fee claim by periodId uint lastFeeWithdrawal = getLastFeeWithdrawal(account); // Go through our fee periods from the oldest feePeriod[FEE_PERIOD_LENGTH - 1] and figure out what we owe them. // Condition checks for periods > 0 for (uint i = FEE_PERIOD_LENGTH - 1; i > 0; i--) { uint next = i - 1; uint nextPeriodStartingDebtIndex = _recentFeePeriodsStorage(next).startingDebtIndex; // We can skip the period, as no debt minted during period (next period's startingDebtIndex is still 0) if (nextPeriodStartingDebtIndex > 0 && lastFeeWithdrawal < _recentFeePeriodsStorage(i).feePeriodId) { // We calculate a feePeriod's closingDebtIndex by looking at the next feePeriod's startingDebtIndex // we can use the most recent issuanceData[0] for the current feePeriod // else find the applicableIssuanceData for the feePeriod based on the StartingDebtIndex of the period uint closingDebtIndex = uint256(nextPeriodStartingDebtIndex).sub(1); // Gas optimisation - to reuse debtEntryIndex if found new applicable one // if applicable is 0,0 (none found) we keep most recent one from issuanceData[0] // return if userOwnershipPercentage = 0) (userOwnershipPercentage, debtEntryIndex) = _feePoolState.applicableIssuanceData(account, closingDebtIndex); (feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(i, userOwnershipPercentage, debtEntryIndex); results[i][0] = feesFromPeriod; results[i][1] = rewardsFromPeriod; } } } /** * @notice ownershipPercentage is a high precision decimals uint based on * wallet's debtPercentage. Gives a precise amount of the feesToDistribute * for fees in the period. Precision factor is removed before results are * returned. * @dev The reported fees owing for the current period [0] are just a * running balance until the fee period closes */ function _feesAndRewardsFromPeriod( uint period, uint ownershipPercentage, uint debtEntryIndex ) internal view returns (uint, uint) { // If it's zero, they haven't issued, and they have no fees OR rewards. if (ownershipPercentage == 0) return (0, 0); uint debtOwnershipForPeriod = ownershipPercentage; // If period has closed we want to calculate debtPercentage for the period if (period > 0) { uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1); debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex); } // Calculate their percentage of the fees / rewards in this period // This is a high precision integer. uint feesFromPeriod = _recentFeePeriodsStorage(period).feesToDistribute.multiplyDecimal(debtOwnershipForPeriod); uint rewardsFromPeriod = _recentFeePeriodsStorage(period).rewardsToDistribute.multiplyDecimal( debtOwnershipForPeriod ); return (feesFromPeriod.preciseDecimalToDecimal(), rewardsFromPeriod.preciseDecimalToDecimal()); } function _effectiveDebtRatioForPeriod( uint closingDebtIndex, uint ownershipPercentage, uint debtEntryIndex ) internal view returns (uint) { // Figure out their global debt percentage delta at end of fee Period. // This is a high precision integer. IPynthetixState _pynthetixState = pynthetixState(); uint feePeriodDebtOwnership = _pynthetixState .debtLedger(closingDebtIndex) .divideDecimalRoundPrecise(_pynthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(ownershipPercentage); return feePeriodDebtOwnership; } function effectiveDebtRatioForPeriod(address account, uint period) external view returns (uint) { require(period != 0, "Current period is not closed yet"); require(period < FEE_PERIOD_LENGTH, "Exceeds the FEE_PERIOD_LENGTH"); // If the period being checked is uninitialised then return 0. This is only at the start of the system. if (_recentFeePeriodsStorage(period - 1).startingDebtIndex == 0) return 0; uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1); uint ownershipPercentage; uint debtEntryIndex; (ownershipPercentage, debtEntryIndex) = feePoolState().applicableIssuanceData(account, closingDebtIndex); // internal function will check closingDebtIndex has corresponding debtLedger entry return _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex); } /** * @notice Get the feePeriodID of the last claim this account made * @param _claimingAddress account to check the last fee period ID claim for * @return uint of the feePeriodID this account last claimed */ function getLastFeeWithdrawal(address _claimingAddress) public view returns (uint) { return feePoolEternalStorage().getUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress))); } /** * @notice Calculate the collateral ratio before user is blocked from claiming. */ function getPenaltyThresholdRatio() public view returns (uint) { return getIssuanceRatio().multiplyDecimal(SafeDecimalMath.unit().add(getTargetThreshold())); } /** * @notice Set the feePeriodID of the last claim this account made * @param _claimingAddress account to set the last feePeriodID claim for * @param _feePeriodID the feePeriodID this account claimed fees for */ function _setLastFeeWithdrawal(address _claimingAddress, uint _feePeriodID) internal { feePoolEternalStorage().setUIntValue( keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress)), _feePeriodID ); } /* ========== Modifiers ========== */ modifier onlyInternalContracts { bool isExchanger = msg.sender == address(exchanger()); bool isPynth = issuer().pynthsByAddress(msg.sender) != bytes32(0); bool isEtherCollateralsUSD = msg.sender == address(etherCollateralsUSD()); bool isCollateral = collateralManager().hasCollateral(msg.sender); require(isExchanger || isPynth || isEtherCollateralsUSD || isCollateral, "Only Internal Contracts"); _; } modifier onlyIssuer { require(msg.sender == address(issuer()), "FeePool: Only Issuer Authorised"); _; } modifier notFeeAddress(address account) { require(account != FEE_ADDRESS, "Fee address not allowed"); _; } modifier issuanceActive() { systemStatus().requireIssuanceActive(); _; } /* ========== Proxy Events ========== */ event IssuanceDebtRatioEntry( address indexed account, uint debtRatio, uint debtEntryIndex, uint feePeriodStartingDebtIndex ); bytes32 private constant ISSUANCEDEBTRATIOENTRY_SIG = keccak256( "IssuanceDebtRatioEntry(address,uint256,uint256,uint256)" ); function emitIssuanceDebtRatioEntry( address account, uint debtRatio, uint debtEntryIndex, uint feePeriodStartingDebtIndex ) internal { proxy._emit( abi.encode(debtRatio, debtEntryIndex, feePeriodStartingDebtIndex), 2, ISSUANCEDEBTRATIOENTRY_SIG, bytes32(uint256(uint160(account))), 0, 0 ); } event FeePeriodClosed(uint feePeriodId); bytes32 private constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)"); function emitFeePeriodClosed(uint feePeriodId) internal { proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0); } event FeesClaimed(address account, uint sUSDAmount, uint snxRewards); bytes32 private constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256,uint256)"); function emitFeesClaimed( address account, uint sUSDAmount, uint snxRewards ) internal { proxy._emit(abi.encode(account, sUSDAmount, snxRewards), 1, FEESCLAIMED_SIG, 0, 0, 0); } }
37,272