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
196
// If requested, Assert Block is Finalized
if eq(assertFinalized, 1) { assertOrInvalidProof(gte( number(), safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // ethBlock + delay ), ErrorCode_BlockNotFinalized) }
if eq(assertFinalized, 1) { assertOrInvalidProof(gte( number(), safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // ethBlock + delay ), ErrorCode_BlockNotFinalized) }
21,524
457
// attempt to notify delegate
if (delegate.isContract()) {
if (delegate.isContract()) {
41,996
27
// Check whether a given action is queued._vault The target vault. actionHashHash of the action to be checked.return Boolean `true` if the underlying action of `actionHash` is queued, otherwise `false`./
function isActionQueued( address _vault, bytes32 actionHash ) public view returns (bool)
function isActionQueued( address _vault, bytes32 actionHash ) public view returns (bool)
27,118
1,240
// Calcualted the ratio of debt / adjusted collateral/_user Address of the user
function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); }
function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); }
55,235
42
// Gets the actual index of the blacklisted address in "__blacklistedAddresses" array. /
function _getBlacklistedIndex( address _blacklisted
function _getBlacklistedIndex( address _blacklisted
39,102
10
// Constructor function Initializes contract with initial supply tokens to the creator of the contract /
function TokenERC20() public { totalSupply = 90000000* 10 ** uint256(decimals); // Updating total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Giving the creator all initial tokens name = "Lehman Brothers Coin"; // Setting the name for display purposes symbol = "LBC"; }
function TokenERC20() public { totalSupply = 90000000* 10 ** uint256(decimals); // Updating total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Giving the creator all initial tokens name = "Lehman Brothers Coin"; // Setting the name for display purposes symbol = "LBC"; }
24,346
90
// Stakes the specified `amount` of tokens, this will attempt to transfer the given amount from the caller. It will count the actual number of tokens trasferred as being staked MUST trigger Staked event. Returns the number of tokens actually staked/
function stake(uint256 amount) external override nonReentrant returns (uint256){ require(amount > 0, "Cannot Stake 0"); uint256 previousAmount = IERC20(_token).balanceOf(address(this)); _token.safeTransferFrom( msg.sender, address(this), amount); uint256 transferred = IERC20(_token).balanceOf(address(this)) - previousAmount; require(transferred > 0); stakes[msg.sender].totalStake = stakes[msg.sender].totalStake + transferred; stakes[msg.sender].stakedAmount[msg.sender] = stakes[msg.sender].stakedAmount[msg.sender] + transferred; _totalStaked = _totalStaked + transferred; emit Staked(msg.sender, msg.sender, msg.sender, transferred); return transferred; }
function stake(uint256 amount) external override nonReentrant returns (uint256){ require(amount > 0, "Cannot Stake 0"); uint256 previousAmount = IERC20(_token).balanceOf(address(this)); _token.safeTransferFrom( msg.sender, address(this), amount); uint256 transferred = IERC20(_token).balanceOf(address(this)) - previousAmount; require(transferred > 0); stakes[msg.sender].totalStake = stakes[msg.sender].totalStake + transferred; stakes[msg.sender].stakedAmount[msg.sender] = stakes[msg.sender].stakedAmount[msg.sender] + transferred; _totalStaked = _totalStaked + transferred; emit Staked(msg.sender, msg.sender, msg.sender, transferred); return transferred; }
45,177
46
// Returns the subtraction of two unsigned integers, reverting with custom message onoverflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow. /
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
542
252
// Wrap ETH.
WETH.deposit{value: depositAmount}();
WETH.deposit{value: depositAmount}();
2,592
15
// function buyTokens(uint _numberOfTokens)
// returns (bool success) { // success = tokenContract.approve(address(this), _numberOfTokens) // && tokenContract.transfer(address(this), _numberOfTokens) // && tokenContract.transferFrom(address(this), msg.sender, multiply(_numberOfTokens, tokenPrice)); // if (!success) throw; // }
// returns (bool success) { // success = tokenContract.approve(address(this), _numberOfTokens) // && tokenContract.transfer(address(this), _numberOfTokens) // && tokenContract.transferFrom(address(this), msg.sender, multiply(_numberOfTokens, tokenPrice)); // if (!success) throw; // }
26,252
31
// tested/
function withdrawEth() public onlyAdmin returns (bool)
function withdrawEth() public onlyAdmin returns (bool)
45,070
149
// Add the market to the markets mapping and set it as listed Admin function to set isListed and add support for the market jToken The address of the market (token) to list version The version of the market (token)return uint 0=success, otherwise a failure. (See enum Error for details) /
function _supportMarket(JToken jToken, Version version) external returns (uint256) { require(msg.sender == admin, "only admin may support market"); require(!isMarketListed(address(jToken)), "market already listed"); jToken.isJToken(); // Sanity check to make sure its really a JToken markets[address(jToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(jToken)); emit MarketListed(jToken); return uint256(Error.NO_ERROR); }
function _supportMarket(JToken jToken, Version version) external returns (uint256) { require(msg.sender == admin, "only admin may support market"); require(!isMarketListed(address(jToken)), "market already listed"); jToken.isJToken(); // Sanity check to make sure its really a JToken markets[address(jToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(jToken)); emit MarketListed(jToken); return uint256(Error.NO_ERROR); }
8,636
99
// Refund surplus tokens.
uint256 _balance = token.balanceOf(address(this)); uint256 _surplus = _balance.sub(totalTokenUnits); emit SurplusTokensRefunded(crowdsaleOwner, _surplus); if (_surplus > 0) {
uint256 _balance = token.balanceOf(address(this)); uint256 _surplus = _balance.sub(totalTokenUnits); emit SurplusTokensRefunded(crowdsaleOwner, _surplus); if (_surplus > 0) {
42,929
219
// Set the color
colorBytes[k][placeFrame] = abi.encodePacked( colorFrame )[0]; placedPixels[k][placeFrame] = true;
colorBytes[k][placeFrame] = abi.encodePacked( colorFrame )[0]; placedPixels[k][placeFrame] = true;
34,322
29
// See {BEP20-balanceOf}. /
function balanceOf(address account) external view returns (uint256) {
function balanceOf(address account) external view returns (uint256) {
15,859
4
// deposit underlying currency, underwriting calls of that currency with respect to base currency amount quantity of underlying currency to deposit isCallPool whether to deposit underlying in the call pool or base in the put pool skipWethDeposit if false, will not try to deposit weth from attach eth /
function _deposit( uint256 amount, bool isCallPool, bool skipWethDeposit
function _deposit( uint256 amount, bool isCallPool, bool skipWethDeposit
48,270
207
// NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded`
uint256 _existingLiquidAssets = wantBalance(); if (_existingLiquidAssets >= _amountNeeded) { return (_amountNeeded, 0); }
uint256 _existingLiquidAssets = wantBalance(); if (_existingLiquidAssets >= _amountNeeded) { return (_amountNeeded, 0); }
43,759
20
// UpgradeabilityStorage This contract holds all the necessary state variables to support the upgrade functionality /
contract UpgradeabilityStorage { // Version name of the current implementation uint256 internal _version; // Address of the current implementation address internal _implementation; /** * @dev Tells the version name of the current implementation * @return uint256 representing the name of the current version */ function version() external view returns (uint256) { return _version; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } }
contract UpgradeabilityStorage { // Version name of the current implementation uint256 internal _version; // Address of the current implementation address internal _implementation; /** * @dev Tells the version name of the current implementation * @return uint256 representing the name of the current version */ function version() external view returns (uint256) { return _version; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } }
6,501
7
// ----> ReviewsCount
mapping(uint256 => Review) public reviews; uint256 public numberOfReviews = 0;
mapping(uint256 => Review) public reviews; uint256 public numberOfReviews = 0;
7,339
19
// This check tries to make sure that a valid aggregator is being added. It checks if the aggregator is an existing smart contract that has implemented `latestTimestamp` function.
require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (address(aggregators[currencyKey]) == address(0)) { aggregatorKeys.push(currencyKey); }
require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (address(aggregators[currencyKey]) == address(0)) { aggregatorKeys.push(currencyKey); }
38,852
27
// Set up the member: status, name, `member since` & `inactive since`.
members_[_memberId] = Member(true, _memberName, "", uint64(now), 0);
members_[_memberId] = Member(true, _memberName, "", uint64(now), 0);
24,968
205
// returns the remaining supply
function publicSupply() external view returns (uint256) { uint256 amount = maxSupply - totalSupply(); return amount; }
function publicSupply() external view returns (uint256) { uint256 amount = maxSupply - totalSupply(); return amount; }
13,741
159
// keep in mind votes which others could have delegated
_computeUserData(latestData, data, delegatables[account]) ); delegatables[account] = data;
_computeUserData(latestData, data, delegatables[account]) ); delegatables[account] = data;
38,047
3
// Queries the fillable taker asset amounts of native orders./orders Native orders to query./orderSignatures Signatures for each respective order in `orders`./ return orderFillableTakerAssetAmounts How much taker asset can be filled/ by each order in `orders`.
function getOrderFillableTakerAssetAmounts( LibOrder.Order[] calldata orders, bytes[] calldata orderSignatures ) external view returns (uint256[] memory orderFillableTakerAssetAmounts);
function getOrderFillableTakerAssetAmounts( LibOrder.Order[] calldata orders, bytes[] calldata orderSignatures ) external view returns (uint256[] memory orderFillableTakerAssetAmounts);
28,144
34
// log the addition of the new validator
emit ValidatorAdded(validator, description);
emit ValidatorAdded(validator, description);
34,617
117
// Deprecated
(uint256 rAmount, , , , , ) = _getValues(tAmount); //WORKSPACE ZZ
(uint256 rAmount, , , , , ) = _getValues(tAmount); //WORKSPACE ZZ
21,063
26
// modifier for owner only /
modifier owned() { ownly(); _; }
modifier owned() { ownly(); _; }
27,002
137
// Binary search to estimate timestamp for block number/_block Block to find/max_epoch Don't go beyond this epoch/ return Approximate timestamp for block
function _find_block_epoch(uint _block, uint max_epoch) internal view returns (uint) { // Binary search uint _min = 0; uint _max = max_epoch; for (uint i = 0; i < 128; ++i) { // Will be always enough for 128-bit numbers if (_min >= _max) { break; } uint _mid = (_min + _max + 1) / 2; if (point_history[_mid].blk <= _block) { _min = _mid; } else { _max = _mid - 1; } } return _min; }
function _find_block_epoch(uint _block, uint max_epoch) internal view returns (uint) { // Binary search uint _min = 0; uint _max = max_epoch; for (uint i = 0; i < 128; ++i) { // Will be always enough for 128-bit numbers if (_min >= _max) { break; } uint _mid = (_min + _max + 1) / 2; if (point_history[_mid].blk <= _block) { _min = _mid; } else { _max = _mid - 1; } } return _min; }
12,703
208
// Expose Vars
function curId() public view returns (uint32) { return vars.curId; }
function curId() public view returns (uint32) { return vars.curId; }
57,135
23
// mint allows an user to mint 1 NFT per transaction after the presale has ended. /
function mint() public payable onlyWhenNotPaused returns (uint256) { require( block.timestamp > timeToEndPresale, "Presale has not ended yet" ); require( totalSupply() < maxTokenIds, "Exceeded maximum Eager Beavers supply" ); require(msg.value >= _price, "Invalid Ether amount sent"); currentId.increment(); tokenCount.increment(); // skip any already minted NFTs while (_exists(currentId.current())) { currentId.increment(); } uint256 tokenId = currentId.current(); _safeMint(msg.sender, tokenId); return tokenId; }
function mint() public payable onlyWhenNotPaused returns (uint256) { require( block.timestamp > timeToEndPresale, "Presale has not ended yet" ); require( totalSupply() < maxTokenIds, "Exceeded maximum Eager Beavers supply" ); require(msg.value >= _price, "Invalid Ether amount sent"); currentId.increment(); tokenCount.increment(); // skip any already minted NFTs while (_exists(currentId.current())) { currentId.increment(); } uint256 tokenId = currentId.current(); _safeMint(msg.sender, tokenId); return tokenId; }
66,563
25
// Stores INTEREST ACCOUNT details of the USER
struct InterestAccount { uint256 amount; uint256 time; uint256 interestRate; uint256 interestPayouts; uint256 timeperiod; uint256 proposalId; bool withdrawn; }
struct InterestAccount { uint256 amount; uint256 time; uint256 interestRate; uint256 interestPayouts; uint256 timeperiod; uint256 proposalId; bool withdrawn; }
20,843
0
// Unit test interface /
contract TestCase { /* This field is a short test description */ string public name; /** @dev This method contains single check * and returns true when all is OK */ function run() public returns (bool); }
contract TestCase { /* This field is a short test description */ string public name; /** @dev This method contains single check * and returns true when all is OK */ function run() public returns (bool); }
36,261
34
// Given X, find Y where y = sqrt(x^3 + b) Returns: (x^3 + b), y/
function findYFromX(uint256 x) internal view returns(uint256, uint256)
function findYFromX(uint256 x) internal view returns(uint256, uint256)
29,678
13
// Gets the gas basefee cost to calculate keeper rewards/Keepers are required to pay a priority fee to be included, this function recognizes a minimum priority fee/ return _baseFee The block's basefee + a minimum priority fee, or a preset minimum gas fee
function _getBasefee() internal view virtual returns (uint256 _baseFee) { return Math.max(minBaseFee, block.basefee + minPriorityFee); }
function _getBasefee() internal view virtual returns (uint256 _baseFee) { return Math.max(minBaseFee, block.basefee + minPriorityFee); }
255
28
// Appends a bytes20 to the buffer. Resizes if doing so would exceedthe capacity of the buffer.buf The buffer to append to.data The data to append. return The original buffer, for chhaining./
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); }
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); }
64,399
5
// Kill the contract, and return contract funds to the message sender.Only the issuer is allowed to call this function.Important: Permissions should be set for any function that can call the selfdestruct function because otherwise, anyone might be able to kill the contract. /
function killContract() public ifIssuer { selfdestruct(msg.sender); }
function killContract() public ifIssuer { selfdestruct(msg.sender); }
17,866
124
// NFT lending vault/This contracts allows users to borrow PUSD using NFTs as collateral./ The floor price of the NFT collection is fetched using a chainlink oracle, while some other more valuable traits/ can have an higher price set by the DAO. Users can also increase the price (and thus the borrow limit) of their/ NFT by submitting a governance proposal. If the proposal is approved the user can lock a percentage of the new price/ worth of JPEG to make it effective
contract NFTVault is AccessControlUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeERC20Upgradeable for IStableCoin; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; event PositionOpened(address indexed owner, uint256 indexed index); event Borrowed( address indexed owner, uint256 indexed index, uint256 amount ); event Repaid(address indexed owner, uint256 indexed index, uint256 amount); event PositionClosed(address indexed owner, uint256 indexed index); event Liquidated( address indexed liquidator, address indexed owner, uint256 indexed index, bool insured ); event Repurchased(address indexed owner, uint256 indexed index); event InsuranceExpired(address indexed owner, uint256 indexed index); enum BorrowType { NOT_CONFIRMED, NON_INSURANCE, USE_INSURANCE } struct Position { BorrowType borrowType; uint256 debtPrincipal; uint256 debtPortion; uint256 debtAmountForRepurchase; uint256 liquidatedAt; address liquidator; } struct Rate { uint128 numerator; uint128 denominator; } struct VaultSettings { Rate debtInterestApr; Rate creditLimitRate; Rate liquidationLimitRate; Rate cigStakedCreditLimitRate; Rate cigStakedLiquidationLimitRate; Rate valueIncreaseLockRate; Rate organizationFeeRate; Rate insurancePurchaseRate; Rate insuranceLiquidationPenaltyRate; uint256 insuranceRepurchaseTimeLimit; uint256 borrowAmountCap; } bytes32 public constant DAO_ROLE = keccak256("DAO_ROLE"); bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE"); bytes32 public constant CUSTOM_NFT_HASH = keccak256("CUSTOM"); IStableCoin public stablecoin; /// @notice Chainlink ETH/USD price feed IAggregatorV3Interface public ethAggregator; /// @notice Chainlink JPEG/USD price feed IAggregatorV3Interface public jpegAggregator; /// @notice Chainlink NFT floor oracle IAggregatorV3Interface public floorOracle; /// @notice Chainlink NFT fallback floor oracle IAggregatorV3Interface public fallbackOracle; /// @notice JPEGLocker, used by this contract to lock JPEG and increase the value of an NFT IJPEGLock public jpegLocker; /// @notice JPEGCardsCigStaking, cig stakers get an higher credit limit rate and liquidation limit rate. /// Immediately reverts to normal rates if the cig is unstaked. IJPEGCardsCigStaking public cigStaking; IERC721Upgradeable public nftContract; /// @notice If true, the floor price won't be fetched using the Chainlink oracle but /// a value set by the DAO will be used instead bool public daoFloorOverride; // @notice If true, the floor price will be fetched using the fallback oracle bool public useFallbackOracle; /// @notice Total outstanding debt uint256 public totalDebtAmount; /// @dev Last time debt was accrued. See {accrue} for more info uint256 public totalDebtAccruedAt; uint256 public totalFeeCollected; uint256 internal totalDebtPortion; VaultSettings public settings; /// @dev Keeps track of all the NFTs used as collateral for positions EnumerableSetUpgradeable.UintSet private positionIndexes; mapping(uint256 => Position) private positions; mapping(uint256 => address) public positionOwner; mapping(bytes32 => uint256) public nftTypeValueETH; mapping(uint256 => uint256) public nftValueETH; //bytes32(0) is floor mapping(uint256 => bytes32) public nftTypes; mapping(uint256 => uint256) public pendingNFTValueETH; /// @dev Checks if the provided NFT index is valid /// @param nftIndex The index to check modifier validNFTIndex(uint256 nftIndex) { //The standard OZ ERC721 implementation of ownerOf reverts on a non existing nft isntead of returning address(0) require(nftContract.ownerOf(nftIndex) != address(0), "invalid_nft"); _; } struct NFTCategoryInitializer { bytes32 hash; uint256 valueETH; uint256[] nfts; } /// @param _stablecoin PUSD address /// @param _nftContract The NFT contrat address. It could also be the address of an helper contract /// if the target NFT isn't an ERC721 (CryptoPunks as an example) /// @param _ethAggregator Chainlink ETH/USD price feed address /// @param _floorOracle Chainlink floor oracle address /// @param _typeInitializers Used to initialize NFT categories with their value and NFT indexes. /// Floor NFT shouldn't be initialized this way /// @param _settings Initial settings used by the contract function initialize( IStableCoin _stablecoin, IERC721Upgradeable _nftContract, IAggregatorV3Interface _ethAggregator, IAggregatorV3Interface _floorOracle, NFTCategoryInitializer[] calldata _typeInitializers, IJPEGCardsCigStaking _cigStaking, VaultSettings calldata _settings ) external initializer { __AccessControl_init(); __ReentrancyGuard_init(); _setupRole(DAO_ROLE, msg.sender); _setRoleAdmin(LIQUIDATOR_ROLE, DAO_ROLE); _setRoleAdmin(DAO_ROLE, DAO_ROLE); _validateRate(_settings.debtInterestApr); _validateRate(_settings.creditLimitRate); _validateRate(_settings.liquidationLimitRate); _validateRate(_settings.cigStakedCreditLimitRate); _validateRate(_settings.cigStakedLiquidationLimitRate); _validateRate(_settings.valueIncreaseLockRate); _validateRate(_settings.organizationFeeRate); _validateRate(_settings.insurancePurchaseRate); _validateRate(_settings.insuranceLiquidationPenaltyRate); require( _greaterThan( _settings.liquidationLimitRate, _settings.creditLimitRate ), "invalid_liquidation_limit" ); require( _greaterThan( _settings.cigStakedLiquidationLimitRate, _settings.cigStakedCreditLimitRate ), "invalid_cig_liquidation_limit" ); require( _greaterThan( _settings.cigStakedCreditLimitRate, _settings.creditLimitRate ), "invalid_cig_credit_limit" ); require( _greaterThan( _settings.cigStakedLiquidationLimitRate, _settings.liquidationLimitRate ), "invalid_cig_liquidation_limit" ); stablecoin = _stablecoin; ethAggregator = _ethAggregator; floorOracle = _floorOracle; cigStaking = _cigStaking; nftContract = _nftContract; settings = _settings; //initializing the categories for (uint256 i; i < _typeInitializers.length; ++i) { NFTCategoryInitializer memory initializer = _typeInitializers[i]; nftTypeValueETH[initializer.hash] = initializer.valueETH; for (uint256 j; j < initializer.nfts.length; j++) { nftTypes[initializer.nfts[j]] = initializer.hash; } } } /// @dev The {accrue} function updates the contract's state by calculating /// the additional interest accrued since the last state update function accrue() public { uint256 additionalInterest = _calculateAdditionalInterest(); totalDebtAccruedAt = block.timestamp; totalDebtAmount += additionalInterest; totalFeeCollected += additionalInterest; } /// @notice Allows the DAO to change the total debt cap /// @param _borrowAmountCap New total debt cap function setBorrowAmountCap(uint256 _borrowAmountCap) external onlyRole(DAO_ROLE) { settings.borrowAmountCap = _borrowAmountCap; } /// @notice Allows the DAO to change the interest APR on borrows /// @param _debtInterestApr The new interest rate function setDebtInterestApr(Rate calldata _debtInterestApr) external onlyRole(DAO_ROLE) { _validateRate(_debtInterestApr); accrue(); settings.debtInterestApr = _debtInterestApr; } /// @notice Allows the DAO to change the amount of JPEG needed to increase the value of an NFT relative to the desired value /// @param _valueIncreaseLockRate The new rate function setValueIncreaseLockRate(Rate calldata _valueIncreaseLockRate) external onlyRole(DAO_ROLE) { _validateRate(_valueIncreaseLockRate); settings.valueIncreaseLockRate = _valueIncreaseLockRate; } /// @notice Allows the DAO to change the max debt to collateral rate for a position /// @param _creditLimitRate The new rate function setCreditLimitRate(Rate calldata _creditLimitRate) external onlyRole(DAO_ROLE) { _validateRate(_creditLimitRate); require( _greaterThan(settings.liquidationLimitRate, _creditLimitRate), "invalid_credit_limit" ); require( _greaterThan(settings.cigStakedCreditLimitRate, _creditLimitRate), "invalid_credit_limit" ); settings.creditLimitRate = _creditLimitRate; } /// @notice Allows the DAO to change the minimum debt to collateral rate for a position to be market as liquidatable /// @param _liquidationLimitRate The new rate function setLiquidationLimitRate(Rate calldata _liquidationLimitRate) external onlyRole(DAO_ROLE) { _validateRate(_liquidationLimitRate); require( _greaterThan(_liquidationLimitRate, settings.creditLimitRate), "invalid_liquidation_limit" ); require( _greaterThan( settings.cigStakedLiquidationLimitRate, _liquidationLimitRate ), "invalid_liquidation_limit" ); settings.liquidationLimitRate = _liquidationLimitRate; } /// @notice Allows the DAO to change the minimum debt to collateral rate for a position staking a cig to be market as liquidatable /// @param _cigLiquidationLimitRate The new rate function setStakedCigLiquidationLimitRate( Rate calldata _cigLiquidationLimitRate ) external onlyRole(DAO_ROLE) { _validateRate(_cigLiquidationLimitRate); require( _greaterThan( _cigLiquidationLimitRate, settings.cigStakedCreditLimitRate ), "invalid_cig_liquidation_limit" ); require( _greaterThan( _cigLiquidationLimitRate, settings.liquidationLimitRate ), "invalid_cig_liquidation_limit" ); settings.cigStakedLiquidationLimitRate = _cigLiquidationLimitRate; } /// @notice Allows the DAO to change the max debt to collateral rate for a position staking a cig /// @param _cigCreditLimitRate The new rate function setStakedCigCreditLimitRate(Rate calldata _cigCreditLimitRate) external onlyRole(DAO_ROLE) { _validateRate(_cigCreditLimitRate); require( _greaterThan( settings.cigStakedLiquidationLimitRate, _cigCreditLimitRate ), "invalid_cig_credit_limit" ); require( _greaterThan(_cigCreditLimitRate, settings.creditLimitRate), "invalid_cig_credit_limit" ); settings.cigStakedCreditLimitRate = _cigCreditLimitRate; } /// @notice Allows the DAO to set the JPEG oracle /// @param _aggregator new oracle address function setJPEGAggregator(IAggregatorV3Interface _aggregator) external onlyRole(DAO_ROLE) { require(address(_aggregator) != address(0), "invalid_address"); require(address(jpegAggregator) == address(0), "already_set"); jpegAggregator = _aggregator; } /// @notice Allows the DAO to change fallback oracle /// @param _fallback new fallback address function setFallbackOracle(IAggregatorV3Interface _fallback) external onlyRole(DAO_ROLE) { require(address(_fallback) != address(0), "invalid_address"); fallbackOracle = _fallback; } /// @notice Allows the DAO to toggle the fallback oracle /// @param _useFallback Whether to use the fallback oracle function toggleFallbackOracle(bool _useFallback) external onlyRole(DAO_ROLE) { require(address(fallbackOracle) != address(0), "fallback_not_set"); useFallbackOracle = _useFallback; } /// @notice Allows the DAO to set jpeg locker /// @param _jpegLocker The jpeg locker address function setJPEGLocker(IJPEGLock _jpegLocker) external onlyRole(DAO_ROLE) { require(address(_jpegLocker) != address(0), "invalid_address"); jpegLocker = _jpegLocker; } /// @notice Allows the DAO to change the amount of time JPEG tokens need to be locked to change the value of an NFT /// @param _newLockTime The amount new lock time amount function setJPEGLockTime(uint256 _newLockTime) external onlyRole(DAO_ROLE) { require(address(jpegLocker) != address(0), "no_jpeg_locker"); jpegLocker.setLockTime(_newLockTime); } /// @notice Allows the DAO to change the amount of time insurance remains valid after liquidation /// @param _newLimit New time limit function setInsuranceRepurchaseTimeLimit(uint256 _newLimit) external onlyRole(DAO_ROLE) { require(_newLimit != 0, "invalid_limit"); settings.insuranceRepurchaseTimeLimit = _newLimit; } /// @notice Allows the DAO to bypass the floor oracle and override the NFT floor value /// @param _newFloor The new floor function overrideFloor(uint256 _newFloor) external onlyRole(DAO_ROLE) { require(_newFloor != 0, "invalid_floor"); nftTypeValueETH[bytes32(0)] = _newFloor; daoFloorOverride = true; } /// @notice Allows the DAO to stop overriding floor function disableFloorOverride() external onlyRole(DAO_ROLE) { daoFloorOverride = false; } /// @notice Allows the DAO to change the static borrow fee /// @param _organizationFeeRate The new fee rate function setOrganizationFeeRate(Rate calldata _organizationFeeRate) external onlyRole(DAO_ROLE) { _validateRate(_organizationFeeRate); settings.organizationFeeRate = _organizationFeeRate; } /// @notice Allows the DAO to change the cost of insurance /// @param _insurancePurchaseRate The new insurance fee rate function setInsurancePurchaseRate(Rate calldata _insurancePurchaseRate) external onlyRole(DAO_ROLE) { _validateRate(_insurancePurchaseRate); settings.insurancePurchaseRate = _insurancePurchaseRate; } /// @notice Allows the DAO to change the repurchase penalty rate in case of liquidation of an insured NFT /// @param _insuranceLiquidationPenaltyRate The new rate function setInsuranceLiquidationPenaltyRate( Rate calldata _insuranceLiquidationPenaltyRate ) external onlyRole(DAO_ROLE) { _validateRate(_insuranceLiquidationPenaltyRate); settings .insuranceLiquidationPenaltyRate = _insuranceLiquidationPenaltyRate; } /// @notice Allows the DAO to add an NFT to a specific price category /// @param _nftIndex The index to add to the category /// @param _type The category hash function setNFTType(uint256 _nftIndex, bytes32 _type) external validNFTIndex(_nftIndex) onlyRole(DAO_ROLE) { require( _type == bytes32(0) || nftTypeValueETH[_type] != 0, "invalid_nftType" ); nftTypes[_nftIndex] = _type; } /// @notice Allows the DAO to change the value of an NFT category /// @param _type The category hash /// @param _amountETH The new value, in ETH function setNFTTypeValueETH(bytes32 _type, uint256 _amountETH) external onlyRole(DAO_ROLE) { nftTypeValueETH[_type] = _amountETH; } /// @notice Allows the DAO to set the value in ETH of the NFT at index `_nftIndex`. /// A JPEG deposit by a user is required afterwards. See {finalizePendingNFTValueETH} for more details /// @param _nftIndex The index of the NFT to change the value of /// @param _amountETH The new desired ETH value function setPendingNFTValueETH(uint256 _nftIndex, uint256 _amountETH) external validNFTIndex(_nftIndex) onlyRole(DAO_ROLE) { require(address(jpegLocker) != address(0), "no_jpeg_locker"); pendingNFTValueETH[_nftIndex] = _amountETH; } /// @notice Allows a user to lock up JPEG to make the change in value of an NFT effective. /// Can only be called after {setPendingNFTValueETH}, which requires a governance vote. /// @dev The amount of JPEG that needs to be locked is calculated by applying `valueIncreaseLockRate` /// to the new credit limit of the NFT /// @param _nftIndex The index of the NFT function finalizePendingNFTValueETH(uint256 _nftIndex) external validNFTIndex(_nftIndex) { require(address(jpegLocker) != address(0), "no_jpeg_locker"); uint256 pendingValue = pendingNFTValueETH[_nftIndex]; require(pendingValue != 0, "no_pending_value"); uint256 toLockJpeg = (((pendingValue * 1 ether * settings.creditLimitRate.numerator) / settings.creditLimitRate.denominator) * settings.valueIncreaseLockRate.numerator) / settings.valueIncreaseLockRate.denominator / _jpegPriceETH(); //lock JPEG using JPEGLock jpegLocker.lockFor(msg.sender, _nftIndex, toLockJpeg); nftTypes[_nftIndex] = CUSTOM_NFT_HASH; nftValueETH[_nftIndex] = pendingValue; //clear pending value pendingNFTValueETH[_nftIndex] = 0; } /// @dev Checks if `r1` is greater than `r2`. function _greaterThan(Rate memory _r1, Rate memory _r2) internal pure returns (bool) { return _r1.numerator * _r2.denominator > _r2.numerator * _r1.denominator; } /// @dev Validates a rate. The denominator must be greater than zero and greater than or equal to the numerator. /// @param rate The rate to validate function _validateRate(Rate calldata rate) internal pure { require( rate.denominator != 0 && rate.denominator >= rate.numerator, "invalid_rate" ); } /// @dev Returns the value in ETH of the NFT at index `_nftIndex` /// @param _nftIndex The NFT to return the value of /// @return The value of the NFT, 18 decimals function _getNFTValueETH(uint256 _nftIndex) internal view returns (uint256) { bytes32 nftType = nftTypes[_nftIndex]; if (nftType == bytes32(0) && !daoFloorOverride) { return _normalizeAggregatorAnswer( useFallbackOracle ? fallbackOracle : floorOracle ); } else if (nftType == CUSTOM_NFT_HASH) return nftValueETH[_nftIndex]; return nftTypeValueETH[nftType]; } /// @dev Returns the value in USD of the NFT at index `_nftIndex` /// @param _nftIndex The NFT to return the value of /// @return The value of the NFT in USD, 18 decimals function _getNFTValueUSD(uint256 _nftIndex) internal view returns (uint256) { uint256 nft_value = _getNFTValueETH(_nftIndex); return (nft_value * _ethPriceUSD()) / 1 ether; } /// @dev Returns the current ETH price in USD /// @return The current ETH price, 18 decimals function _ethPriceUSD() internal view returns (uint256) { return _normalizeAggregatorAnswer(ethAggregator); } /// @dev Returns the current JPEG price in ETH /// @return The current JPEG price, 18 decimals function _jpegPriceETH() internal view returns (uint256) { IAggregatorV3Interface aggregator = jpegAggregator; require(address(aggregator) != address(0), "jpeg_oracle_not_set"); return _normalizeAggregatorAnswer(aggregator); } /// @dev Fetches and converts to 18 decimals precision the latest answer of a Chainlink aggregator /// @param aggregator The aggregator to fetch the answer from /// @return The latest aggregator answer, normalized function _normalizeAggregatorAnswer(IAggregatorV3Interface aggregator) internal view returns (uint256) { (, int256 answer, , uint256 timestamp, ) = aggregator.latestRoundData(); require(answer > 0, "invalid_oracle_answer"); require(timestamp != 0, "round_incomplete"); uint8 decimals = aggregator.decimals(); unchecked { //converts the answer to have 18 decimals return decimals > 18 ? uint256(answer) / 10**(decimals - 18) : uint256(answer) * 10**(18 - decimals); } } struct NFTInfo { uint256 index; bytes32 nftType; address owner; uint256 nftValueETH; uint256 nftValueUSD; } /// @notice Returns data relative to the NFT at index `_nftIndex` /// @param _nftIndex The NFT index /// @return nftInfo The data relative to the NFT function getNFTInfo(uint256 _nftIndex) external view returns (NFTInfo memory nftInfo) { nftInfo = NFTInfo( _nftIndex, nftTypes[_nftIndex], nftContract.ownerOf(_nftIndex), _getNFTValueETH(_nftIndex), _getNFTValueUSD(_nftIndex) ); } /// @dev Returns the credit limit of an NFT /// @param _nftIndex The NFT to return credit limit of /// @return The NFT credit limit function _getCreditLimit(address user, uint256 _nftIndex) internal view returns (uint256) { uint256 value = _getNFTValueUSD(_nftIndex); if (cigStaking.isUserStaking(user)) { return (value * settings.cigStakedCreditLimitRate.numerator) / settings.cigStakedCreditLimitRate.denominator; } return (value * settings.creditLimitRate.numerator) / settings.creditLimitRate.denominator; } /// @dev Returns the minimum amount of debt necessary to liquidate an NFT /// @param _nftIndex The index of the NFT /// @return The minimum amount of debt to liquidate the NFT function _getLiquidationLimit(address user, uint256 _nftIndex) internal view returns (uint256) { uint256 value = _getNFTValueUSD(_nftIndex); if (cigStaking.isUserStaking(user)) { return (value * settings.cigStakedLiquidationLimitRate.numerator) / settings.cigStakedLiquidationLimitRate.denominator; } return (value * settings.liquidationLimitRate.numerator) / settings.liquidationLimitRate.denominator; } /// @dev Calculates current outstanding debt of an NFT /// @param _nftIndex The NFT to calculate the outstanding debt of /// @return The outstanding debt value function _getDebtAmount(uint256 _nftIndex) internal view returns (uint256) { uint256 calculatedDebt = _calculateDebt( totalDebtAmount, positions[_nftIndex].debtPortion, totalDebtPortion ); uint256 principal = positions[_nftIndex].debtPrincipal; //_calculateDebt is prone to rounding errors that may cause //the calculated debt amount to be 1 or 2 units less than //the debt principal when the accrue() function isn't called //in between the first borrow and the _calculateDebt call. return principal > calculatedDebt ? principal : calculatedDebt; } /// @dev Calculates the total debt of a position given the global debt, the user's portion of the debt and the total user portions /// @param total The global outstanding debt /// @param userPortion The user's portion of debt /// @param totalPortion The total user portions of debt /// @return The outstanding debt of the position function _calculateDebt( uint256 total, uint256 userPortion, uint256 totalPortion ) internal pure returns (uint256) { return totalPortion == 0 ? 0 : (total * userPortion) / totalPortion; } /// @dev Opens a position /// Emits a {PositionOpened} event /// @param _owner The owner of the position to open /// @param _nftIndex The NFT used as collateral for the position function _openPosition(address _owner, uint256 _nftIndex) internal { positionOwner[_nftIndex] = _owner; positionIndexes.add(_nftIndex); nftContract.transferFrom(_owner, address(this), _nftIndex); emit PositionOpened(_owner, _nftIndex); } /// @dev Calculates the additional global interest since last time the contract's state was updated by calling {accrue} /// @return The additional interest value function _calculateAdditionalInterest() internal view returns (uint256) { // Number of seconds since {accrue} was called uint256 elapsedTime = block.timestamp - totalDebtAccruedAt; if (elapsedTime == 0) { return 0; } uint256 totalDebt = totalDebtAmount; if (totalDebt == 0) { return 0; } // Accrue interest return (elapsedTime * totalDebt * settings.debtInterestApr.numerator) / settings.debtInterestApr.denominator / 365 days; } /// @notice Returns the number of open positions /// @return The number of open positions function totalPositions() external view returns (uint256) { return positionIndexes.length(); } /// @notice Returns all open position NFT indexes /// @return The open position NFT indexes function openPositionsIndexes() external view returns (uint256[] memory) { return positionIndexes.values(); } struct PositionPreview { address owner; uint256 nftIndex; bytes32 nftType; uint256 nftValueUSD; VaultSettings vaultSettings; uint256 creditLimit; uint256 debtPrincipal; uint256 debtInterest; uint256 liquidatedAt; BorrowType borrowType; bool liquidatable; address liquidator; } /// @notice Returns data relative to a postition, existing or not /// @param _nftIndex The index of the NFT used as collateral for the position /// @return preview See assignment below function showPosition(uint256 _nftIndex) external view validNFTIndex(_nftIndex) returns (PositionPreview memory preview) { address posOwner = positionOwner[_nftIndex]; Position storage position = positions[_nftIndex]; uint256 debtPrincipal = position.debtPrincipal; uint256 liquidatedAt = position.liquidatedAt; uint256 debtAmount = liquidatedAt != 0 ? position.debtAmountForRepurchase //calculate updated debt : _calculateDebt( totalDebtAmount + _calculateAdditionalInterest(), position.debtPortion, totalDebtPortion ); //_calculateDebt is prone to rounding errors that may cause //the calculated debt amount to be 1 or 2 units less than //the debt principal if no time has elapsed in between the first borrow //and the _calculateDebt call. if (debtPrincipal > debtAmount) debtAmount = debtPrincipal; unchecked { preview = PositionPreview({ owner: posOwner, //the owner of the position, `address(0)` if the position doesn't exists nftIndex: _nftIndex, //the NFT used as collateral for the position nftType: nftTypes[_nftIndex], //the type of the NFT nftValueUSD: _getNFTValueUSD(_nftIndex), //the value in USD of the NFT vaultSettings: settings, //the current vault's settings creditLimit: _getCreditLimit(posOwner, _nftIndex), //the NFT's credit limit debtPrincipal: debtPrincipal, //the debt principal for the position, `0` if the position doesn't exists debtInterest: debtAmount - debtPrincipal, //the interest of the position borrowType: position.borrowType, //the insurance type of the position, `NOT_CONFIRMED` if it doesn't exist liquidatable: liquidatedAt == 0 && debtAmount >= _getLiquidationLimit(posOwner, _nftIndex), //if the position can be liquidated liquidatedAt: liquidatedAt, //if the position has been liquidated and it had insurance, the timestamp at which the liquidation happened liquidator: position.liquidator //if the position has been liquidated and it had insurance, the address of the liquidator }); } } /// @notice Allows users to open positions and borrow using an NFT /// @dev emits a {Borrowed} event /// @param _nftIndex The index of the NFT to be used as collateral /// @param _amount The amount of PUSD to be borrowed. Note that the user will receive less than the amount requested, /// the borrow fee and insurance automatically get removed from the amount borrowed /// @param _useInsurance Whereter to open an insured position. In case the position has already been opened previously, /// this parameter needs to match the previous insurance mode. To change insurance mode, a user needs to close and reopen the position function borrow( uint256 _nftIndex, uint256 _amount, bool _useInsurance ) external validNFTIndex(_nftIndex) nonReentrant { accrue(); require( msg.sender == positionOwner[_nftIndex] || address(0) == positionOwner[_nftIndex], "unauthorized" ); require(_amount != 0, "invalid_amount"); require( totalDebtAmount + _amount <= settings.borrowAmountCap, "debt_cap" ); Position storage position = positions[_nftIndex]; require(position.liquidatedAt == 0, "liquidated"); require( position.borrowType == BorrowType.NOT_CONFIRMED || (position.borrowType == BorrowType.USE_INSURANCE && _useInsurance) || (position.borrowType == BorrowType.NON_INSURANCE && !_useInsurance), "invalid_insurance_mode" ); uint256 creditLimit = _getCreditLimit(msg.sender, _nftIndex); uint256 debtAmount = _getDebtAmount(_nftIndex); require(debtAmount + _amount <= creditLimit, "insufficient_credit"); //calculate the borrow fee uint256 organizationFee = (_amount * settings.organizationFeeRate.numerator) / settings.organizationFeeRate.denominator; uint256 feeAmount = organizationFee; //if the position is insured, calculate the insurance fee if (position.borrowType == BorrowType.USE_INSURANCE || _useInsurance) { feeAmount += (_amount * settings.insurancePurchaseRate.numerator) / settings.insurancePurchaseRate.denominator; } totalFeeCollected += feeAmount; if (position.borrowType == BorrowType.NOT_CONFIRMED) { position.borrowType = _useInsurance ? BorrowType.USE_INSURANCE : BorrowType.NON_INSURANCE; } uint256 debtPortion = totalDebtPortion; // update debt portion if (debtPortion == 0) { totalDebtPortion = _amount; position.debtPortion = _amount; } else { uint256 plusPortion = (debtPortion * _amount) / totalDebtAmount; totalDebtPortion = debtPortion + plusPortion; position.debtPortion += plusPortion; } position.debtPrincipal += _amount; totalDebtAmount += _amount; if (positionOwner[_nftIndex] == address(0)) { _openPosition(msg.sender, _nftIndex); } //subtract the fee from the amount borrowed stablecoin.mint(msg.sender, _amount - feeAmount); emit Borrowed(msg.sender, _nftIndex, _amount); } /// @notice Allows users to repay a portion/all of their debt. Note that since interest increases every second, /// a user wanting to repay all of their debt should repay for an amount greater than their current debt to account for the /// additional interest while the repay transaction is pending, the contract will only take what's necessary to repay all the debt /// @dev Emits a {Repaid} event /// @param _nftIndex The NFT used as collateral for the position /// @param _amount The amount of debt to repay. If greater than the position's outstanding debt, only the amount necessary to repay all the debt will be taken function repay(uint256 _nftIndex, uint256 _amount) external validNFTIndex(_nftIndex) nonReentrant { accrue(); require(msg.sender == positionOwner[_nftIndex], "unauthorized"); require(_amount != 0, "invalid_amount"); Position storage position = positions[_nftIndex]; require(position.liquidatedAt == 0, "liquidated"); uint256 debtAmount = _getDebtAmount(_nftIndex); require(debtAmount != 0, "position_not_borrowed"); uint256 debtPrincipal = position.debtPrincipal; uint256 debtInterest = debtAmount - debtPrincipal; _amount = _amount > debtAmount ? debtAmount : _amount; // burn all payment, the interest is sent to the DAO using the {collect} function stablecoin.burnFrom(msg.sender, _amount); uint256 paidPrincipal; unchecked { paidPrincipal = _amount > debtInterest ? _amount - debtInterest : 0; } uint256 totalPortion = totalDebtPortion; uint256 totalDebt = totalDebtAmount; uint256 minusPortion = paidPrincipal == debtPrincipal ? position.debtPortion : (totalPortion * _amount) / totalDebt; totalDebtPortion = totalPortion - minusPortion; position.debtPortion -= minusPortion; position.debtPrincipal -= paidPrincipal; totalDebtAmount = totalDebt - _amount; emit Repaid(msg.sender, _nftIndex, _amount); } /// @notice Allows a user to close a position and get their collateral back, if the position's outstanding debt is 0 /// @dev Emits a {PositionClosed} event /// @param _nftIndex The index of the NFT used as collateral function closePosition(uint256 _nftIndex) external validNFTIndex(_nftIndex) nonReentrant { accrue(); require(msg.sender == positionOwner[_nftIndex], "unauthorized"); require(positions[_nftIndex].liquidatedAt == 0, "liquidated"); require(_getDebtAmount(_nftIndex) == 0, "position_not_repaid"); positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); // transfer nft back to owner if nft was deposited if (nftContract.ownerOf(_nftIndex) == address(this)) { nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); } emit PositionClosed(msg.sender, _nftIndex); } /// @notice Allows members of the `LIQUIDATOR_ROLE` to liquidate a position. Positions can only be liquidated /// once their debt amount exceeds the minimum liquidation debt to collateral value rate. /// In order to liquidate a position, the liquidator needs to repay the user's outstanding debt. /// If the position is not insured, it's closed immediately and the collateral is sent to the liquidator. /// If the position is insured, the position remains open (interest doesn't increase) and the owner of the position has a certain amount of time /// (`insuranceRepurchaseTimeLimit`) to fully repay the liquidator and pay an additional liquidation fee (`insuranceLiquidationPenaltyRate`), if this /// is done in time the user gets back their collateral and their position is automatically closed. If the user doesn't repurchase their collateral /// before the time limit passes, the liquidator can claim the liquidated NFT and the position is closed /// @dev Emits a {Liquidated} event /// @param _nftIndex The NFT to liquidate function liquidate(uint256 _nftIndex) external onlyRole(LIQUIDATOR_ROLE) validNFTIndex(_nftIndex) nonReentrant { accrue(); address posOwner = positionOwner[_nftIndex]; require(posOwner != address(0), "position_not_exist"); Position storage position = positions[_nftIndex]; require(position.liquidatedAt == 0, "liquidated"); uint256 debtAmount = _getDebtAmount(_nftIndex); require( debtAmount >= _getLiquidationLimit(posOwner, _nftIndex), "position_not_liquidatable" ); // burn all payment stablecoin.burnFrom(msg.sender, debtAmount); // update debt portion totalDebtPortion -= position.debtPortion; totalDebtAmount -= debtAmount; position.debtPortion = 0; bool insured = position.borrowType == BorrowType.USE_INSURANCE; if (insured) { position.debtAmountForRepurchase = debtAmount; position.liquidatedAt = block.timestamp; position.liquidator = msg.sender; } else { // transfer nft to liquidator positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); } emit Liquidated(msg.sender, posOwner, _nftIndex, insured); } /// @notice Allows liquidated users who purchased insurance to repurchase their collateral within the time limit /// defined with the `insuranceRepurchaseTimeLimit`. The user needs to pay the liquidator the total amount of debt /// the position had at the time of liquidation, plus an insurance liquidation fee defined with `insuranceLiquidationPenaltyRate` /// @dev Emits a {Repurchased} event /// @param _nftIndex The NFT to repurchase function repurchase(uint256 _nftIndex) external validNFTIndex(_nftIndex) nonReentrant { Position memory position = positions[_nftIndex]; require(msg.sender == positionOwner[_nftIndex], "unauthorized"); require(position.liquidatedAt != 0, "not_liquidated"); require( position.borrowType == BorrowType.USE_INSURANCE, "non_insurance" ); require( position.liquidatedAt + settings.insuranceRepurchaseTimeLimit >= block.timestamp, "insurance_expired" ); uint256 debtAmount = position.debtAmountForRepurchase; uint256 penalty = (debtAmount * settings.insuranceLiquidationPenaltyRate.numerator) / settings.insuranceLiquidationPenaltyRate.denominator; // transfer nft to user positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); // transfer payment to liquidator stablecoin.safeTransferFrom( msg.sender, position.liquidator, debtAmount + penalty ); nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); emit Repurchased(msg.sender, _nftIndex); } /// @notice Allows the liquidator who liquidated the insured position with NFT at index `_nftIndex` to claim the position's collateral /// after the time period defined with `insuranceRepurchaseTimeLimit` has expired and the position owner has not repurchased the collateral. /// @dev Emits an {InsuranceExpired} event /// @param _nftIndex The NFT to claim function claimExpiredInsuranceNFT(uint256 _nftIndex) external validNFTIndex(_nftIndex) nonReentrant { Position memory position = positions[_nftIndex]; address owner = positionOwner[_nftIndex]; require(address(0) != owner, "no_position"); require(position.liquidatedAt != 0, "not_liquidated"); require( position.liquidatedAt + settings.insuranceRepurchaseTimeLimit < block.timestamp, "insurance_not_expired" ); require(position.liquidator == msg.sender, "unauthorized"); positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); emit InsuranceExpired(owner, _nftIndex); } /// @notice Allows the DAO to collect interest and fees before they are repaid function collect() external nonReentrant onlyRole(DAO_ROLE) { accrue(); stablecoin.mint(msg.sender, totalFeeCollected); totalFeeCollected = 0; } uint256[50] private __gap; }
contract NFTVault is AccessControlUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeERC20Upgradeable for IStableCoin; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; event PositionOpened(address indexed owner, uint256 indexed index); event Borrowed( address indexed owner, uint256 indexed index, uint256 amount ); event Repaid(address indexed owner, uint256 indexed index, uint256 amount); event PositionClosed(address indexed owner, uint256 indexed index); event Liquidated( address indexed liquidator, address indexed owner, uint256 indexed index, bool insured ); event Repurchased(address indexed owner, uint256 indexed index); event InsuranceExpired(address indexed owner, uint256 indexed index); enum BorrowType { NOT_CONFIRMED, NON_INSURANCE, USE_INSURANCE } struct Position { BorrowType borrowType; uint256 debtPrincipal; uint256 debtPortion; uint256 debtAmountForRepurchase; uint256 liquidatedAt; address liquidator; } struct Rate { uint128 numerator; uint128 denominator; } struct VaultSettings { Rate debtInterestApr; Rate creditLimitRate; Rate liquidationLimitRate; Rate cigStakedCreditLimitRate; Rate cigStakedLiquidationLimitRate; Rate valueIncreaseLockRate; Rate organizationFeeRate; Rate insurancePurchaseRate; Rate insuranceLiquidationPenaltyRate; uint256 insuranceRepurchaseTimeLimit; uint256 borrowAmountCap; } bytes32 public constant DAO_ROLE = keccak256("DAO_ROLE"); bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE"); bytes32 public constant CUSTOM_NFT_HASH = keccak256("CUSTOM"); IStableCoin public stablecoin; /// @notice Chainlink ETH/USD price feed IAggregatorV3Interface public ethAggregator; /// @notice Chainlink JPEG/USD price feed IAggregatorV3Interface public jpegAggregator; /// @notice Chainlink NFT floor oracle IAggregatorV3Interface public floorOracle; /// @notice Chainlink NFT fallback floor oracle IAggregatorV3Interface public fallbackOracle; /// @notice JPEGLocker, used by this contract to lock JPEG and increase the value of an NFT IJPEGLock public jpegLocker; /// @notice JPEGCardsCigStaking, cig stakers get an higher credit limit rate and liquidation limit rate. /// Immediately reverts to normal rates if the cig is unstaked. IJPEGCardsCigStaking public cigStaking; IERC721Upgradeable public nftContract; /// @notice If true, the floor price won't be fetched using the Chainlink oracle but /// a value set by the DAO will be used instead bool public daoFloorOverride; // @notice If true, the floor price will be fetched using the fallback oracle bool public useFallbackOracle; /// @notice Total outstanding debt uint256 public totalDebtAmount; /// @dev Last time debt was accrued. See {accrue} for more info uint256 public totalDebtAccruedAt; uint256 public totalFeeCollected; uint256 internal totalDebtPortion; VaultSettings public settings; /// @dev Keeps track of all the NFTs used as collateral for positions EnumerableSetUpgradeable.UintSet private positionIndexes; mapping(uint256 => Position) private positions; mapping(uint256 => address) public positionOwner; mapping(bytes32 => uint256) public nftTypeValueETH; mapping(uint256 => uint256) public nftValueETH; //bytes32(0) is floor mapping(uint256 => bytes32) public nftTypes; mapping(uint256 => uint256) public pendingNFTValueETH; /// @dev Checks if the provided NFT index is valid /// @param nftIndex The index to check modifier validNFTIndex(uint256 nftIndex) { //The standard OZ ERC721 implementation of ownerOf reverts on a non existing nft isntead of returning address(0) require(nftContract.ownerOf(nftIndex) != address(0), "invalid_nft"); _; } struct NFTCategoryInitializer { bytes32 hash; uint256 valueETH; uint256[] nfts; } /// @param _stablecoin PUSD address /// @param _nftContract The NFT contrat address. It could also be the address of an helper contract /// if the target NFT isn't an ERC721 (CryptoPunks as an example) /// @param _ethAggregator Chainlink ETH/USD price feed address /// @param _floorOracle Chainlink floor oracle address /// @param _typeInitializers Used to initialize NFT categories with their value and NFT indexes. /// Floor NFT shouldn't be initialized this way /// @param _settings Initial settings used by the contract function initialize( IStableCoin _stablecoin, IERC721Upgradeable _nftContract, IAggregatorV3Interface _ethAggregator, IAggregatorV3Interface _floorOracle, NFTCategoryInitializer[] calldata _typeInitializers, IJPEGCardsCigStaking _cigStaking, VaultSettings calldata _settings ) external initializer { __AccessControl_init(); __ReentrancyGuard_init(); _setupRole(DAO_ROLE, msg.sender); _setRoleAdmin(LIQUIDATOR_ROLE, DAO_ROLE); _setRoleAdmin(DAO_ROLE, DAO_ROLE); _validateRate(_settings.debtInterestApr); _validateRate(_settings.creditLimitRate); _validateRate(_settings.liquidationLimitRate); _validateRate(_settings.cigStakedCreditLimitRate); _validateRate(_settings.cigStakedLiquidationLimitRate); _validateRate(_settings.valueIncreaseLockRate); _validateRate(_settings.organizationFeeRate); _validateRate(_settings.insurancePurchaseRate); _validateRate(_settings.insuranceLiquidationPenaltyRate); require( _greaterThan( _settings.liquidationLimitRate, _settings.creditLimitRate ), "invalid_liquidation_limit" ); require( _greaterThan( _settings.cigStakedLiquidationLimitRate, _settings.cigStakedCreditLimitRate ), "invalid_cig_liquidation_limit" ); require( _greaterThan( _settings.cigStakedCreditLimitRate, _settings.creditLimitRate ), "invalid_cig_credit_limit" ); require( _greaterThan( _settings.cigStakedLiquidationLimitRate, _settings.liquidationLimitRate ), "invalid_cig_liquidation_limit" ); stablecoin = _stablecoin; ethAggregator = _ethAggregator; floorOracle = _floorOracle; cigStaking = _cigStaking; nftContract = _nftContract; settings = _settings; //initializing the categories for (uint256 i; i < _typeInitializers.length; ++i) { NFTCategoryInitializer memory initializer = _typeInitializers[i]; nftTypeValueETH[initializer.hash] = initializer.valueETH; for (uint256 j; j < initializer.nfts.length; j++) { nftTypes[initializer.nfts[j]] = initializer.hash; } } } /// @dev The {accrue} function updates the contract's state by calculating /// the additional interest accrued since the last state update function accrue() public { uint256 additionalInterest = _calculateAdditionalInterest(); totalDebtAccruedAt = block.timestamp; totalDebtAmount += additionalInterest; totalFeeCollected += additionalInterest; } /// @notice Allows the DAO to change the total debt cap /// @param _borrowAmountCap New total debt cap function setBorrowAmountCap(uint256 _borrowAmountCap) external onlyRole(DAO_ROLE) { settings.borrowAmountCap = _borrowAmountCap; } /// @notice Allows the DAO to change the interest APR on borrows /// @param _debtInterestApr The new interest rate function setDebtInterestApr(Rate calldata _debtInterestApr) external onlyRole(DAO_ROLE) { _validateRate(_debtInterestApr); accrue(); settings.debtInterestApr = _debtInterestApr; } /// @notice Allows the DAO to change the amount of JPEG needed to increase the value of an NFT relative to the desired value /// @param _valueIncreaseLockRate The new rate function setValueIncreaseLockRate(Rate calldata _valueIncreaseLockRate) external onlyRole(DAO_ROLE) { _validateRate(_valueIncreaseLockRate); settings.valueIncreaseLockRate = _valueIncreaseLockRate; } /// @notice Allows the DAO to change the max debt to collateral rate for a position /// @param _creditLimitRate The new rate function setCreditLimitRate(Rate calldata _creditLimitRate) external onlyRole(DAO_ROLE) { _validateRate(_creditLimitRate); require( _greaterThan(settings.liquidationLimitRate, _creditLimitRate), "invalid_credit_limit" ); require( _greaterThan(settings.cigStakedCreditLimitRate, _creditLimitRate), "invalid_credit_limit" ); settings.creditLimitRate = _creditLimitRate; } /// @notice Allows the DAO to change the minimum debt to collateral rate for a position to be market as liquidatable /// @param _liquidationLimitRate The new rate function setLiquidationLimitRate(Rate calldata _liquidationLimitRate) external onlyRole(DAO_ROLE) { _validateRate(_liquidationLimitRate); require( _greaterThan(_liquidationLimitRate, settings.creditLimitRate), "invalid_liquidation_limit" ); require( _greaterThan( settings.cigStakedLiquidationLimitRate, _liquidationLimitRate ), "invalid_liquidation_limit" ); settings.liquidationLimitRate = _liquidationLimitRate; } /// @notice Allows the DAO to change the minimum debt to collateral rate for a position staking a cig to be market as liquidatable /// @param _cigLiquidationLimitRate The new rate function setStakedCigLiquidationLimitRate( Rate calldata _cigLiquidationLimitRate ) external onlyRole(DAO_ROLE) { _validateRate(_cigLiquidationLimitRate); require( _greaterThan( _cigLiquidationLimitRate, settings.cigStakedCreditLimitRate ), "invalid_cig_liquidation_limit" ); require( _greaterThan( _cigLiquidationLimitRate, settings.liquidationLimitRate ), "invalid_cig_liquidation_limit" ); settings.cigStakedLiquidationLimitRate = _cigLiquidationLimitRate; } /// @notice Allows the DAO to change the max debt to collateral rate for a position staking a cig /// @param _cigCreditLimitRate The new rate function setStakedCigCreditLimitRate(Rate calldata _cigCreditLimitRate) external onlyRole(DAO_ROLE) { _validateRate(_cigCreditLimitRate); require( _greaterThan( settings.cigStakedLiquidationLimitRate, _cigCreditLimitRate ), "invalid_cig_credit_limit" ); require( _greaterThan(_cigCreditLimitRate, settings.creditLimitRate), "invalid_cig_credit_limit" ); settings.cigStakedCreditLimitRate = _cigCreditLimitRate; } /// @notice Allows the DAO to set the JPEG oracle /// @param _aggregator new oracle address function setJPEGAggregator(IAggregatorV3Interface _aggregator) external onlyRole(DAO_ROLE) { require(address(_aggregator) != address(0), "invalid_address"); require(address(jpegAggregator) == address(0), "already_set"); jpegAggregator = _aggregator; } /// @notice Allows the DAO to change fallback oracle /// @param _fallback new fallback address function setFallbackOracle(IAggregatorV3Interface _fallback) external onlyRole(DAO_ROLE) { require(address(_fallback) != address(0), "invalid_address"); fallbackOracle = _fallback; } /// @notice Allows the DAO to toggle the fallback oracle /// @param _useFallback Whether to use the fallback oracle function toggleFallbackOracle(bool _useFallback) external onlyRole(DAO_ROLE) { require(address(fallbackOracle) != address(0), "fallback_not_set"); useFallbackOracle = _useFallback; } /// @notice Allows the DAO to set jpeg locker /// @param _jpegLocker The jpeg locker address function setJPEGLocker(IJPEGLock _jpegLocker) external onlyRole(DAO_ROLE) { require(address(_jpegLocker) != address(0), "invalid_address"); jpegLocker = _jpegLocker; } /// @notice Allows the DAO to change the amount of time JPEG tokens need to be locked to change the value of an NFT /// @param _newLockTime The amount new lock time amount function setJPEGLockTime(uint256 _newLockTime) external onlyRole(DAO_ROLE) { require(address(jpegLocker) != address(0), "no_jpeg_locker"); jpegLocker.setLockTime(_newLockTime); } /// @notice Allows the DAO to change the amount of time insurance remains valid after liquidation /// @param _newLimit New time limit function setInsuranceRepurchaseTimeLimit(uint256 _newLimit) external onlyRole(DAO_ROLE) { require(_newLimit != 0, "invalid_limit"); settings.insuranceRepurchaseTimeLimit = _newLimit; } /// @notice Allows the DAO to bypass the floor oracle and override the NFT floor value /// @param _newFloor The new floor function overrideFloor(uint256 _newFloor) external onlyRole(DAO_ROLE) { require(_newFloor != 0, "invalid_floor"); nftTypeValueETH[bytes32(0)] = _newFloor; daoFloorOverride = true; } /// @notice Allows the DAO to stop overriding floor function disableFloorOverride() external onlyRole(DAO_ROLE) { daoFloorOverride = false; } /// @notice Allows the DAO to change the static borrow fee /// @param _organizationFeeRate The new fee rate function setOrganizationFeeRate(Rate calldata _organizationFeeRate) external onlyRole(DAO_ROLE) { _validateRate(_organizationFeeRate); settings.organizationFeeRate = _organizationFeeRate; } /// @notice Allows the DAO to change the cost of insurance /// @param _insurancePurchaseRate The new insurance fee rate function setInsurancePurchaseRate(Rate calldata _insurancePurchaseRate) external onlyRole(DAO_ROLE) { _validateRate(_insurancePurchaseRate); settings.insurancePurchaseRate = _insurancePurchaseRate; } /// @notice Allows the DAO to change the repurchase penalty rate in case of liquidation of an insured NFT /// @param _insuranceLiquidationPenaltyRate The new rate function setInsuranceLiquidationPenaltyRate( Rate calldata _insuranceLiquidationPenaltyRate ) external onlyRole(DAO_ROLE) { _validateRate(_insuranceLiquidationPenaltyRate); settings .insuranceLiquidationPenaltyRate = _insuranceLiquidationPenaltyRate; } /// @notice Allows the DAO to add an NFT to a specific price category /// @param _nftIndex The index to add to the category /// @param _type The category hash function setNFTType(uint256 _nftIndex, bytes32 _type) external validNFTIndex(_nftIndex) onlyRole(DAO_ROLE) { require( _type == bytes32(0) || nftTypeValueETH[_type] != 0, "invalid_nftType" ); nftTypes[_nftIndex] = _type; } /// @notice Allows the DAO to change the value of an NFT category /// @param _type The category hash /// @param _amountETH The new value, in ETH function setNFTTypeValueETH(bytes32 _type, uint256 _amountETH) external onlyRole(DAO_ROLE) { nftTypeValueETH[_type] = _amountETH; } /// @notice Allows the DAO to set the value in ETH of the NFT at index `_nftIndex`. /// A JPEG deposit by a user is required afterwards. See {finalizePendingNFTValueETH} for more details /// @param _nftIndex The index of the NFT to change the value of /// @param _amountETH The new desired ETH value function setPendingNFTValueETH(uint256 _nftIndex, uint256 _amountETH) external validNFTIndex(_nftIndex) onlyRole(DAO_ROLE) { require(address(jpegLocker) != address(0), "no_jpeg_locker"); pendingNFTValueETH[_nftIndex] = _amountETH; } /// @notice Allows a user to lock up JPEG to make the change in value of an NFT effective. /// Can only be called after {setPendingNFTValueETH}, which requires a governance vote. /// @dev The amount of JPEG that needs to be locked is calculated by applying `valueIncreaseLockRate` /// to the new credit limit of the NFT /// @param _nftIndex The index of the NFT function finalizePendingNFTValueETH(uint256 _nftIndex) external validNFTIndex(_nftIndex) { require(address(jpegLocker) != address(0), "no_jpeg_locker"); uint256 pendingValue = pendingNFTValueETH[_nftIndex]; require(pendingValue != 0, "no_pending_value"); uint256 toLockJpeg = (((pendingValue * 1 ether * settings.creditLimitRate.numerator) / settings.creditLimitRate.denominator) * settings.valueIncreaseLockRate.numerator) / settings.valueIncreaseLockRate.denominator / _jpegPriceETH(); //lock JPEG using JPEGLock jpegLocker.lockFor(msg.sender, _nftIndex, toLockJpeg); nftTypes[_nftIndex] = CUSTOM_NFT_HASH; nftValueETH[_nftIndex] = pendingValue; //clear pending value pendingNFTValueETH[_nftIndex] = 0; } /// @dev Checks if `r1` is greater than `r2`. function _greaterThan(Rate memory _r1, Rate memory _r2) internal pure returns (bool) { return _r1.numerator * _r2.denominator > _r2.numerator * _r1.denominator; } /// @dev Validates a rate. The denominator must be greater than zero and greater than or equal to the numerator. /// @param rate The rate to validate function _validateRate(Rate calldata rate) internal pure { require( rate.denominator != 0 && rate.denominator >= rate.numerator, "invalid_rate" ); } /// @dev Returns the value in ETH of the NFT at index `_nftIndex` /// @param _nftIndex The NFT to return the value of /// @return The value of the NFT, 18 decimals function _getNFTValueETH(uint256 _nftIndex) internal view returns (uint256) { bytes32 nftType = nftTypes[_nftIndex]; if (nftType == bytes32(0) && !daoFloorOverride) { return _normalizeAggregatorAnswer( useFallbackOracle ? fallbackOracle : floorOracle ); } else if (nftType == CUSTOM_NFT_HASH) return nftValueETH[_nftIndex]; return nftTypeValueETH[nftType]; } /// @dev Returns the value in USD of the NFT at index `_nftIndex` /// @param _nftIndex The NFT to return the value of /// @return The value of the NFT in USD, 18 decimals function _getNFTValueUSD(uint256 _nftIndex) internal view returns (uint256) { uint256 nft_value = _getNFTValueETH(_nftIndex); return (nft_value * _ethPriceUSD()) / 1 ether; } /// @dev Returns the current ETH price in USD /// @return The current ETH price, 18 decimals function _ethPriceUSD() internal view returns (uint256) { return _normalizeAggregatorAnswer(ethAggregator); } /// @dev Returns the current JPEG price in ETH /// @return The current JPEG price, 18 decimals function _jpegPriceETH() internal view returns (uint256) { IAggregatorV3Interface aggregator = jpegAggregator; require(address(aggregator) != address(0), "jpeg_oracle_not_set"); return _normalizeAggregatorAnswer(aggregator); } /// @dev Fetches and converts to 18 decimals precision the latest answer of a Chainlink aggregator /// @param aggregator The aggregator to fetch the answer from /// @return The latest aggregator answer, normalized function _normalizeAggregatorAnswer(IAggregatorV3Interface aggregator) internal view returns (uint256) { (, int256 answer, , uint256 timestamp, ) = aggregator.latestRoundData(); require(answer > 0, "invalid_oracle_answer"); require(timestamp != 0, "round_incomplete"); uint8 decimals = aggregator.decimals(); unchecked { //converts the answer to have 18 decimals return decimals > 18 ? uint256(answer) / 10**(decimals - 18) : uint256(answer) * 10**(18 - decimals); } } struct NFTInfo { uint256 index; bytes32 nftType; address owner; uint256 nftValueETH; uint256 nftValueUSD; } /// @notice Returns data relative to the NFT at index `_nftIndex` /// @param _nftIndex The NFT index /// @return nftInfo The data relative to the NFT function getNFTInfo(uint256 _nftIndex) external view returns (NFTInfo memory nftInfo) { nftInfo = NFTInfo( _nftIndex, nftTypes[_nftIndex], nftContract.ownerOf(_nftIndex), _getNFTValueETH(_nftIndex), _getNFTValueUSD(_nftIndex) ); } /// @dev Returns the credit limit of an NFT /// @param _nftIndex The NFT to return credit limit of /// @return The NFT credit limit function _getCreditLimit(address user, uint256 _nftIndex) internal view returns (uint256) { uint256 value = _getNFTValueUSD(_nftIndex); if (cigStaking.isUserStaking(user)) { return (value * settings.cigStakedCreditLimitRate.numerator) / settings.cigStakedCreditLimitRate.denominator; } return (value * settings.creditLimitRate.numerator) / settings.creditLimitRate.denominator; } /// @dev Returns the minimum amount of debt necessary to liquidate an NFT /// @param _nftIndex The index of the NFT /// @return The minimum amount of debt to liquidate the NFT function _getLiquidationLimit(address user, uint256 _nftIndex) internal view returns (uint256) { uint256 value = _getNFTValueUSD(_nftIndex); if (cigStaking.isUserStaking(user)) { return (value * settings.cigStakedLiquidationLimitRate.numerator) / settings.cigStakedLiquidationLimitRate.denominator; } return (value * settings.liquidationLimitRate.numerator) / settings.liquidationLimitRate.denominator; } /// @dev Calculates current outstanding debt of an NFT /// @param _nftIndex The NFT to calculate the outstanding debt of /// @return The outstanding debt value function _getDebtAmount(uint256 _nftIndex) internal view returns (uint256) { uint256 calculatedDebt = _calculateDebt( totalDebtAmount, positions[_nftIndex].debtPortion, totalDebtPortion ); uint256 principal = positions[_nftIndex].debtPrincipal; //_calculateDebt is prone to rounding errors that may cause //the calculated debt amount to be 1 or 2 units less than //the debt principal when the accrue() function isn't called //in between the first borrow and the _calculateDebt call. return principal > calculatedDebt ? principal : calculatedDebt; } /// @dev Calculates the total debt of a position given the global debt, the user's portion of the debt and the total user portions /// @param total The global outstanding debt /// @param userPortion The user's portion of debt /// @param totalPortion The total user portions of debt /// @return The outstanding debt of the position function _calculateDebt( uint256 total, uint256 userPortion, uint256 totalPortion ) internal pure returns (uint256) { return totalPortion == 0 ? 0 : (total * userPortion) / totalPortion; } /// @dev Opens a position /// Emits a {PositionOpened} event /// @param _owner The owner of the position to open /// @param _nftIndex The NFT used as collateral for the position function _openPosition(address _owner, uint256 _nftIndex) internal { positionOwner[_nftIndex] = _owner; positionIndexes.add(_nftIndex); nftContract.transferFrom(_owner, address(this), _nftIndex); emit PositionOpened(_owner, _nftIndex); } /// @dev Calculates the additional global interest since last time the contract's state was updated by calling {accrue} /// @return The additional interest value function _calculateAdditionalInterest() internal view returns (uint256) { // Number of seconds since {accrue} was called uint256 elapsedTime = block.timestamp - totalDebtAccruedAt; if (elapsedTime == 0) { return 0; } uint256 totalDebt = totalDebtAmount; if (totalDebt == 0) { return 0; } // Accrue interest return (elapsedTime * totalDebt * settings.debtInterestApr.numerator) / settings.debtInterestApr.denominator / 365 days; } /// @notice Returns the number of open positions /// @return The number of open positions function totalPositions() external view returns (uint256) { return positionIndexes.length(); } /// @notice Returns all open position NFT indexes /// @return The open position NFT indexes function openPositionsIndexes() external view returns (uint256[] memory) { return positionIndexes.values(); } struct PositionPreview { address owner; uint256 nftIndex; bytes32 nftType; uint256 nftValueUSD; VaultSettings vaultSettings; uint256 creditLimit; uint256 debtPrincipal; uint256 debtInterest; uint256 liquidatedAt; BorrowType borrowType; bool liquidatable; address liquidator; } /// @notice Returns data relative to a postition, existing or not /// @param _nftIndex The index of the NFT used as collateral for the position /// @return preview See assignment below function showPosition(uint256 _nftIndex) external view validNFTIndex(_nftIndex) returns (PositionPreview memory preview) { address posOwner = positionOwner[_nftIndex]; Position storage position = positions[_nftIndex]; uint256 debtPrincipal = position.debtPrincipal; uint256 liquidatedAt = position.liquidatedAt; uint256 debtAmount = liquidatedAt != 0 ? position.debtAmountForRepurchase //calculate updated debt : _calculateDebt( totalDebtAmount + _calculateAdditionalInterest(), position.debtPortion, totalDebtPortion ); //_calculateDebt is prone to rounding errors that may cause //the calculated debt amount to be 1 or 2 units less than //the debt principal if no time has elapsed in between the first borrow //and the _calculateDebt call. if (debtPrincipal > debtAmount) debtAmount = debtPrincipal; unchecked { preview = PositionPreview({ owner: posOwner, //the owner of the position, `address(0)` if the position doesn't exists nftIndex: _nftIndex, //the NFT used as collateral for the position nftType: nftTypes[_nftIndex], //the type of the NFT nftValueUSD: _getNFTValueUSD(_nftIndex), //the value in USD of the NFT vaultSettings: settings, //the current vault's settings creditLimit: _getCreditLimit(posOwner, _nftIndex), //the NFT's credit limit debtPrincipal: debtPrincipal, //the debt principal for the position, `0` if the position doesn't exists debtInterest: debtAmount - debtPrincipal, //the interest of the position borrowType: position.borrowType, //the insurance type of the position, `NOT_CONFIRMED` if it doesn't exist liquidatable: liquidatedAt == 0 && debtAmount >= _getLiquidationLimit(posOwner, _nftIndex), //if the position can be liquidated liquidatedAt: liquidatedAt, //if the position has been liquidated and it had insurance, the timestamp at which the liquidation happened liquidator: position.liquidator //if the position has been liquidated and it had insurance, the address of the liquidator }); } } /// @notice Allows users to open positions and borrow using an NFT /// @dev emits a {Borrowed} event /// @param _nftIndex The index of the NFT to be used as collateral /// @param _amount The amount of PUSD to be borrowed. Note that the user will receive less than the amount requested, /// the borrow fee and insurance automatically get removed from the amount borrowed /// @param _useInsurance Whereter to open an insured position. In case the position has already been opened previously, /// this parameter needs to match the previous insurance mode. To change insurance mode, a user needs to close and reopen the position function borrow( uint256 _nftIndex, uint256 _amount, bool _useInsurance ) external validNFTIndex(_nftIndex) nonReentrant { accrue(); require( msg.sender == positionOwner[_nftIndex] || address(0) == positionOwner[_nftIndex], "unauthorized" ); require(_amount != 0, "invalid_amount"); require( totalDebtAmount + _amount <= settings.borrowAmountCap, "debt_cap" ); Position storage position = positions[_nftIndex]; require(position.liquidatedAt == 0, "liquidated"); require( position.borrowType == BorrowType.NOT_CONFIRMED || (position.borrowType == BorrowType.USE_INSURANCE && _useInsurance) || (position.borrowType == BorrowType.NON_INSURANCE && !_useInsurance), "invalid_insurance_mode" ); uint256 creditLimit = _getCreditLimit(msg.sender, _nftIndex); uint256 debtAmount = _getDebtAmount(_nftIndex); require(debtAmount + _amount <= creditLimit, "insufficient_credit"); //calculate the borrow fee uint256 organizationFee = (_amount * settings.organizationFeeRate.numerator) / settings.organizationFeeRate.denominator; uint256 feeAmount = organizationFee; //if the position is insured, calculate the insurance fee if (position.borrowType == BorrowType.USE_INSURANCE || _useInsurance) { feeAmount += (_amount * settings.insurancePurchaseRate.numerator) / settings.insurancePurchaseRate.denominator; } totalFeeCollected += feeAmount; if (position.borrowType == BorrowType.NOT_CONFIRMED) { position.borrowType = _useInsurance ? BorrowType.USE_INSURANCE : BorrowType.NON_INSURANCE; } uint256 debtPortion = totalDebtPortion; // update debt portion if (debtPortion == 0) { totalDebtPortion = _amount; position.debtPortion = _amount; } else { uint256 plusPortion = (debtPortion * _amount) / totalDebtAmount; totalDebtPortion = debtPortion + plusPortion; position.debtPortion += plusPortion; } position.debtPrincipal += _amount; totalDebtAmount += _amount; if (positionOwner[_nftIndex] == address(0)) { _openPosition(msg.sender, _nftIndex); } //subtract the fee from the amount borrowed stablecoin.mint(msg.sender, _amount - feeAmount); emit Borrowed(msg.sender, _nftIndex, _amount); } /// @notice Allows users to repay a portion/all of their debt. Note that since interest increases every second, /// a user wanting to repay all of their debt should repay for an amount greater than their current debt to account for the /// additional interest while the repay transaction is pending, the contract will only take what's necessary to repay all the debt /// @dev Emits a {Repaid} event /// @param _nftIndex The NFT used as collateral for the position /// @param _amount The amount of debt to repay. If greater than the position's outstanding debt, only the amount necessary to repay all the debt will be taken function repay(uint256 _nftIndex, uint256 _amount) external validNFTIndex(_nftIndex) nonReentrant { accrue(); require(msg.sender == positionOwner[_nftIndex], "unauthorized"); require(_amount != 0, "invalid_amount"); Position storage position = positions[_nftIndex]; require(position.liquidatedAt == 0, "liquidated"); uint256 debtAmount = _getDebtAmount(_nftIndex); require(debtAmount != 0, "position_not_borrowed"); uint256 debtPrincipal = position.debtPrincipal; uint256 debtInterest = debtAmount - debtPrincipal; _amount = _amount > debtAmount ? debtAmount : _amount; // burn all payment, the interest is sent to the DAO using the {collect} function stablecoin.burnFrom(msg.sender, _amount); uint256 paidPrincipal; unchecked { paidPrincipal = _amount > debtInterest ? _amount - debtInterest : 0; } uint256 totalPortion = totalDebtPortion; uint256 totalDebt = totalDebtAmount; uint256 minusPortion = paidPrincipal == debtPrincipal ? position.debtPortion : (totalPortion * _amount) / totalDebt; totalDebtPortion = totalPortion - minusPortion; position.debtPortion -= minusPortion; position.debtPrincipal -= paidPrincipal; totalDebtAmount = totalDebt - _amount; emit Repaid(msg.sender, _nftIndex, _amount); } /// @notice Allows a user to close a position and get their collateral back, if the position's outstanding debt is 0 /// @dev Emits a {PositionClosed} event /// @param _nftIndex The index of the NFT used as collateral function closePosition(uint256 _nftIndex) external validNFTIndex(_nftIndex) nonReentrant { accrue(); require(msg.sender == positionOwner[_nftIndex], "unauthorized"); require(positions[_nftIndex].liquidatedAt == 0, "liquidated"); require(_getDebtAmount(_nftIndex) == 0, "position_not_repaid"); positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); // transfer nft back to owner if nft was deposited if (nftContract.ownerOf(_nftIndex) == address(this)) { nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); } emit PositionClosed(msg.sender, _nftIndex); } /// @notice Allows members of the `LIQUIDATOR_ROLE` to liquidate a position. Positions can only be liquidated /// once their debt amount exceeds the minimum liquidation debt to collateral value rate. /// In order to liquidate a position, the liquidator needs to repay the user's outstanding debt. /// If the position is not insured, it's closed immediately and the collateral is sent to the liquidator. /// If the position is insured, the position remains open (interest doesn't increase) and the owner of the position has a certain amount of time /// (`insuranceRepurchaseTimeLimit`) to fully repay the liquidator and pay an additional liquidation fee (`insuranceLiquidationPenaltyRate`), if this /// is done in time the user gets back their collateral and their position is automatically closed. If the user doesn't repurchase their collateral /// before the time limit passes, the liquidator can claim the liquidated NFT and the position is closed /// @dev Emits a {Liquidated} event /// @param _nftIndex The NFT to liquidate function liquidate(uint256 _nftIndex) external onlyRole(LIQUIDATOR_ROLE) validNFTIndex(_nftIndex) nonReentrant { accrue(); address posOwner = positionOwner[_nftIndex]; require(posOwner != address(0), "position_not_exist"); Position storage position = positions[_nftIndex]; require(position.liquidatedAt == 0, "liquidated"); uint256 debtAmount = _getDebtAmount(_nftIndex); require( debtAmount >= _getLiquidationLimit(posOwner, _nftIndex), "position_not_liquidatable" ); // burn all payment stablecoin.burnFrom(msg.sender, debtAmount); // update debt portion totalDebtPortion -= position.debtPortion; totalDebtAmount -= debtAmount; position.debtPortion = 0; bool insured = position.borrowType == BorrowType.USE_INSURANCE; if (insured) { position.debtAmountForRepurchase = debtAmount; position.liquidatedAt = block.timestamp; position.liquidator = msg.sender; } else { // transfer nft to liquidator positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); } emit Liquidated(msg.sender, posOwner, _nftIndex, insured); } /// @notice Allows liquidated users who purchased insurance to repurchase their collateral within the time limit /// defined with the `insuranceRepurchaseTimeLimit`. The user needs to pay the liquidator the total amount of debt /// the position had at the time of liquidation, plus an insurance liquidation fee defined with `insuranceLiquidationPenaltyRate` /// @dev Emits a {Repurchased} event /// @param _nftIndex The NFT to repurchase function repurchase(uint256 _nftIndex) external validNFTIndex(_nftIndex) nonReentrant { Position memory position = positions[_nftIndex]; require(msg.sender == positionOwner[_nftIndex], "unauthorized"); require(position.liquidatedAt != 0, "not_liquidated"); require( position.borrowType == BorrowType.USE_INSURANCE, "non_insurance" ); require( position.liquidatedAt + settings.insuranceRepurchaseTimeLimit >= block.timestamp, "insurance_expired" ); uint256 debtAmount = position.debtAmountForRepurchase; uint256 penalty = (debtAmount * settings.insuranceLiquidationPenaltyRate.numerator) / settings.insuranceLiquidationPenaltyRate.denominator; // transfer nft to user positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); // transfer payment to liquidator stablecoin.safeTransferFrom( msg.sender, position.liquidator, debtAmount + penalty ); nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); emit Repurchased(msg.sender, _nftIndex); } /// @notice Allows the liquidator who liquidated the insured position with NFT at index `_nftIndex` to claim the position's collateral /// after the time period defined with `insuranceRepurchaseTimeLimit` has expired and the position owner has not repurchased the collateral. /// @dev Emits an {InsuranceExpired} event /// @param _nftIndex The NFT to claim function claimExpiredInsuranceNFT(uint256 _nftIndex) external validNFTIndex(_nftIndex) nonReentrant { Position memory position = positions[_nftIndex]; address owner = positionOwner[_nftIndex]; require(address(0) != owner, "no_position"); require(position.liquidatedAt != 0, "not_liquidated"); require( position.liquidatedAt + settings.insuranceRepurchaseTimeLimit < block.timestamp, "insurance_not_expired" ); require(position.liquidator == msg.sender, "unauthorized"); positionOwner[_nftIndex] = address(0); delete positions[_nftIndex]; positionIndexes.remove(_nftIndex); nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); emit InsuranceExpired(owner, _nftIndex); } /// @notice Allows the DAO to collect interest and fees before they are repaid function collect() external nonReentrant onlyRole(DAO_ROLE) { accrue(); stablecoin.mint(msg.sender, totalFeeCollected); totalFeeCollected = 0; } uint256[50] private __gap; }
54,152
370
// Check if the address is a valid target If sftHolder returns a valid tokenId, it must be a card not owned by thiscontract (which means it is locked). Even though Cryptofolio supportsmultiple TradeFloors, the main SFT lock handling happens only in thiscontract instance.test The address to test return True if the address is a valid target, false otherwise /
function _validTarget(address test) private view returns (bool) { uint256 tokenId; return test == address(0) || (tokenId = _addressToTokenId(test)) == uint256(-1) || (tokenId.isBaseCard() && IERC1155(address(_sftHolder)).balanceOf(address(this), tokenId) == 0); }
function _validTarget(address test) private view returns (bool) { uint256 tokenId; return test == address(0) || (tokenId = _addressToTokenId(test)) == uint256(-1) || (tokenId.isBaseCard() && IERC1155(address(_sftHolder)).balanceOf(address(this), tokenId) == 0); }
38,861
9
// Transfers `amount` tokens of token type `id` from `from` to `to`. Emits a {TransferSingle} event. Requirements: - `to` cannot be the zero address.- If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.- `from` must have a balance of tokens of type `id` of at least `amount`.- If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return theacceptance magic value. /
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
1,962
163
// Forward an EVM script/
function forward(bytes evmScript) external;
function forward(bytes evmScript) external;
8,896
28
// projectId => project's maximum number of invocations.Optionally synced with core contract value, for gas optimization.Note that this returns a local cache of the core contract'sstate, and may be out of sync with the core contract. This isintentional, as it only enables gas optimization of mints after aproject's maximum invocations has been reached. A number greater than the core contract's project max invocationswill only result in a gas cost increase, since the core contract willstill enforce a maxInvocation check during minting. A number less thanthe core contract's project max invocations is only possible when theproject's max invocations have not been synced
function projectMaxInvocations( uint256 _projectId
function projectMaxInvocations( uint256 _projectId
29,385
7
// Info of each user that stakes LP tokens.
mapping(address => UserInfo) public userInfo;
mapping(address => UserInfo) public userInfo;
5,829
36
// Compute the protocol fee that needs to be paid for a given transfer amount.
function protocolFee(uint256 amount) public view returns (uint256) { return (amount * protocolFeePPM) / 1_000_000; }
function protocolFee(uint256 amount) public view returns (uint256) { return (amount * protocolFeePPM) / 1_000_000; }
8,151
263
// its enough to test modifier onlyOwner, other checks, like isContract() , is contain upgradeTo() method implemented by UUPSUpgradeable
function _authorizeUpgrade(address) internal override onlyOwner {} function name() public view virtual override returns (string memory) { return _name; }
function _authorizeUpgrade(address) internal override onlyOwner {} function name() public view virtual override returns (string memory) { return _name; }
72,087
42
// Wallet Addresses for allocation
address public teamReserveWallet = 0x78e27c0347fa3afcc31e160b0fbc6f90186fd2b6; address public firstReserveWallet = 0xef2ab7226c1a3d274caad2dec6d79a4db5d5799e; address public CEO = 0x2Fc7607CE5f6c36979CC63aFcDA6D62Df656e4aE; address public COO = 0x08465f80A28E095DEE4BE0692AC1bA1A2E3EEeE9; address public CTO = 0xB22E5Ac6C3a9427C48295806a34f7a3C0FD21443; address public CMO = 0xf34C06cd907AD036b75cee40755b6937176f24c3; address public CPO = 0xa33da3654d5fdaBC4Dd49fB4e6c81C58D28aA74a; address public CEO_TEAM =0xc0e3294E567e965C3Ff3687015fCf88eD3CCC9EA; address public AWD = 0xc0e3294E567e965C3Ff3687015fCf88eD3CCC9EA;
address public teamReserveWallet = 0x78e27c0347fa3afcc31e160b0fbc6f90186fd2b6; address public firstReserveWallet = 0xef2ab7226c1a3d274caad2dec6d79a4db5d5799e; address public CEO = 0x2Fc7607CE5f6c36979CC63aFcDA6D62Df656e4aE; address public COO = 0x08465f80A28E095DEE4BE0692AC1bA1A2E3EEeE9; address public CTO = 0xB22E5Ac6C3a9427C48295806a34f7a3C0FD21443; address public CMO = 0xf34C06cd907AD036b75cee40755b6937176f24c3; address public CPO = 0xa33da3654d5fdaBC4Dd49fB4e6c81C58D28aA74a; address public CEO_TEAM =0xc0e3294E567e965C3Ff3687015fCf88eD3CCC9EA; address public AWD = 0xc0e3294E567e965C3Ff3687015fCf88eD3CCC9EA;
14,581
27
// Set/replace all the existing rules.
* @param thresholds List of new thresholds (check {RewardRule} type for info) * @param competitionIds List of new ids */ function reward_setAllRules( uint16[] calldata thresholds, uint256[] calldata competitionIds ) external onlyRole(METAWIN_ROLE) { require( competitionIds.length == thresholds.length, "Input arrays length differ" ); delete _rewardRules; uint256 count = competitionIds.length; for (uint256 index; index < count;) { if (_cmp().raffleNotInAcceptedState(competitionIds[index])) revert NotInAcceptedState(competitionIds[index]); _rewardRules.push( RewardRule(thresholds[index], competitionIds[index]) ); unchecked{++index;} } }
* @param thresholds List of new thresholds (check {RewardRule} type for info) * @param competitionIds List of new ids */ function reward_setAllRules( uint16[] calldata thresholds, uint256[] calldata competitionIds ) external onlyRole(METAWIN_ROLE) { require( competitionIds.length == thresholds.length, "Input arrays length differ" ); delete _rewardRules; uint256 count = competitionIds.length; for (uint256 index; index < count;) { if (_cmp().raffleNotInAcceptedState(competitionIds[index])) revert NotInAcceptedState(competitionIds[index]); _rewardRules.push( RewardRule(thresholds[index], competitionIds[index]) ); unchecked{++index;} } }
1,505
3
// Configure recovery set parameters of `msg.sender`. `emit Activated(msg.sender)` if there was no previous setup, or `emit SetupRequested(msg.sender, now()+setupDelay)` when reconfiguring. _publicHash Hash of `peerHash`. _setupDelay Delay for changes being activ. /
function setup( bytes32 _publicHash, uint256 _setupDelay ) external;
function setup( bytes32 _publicHash, uint256 _setupDelay ) external;
31,942
11
// return the get payment size of the tokens. /
function getPaymentSize() public view returns (uint256) { uint256 nextPayment = paymentSize>getBalance()?getBalance():paymentSize; return nextPayment; }
function getPaymentSize() public view returns (uint256) { uint256 nextPayment = paymentSize>getBalance()?getBalance():paymentSize; return nextPayment; }
3,213
70
// the staking end block.
function endBlock() external view returns (uint256);
function endBlock() external view returns (uint256);
619
6
// Private function to determine today's indexreturn uint256 of today's index. /
function today() private constant returns (uint256) { return now / 1 days; }
function today() private constant returns (uint256) { return now / 1 days; }
30,511
38
// searches for a liquidity pool with specific configurationconverterType converter type reserveTokens reserve tokens reserveWeights reserve weights return the liquidity pool, or zero if no such liquidity pool exists /
function getLiquidityPoolByConfig( uint16 converterType, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights
function getLiquidityPoolByConfig( uint16 converterType, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights
11,259
6
// True if a put option, False if a call option
bool public isPut; uint256 private constant STRIKE_PRICE_SCALE = 1e8; uint256 private constant STRIKE_PRICE_DIGITS = 8;
bool public isPut; uint256 private constant STRIKE_PRICE_SCALE = 1e8; uint256 private constant STRIKE_PRICE_DIGITS = 8;
27,122
49
// Gets the owner of the specified token ID _tokenId uint256 ID of the token to query the owner ofreturn owner address currently marked as the owner of the given token ID /
function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; }
function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; }
16,487
408
// all checks passed, trigger sign up
_triggerTournamentSignUp(_warriorIds, fee);
_triggerTournamentSignUp(_warriorIds, fee);
66,378
11
// Set module in the map
modules.set(_name, _module);
modules.set(_name, _module);
54,051
197
// Check for slippage
require(col_out >= col_out_min, "Collateral slippage");
require(col_out >= col_out_min, "Collateral slippage");
62,211
26
// Update signature nonce of _owner
nonces[_owner] += 1;
nonces[_owner] += 1;
13,711
9
// returns the length of a string in characters
function utfStringLength(string memory _str) internal pure returns (uint256 length)
function utfStringLength(string memory _str) internal pure returns (uint256 length)
10,494
231
// Sets the address of the proxy admin. newAdmin Address of the new proxy admin. /
function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } }
function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } }
45,934
21
// The integrity object used to validate an approval execution. The mapping key is the tx.orgin
mapping(address => CallStackState) internal _callStackStates;
mapping(address => CallStackState) internal _callStackStates;
34,934
10
// 通知任何监听该交易的客户端
Transfer(_from, _to, _value);
Transfer(_from, _to, _value);
18,305
140
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
uint256[50] private ______gap;
6,598
3
// _SWAP_TYPE_HASH = keccak256("Swap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe;
bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe;
8,329
171
// multiple a SignedDecimal.signedDecimal by Decimal.decimal
function mulD(SignedDecimal.signedDecimal memory x, Decimal.decimal memory y) internal pure convertible(y) returns (SignedDecimal.signedDecimal memory)
function mulD(SignedDecimal.signedDecimal memory x, Decimal.decimal memory y) internal pure convertible(y) returns (SignedDecimal.signedDecimal memory)
1,725
119
// Starting price [wad]
uint256 startPrice;
uint256 startPrice;
44,411
44
// Update dev address by owner
function setDevAddr(address payable _devaddr) public onlyOwner { devaddr = _devaddr; }
function setDevAddr(address payable _devaddr) public onlyOwner { devaddr = _devaddr; }
5,236
82
// Update the offset position for the next loop
nextElementHeadPtr := add(nextElementHeadPtr, OneWord)
nextElementHeadPtr := add(nextElementHeadPtr, OneWord)
14,488
157
// MarketPlace core/Contains models, variables, and internal methods for the marketplace./We omit a fallback function to prevent accidental sends to this contract.
contract MarketPlaceBase is Ownable { // Represents an sale on an NFT struct Sale { // Current owner of NFT address seller; // Price (in wei) uint128 price; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; } struct Affiliates { address affiliate_address; uint64 commission; uint64 pricecut; } //Affiliates[] affiliates; // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each sale, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; //map the Affiliate Code to the Affiliate mapping (uint256 => Affiliates) codeToAffiliate; // Map from token ID to their corresponding sale. mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(uint256 tokenId, uint256 price); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addSale(uint256 _tokenId, Sale _sale) internal { tokenIdToSale[_tokenId] = _sale; SaleCreated( uint256(_tokenId), uint256(_sale.price) ); } /// @dev Cancels a sale unconditionally. function _cancelSale(uint256 _tokenId, address _seller) internal { _removeSale(_tokenId); _transfer(_seller, _tokenId); SaleCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return a sale object that is all zeros.) require(_isOnSale(sale)); // Check that the bid is greater than or equal to the current price uint256 price = sale.price; require(_bidAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; // The bid is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the Marketplace's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 marketplaceCut = _computeCut(price); uint256 sellerProceeds = price - marketplaceCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! SaleSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes a sale from the list of open sales. /// @param _tokenId - ID of NFT on sale. function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnSale(Sale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the Marketplace constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } function _computeAffiliateCut(uint256 _price,Affiliates affiliate) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the Marketplace constructor). The result of this // function is always guaranteed to be <= _price. return _price * affiliate.commission / 10000; } /// @dev Adds an affiliate to the list. /// @param _code The referall code of the affiliate. /// @param _affiliate Affiliate to add. function _addAffiliate(uint256 _code, Affiliates _affiliate) internal { codeToAffiliate[_code] = _affiliate; } /// @dev Removes a affiliate from the list. /// @param _code - The referall code of the affiliate. function _removeAffiliate(uint256 _code) internal { delete codeToAffiliate[_code]; } //_bidReferral(_tokenId, msg.value); /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidReferral(uint256 _tokenId, uint256 _bidAmount,Affiliates _affiliate) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; //Only Owner of Contract can sell referrals require(sale.seller==owner); // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return a sale object that is all zeros.) require(_isOnSale(sale)); // Check that the bid is greater than or equal to the current price uint256 price = sale.price; //deduce the affiliate pricecut price=price * _affiliate.pricecut / 10000; require(_bidAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; address affiliate_address = _affiliate.affiliate_address; // The bid is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the Marketplace's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 affiliateCut = _computeAffiliateCut(price,_affiliate); uint256 sellerProceeds = price - affiliateCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); affiliate_address.transfer(affiliateCut); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! SaleSuccessful(_tokenId, price, msg.sender); return price; } }
contract MarketPlaceBase is Ownable { // Represents an sale on an NFT struct Sale { // Current owner of NFT address seller; // Price (in wei) uint128 price; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; } struct Affiliates { address affiliate_address; uint64 commission; uint64 pricecut; } //Affiliates[] affiliates; // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each sale, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; //map the Affiliate Code to the Affiliate mapping (uint256 => Affiliates) codeToAffiliate; // Map from token ID to their corresponding sale. mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(uint256 tokenId, uint256 price); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addSale(uint256 _tokenId, Sale _sale) internal { tokenIdToSale[_tokenId] = _sale; SaleCreated( uint256(_tokenId), uint256(_sale.price) ); } /// @dev Cancels a sale unconditionally. function _cancelSale(uint256 _tokenId, address _seller) internal { _removeSale(_tokenId); _transfer(_seller, _tokenId); SaleCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return a sale object that is all zeros.) require(_isOnSale(sale)); // Check that the bid is greater than or equal to the current price uint256 price = sale.price; require(_bidAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; // The bid is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the Marketplace's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 marketplaceCut = _computeCut(price); uint256 sellerProceeds = price - marketplaceCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! SaleSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes a sale from the list of open sales. /// @param _tokenId - ID of NFT on sale. function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnSale(Sale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the Marketplace constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } function _computeAffiliateCut(uint256 _price,Affiliates affiliate) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the Marketplace constructor). The result of this // function is always guaranteed to be <= _price. return _price * affiliate.commission / 10000; } /// @dev Adds an affiliate to the list. /// @param _code The referall code of the affiliate. /// @param _affiliate Affiliate to add. function _addAffiliate(uint256 _code, Affiliates _affiliate) internal { codeToAffiliate[_code] = _affiliate; } /// @dev Removes a affiliate from the list. /// @param _code - The referall code of the affiliate. function _removeAffiliate(uint256 _code) internal { delete codeToAffiliate[_code]; } //_bidReferral(_tokenId, msg.value); /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidReferral(uint256 _tokenId, uint256 _bidAmount,Affiliates _affiliate) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; //Only Owner of Contract can sell referrals require(sale.seller==owner); // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return a sale object that is all zeros.) require(_isOnSale(sale)); // Check that the bid is greater than or equal to the current price uint256 price = sale.price; //deduce the affiliate pricecut price=price * _affiliate.pricecut / 10000; require(_bidAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; address affiliate_address = _affiliate.affiliate_address; // The bid is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the Marketplace's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 affiliateCut = _computeAffiliateCut(price,_affiliate); uint256 sellerProceeds = price - affiliateCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); affiliate_address.transfer(affiliateCut); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! SaleSuccessful(_tokenId, price, msg.sender); return price; } }
8,141
5
// [WEARABLE ONLY] The slots that this wearable can be added to.
bool[EQUIPPED_WEARABLE_SLOTS] slotPositions;
bool[EQUIPPED_WEARABLE_SLOTS] slotPositions;
17,013
111
// Gets the token symbolreturn string representing the token symbol /
function symbol() external view returns (string) { return _symbol; }
function symbol() external view returns (string) { return _symbol; }
39,612
121
// Withdraw staked 1 NFT and staked $KING token amount, w/o any rewards !!! All possible rewards entitled be lost. Use in emergency only !!!
function emergencyWithdraw(uint256 stakeId) public nonReentrant { _withdraw(stakeId, true); emit EmergencyWithdraw(msg.sender, stakeId); }
function emergencyWithdraw(uint256 stakeId) public nonReentrant { _withdraw(stakeId, true); emit EmergencyWithdraw(msg.sender, stakeId); }
38,149
48
// The function used to set the base token URI. Only collection creator may call. _baseTokenURI The base token URI. /
function setBaseTokenURI(string memory _baseTokenURI) external override initialized onlyCreator { baseTokenURI = _baseTokenURI; emit BaseTokenURISet(_baseTokenURI); }
function setBaseTokenURI(string memory _baseTokenURI) external override initialized onlyCreator { baseTokenURI = _baseTokenURI; emit BaseTokenURISet(_baseTokenURI); }
23,916
114
// Check token mapping
function checkTokenMapping(address token) external view returns (address);
function checkTokenMapping(address token) external view returns (address);
36,814
686
// Interface of the Locker functions. /
interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); }
interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); }
29,104
115
// Yeld
if (getGeneratedYelds() > 0) extractYELDEarningsWhileKeepingDeposit(); depositBlockStarts[msg.sender] = block.number;
if (getGeneratedYelds() > 0) extractYELDEarningsWhileKeepingDeposit(); depositBlockStarts[msg.sender] = block.number;
9,738
498
// Calculate denominator for row 103: x - g^103z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x760))) mstore(add(productsPtr, 0x4c0), partialProduct) mstore(add(valuesPtr, 0x4c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x760))) mstore(add(productsPtr, 0x4c0), partialProduct) mstore(add(valuesPtr, 0x4c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
64,043
125
// returns provider rewards for a specific pool and reserveprovider the owner of the liquidity poolToken the pool token representing the rewards pool reserveToken the reserve token representing the liquidity in the pool return provider rewards for a specific pool and reserve /
function providerRewards( address provider, IDSToken poolToken, IERC20 reserveToken
function providerRewards( address provider, IDSToken poolToken, IERC20 reserveToken
70,970
28
// _Available since v3.1._ /
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() public { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } }
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() public { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } }
12,598
285
// gasUsed_userDeposit_plan.bonusNumerator / bonusDenominator / plan.perGas
return gasUsed_.mul(userDeposit_).mul(plan.bonusNumerator) / plan.bonusDenominator / plan.perGas;
return gasUsed_.mul(userDeposit_).mul(plan.bonusNumerator) / plan.bonusDenominator / plan.perGas;
22,047
2
// Set how many days after last activity funds should be released to beneficiary /
function setGracePeriod(uint256 _days) public onlyOwner { require(_days > 0, "Must be more than 0 days"); releaseFundsAfterDays = _days; }
function setGracePeriod(uint256 _days) public onlyOwner { require(_days > 0, "Must be more than 0 days"); releaseFundsAfterDays = _days; }
21,292
117
// Internal function to set the token IPFS hash for a given token. Reverts if the token ID does not exist.niftyType uint256 ID of the token to set its URIipfs_hash string IPFS link to assign/
function _setTokenIPFSHashNiftyType(uint256 niftyType, string memory ipfs_hash) internal { // require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _niftyTypeIPFSHashes[niftyType] = ipfs_hash; }
function _setTokenIPFSHashNiftyType(uint256 niftyType, string memory ipfs_hash) internal { // require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _niftyTypeIPFSHashes[niftyType] = ipfs_hash; }
5,665
81
// after the ico has run its course, the withdraw account can drain funds bit-by-bit as needed.
function requestPayout(uint _amount) public onlyWithdraw //very important! requireState(States.Operational)
function requestPayout(uint _amount) public onlyWithdraw //very important! requireState(States.Operational)
42,736
423
// function {_taxProcessing} Perform tax processingapplyTax_ Do we apply tax to this transaction? to_ The reciever of the token from_ The sender of the token sentAmount_ The amount being sendreturn amountLessTax_ The amount that will be recieved, i.e. the send amount minus tax /
function _taxProcessing( bool applyTax_, address to_, address from_, uint256 sentAmount_ ) internal returns (uint256 amountLessTax_) { amountLessTax_ = sentAmount_; unchecked { if (_tokenHasTax && applyTax_ && !_autoSwapInProgress) { uint256 tax;
function _taxProcessing( bool applyTax_, address to_, address from_, uint256 sentAmount_ ) internal returns (uint256 amountLessTax_) { amountLessTax_ = sentAmount_; unchecked { if (_tokenHasTax && applyTax_ && !_autoSwapInProgress) { uint256 tax;
11,520
29
// no need to require value <= totalSupply, since that would imply the sender's balance is greater than the totalSupply, which should be an assertion failure
balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value);
balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value);
4,489
28
// Allows an owner to begin transferring ownership to a new address,pending. /
function transferOwnership(address to) public override onlyOwner { _transferOwnership(to); }
function transferOwnership(address to) public override onlyOwner { _transferOwnership(to); }
28,080
236
// return the maximum amount of base token liquidity that can be single-sided staked in the pool
return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork);
return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork);
38,702
16
// this creates an 2 x 2 array with allowances
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => mapping (address => uint256)) public allowance;
4,504
92
// Limit the transfer to 600 tokens for 5 minutes
require(now > liquidityAddedAt + 6 minutes || amount <= 150e18, "You cannot transfer more than 150 tokens.");
require(now > liquidityAddedAt + 6 minutes || amount <= 150e18, "You cannot transfer more than 150 tokens.");
38,396
25
// Enables or disables approval for a third party ("operator") to manage all of`msg.sender`'s assets. It also emits the ApprovalForAll event. The contract MUST allow multiple operators per owner. _operator Address to add to the set of authorized operators. _approved True if the operators is approved, false to revoke approval. /
function setApprovalForAll(
function setApprovalForAll(
8,070
50
// unsigned long long int pr =totalPriceHalf/((total)/1000000000000+ totalPriceHalf/1000000000000); No half time? Return tower.
if (UsedTower.amountToHalfTime == 0){ return UsedTower.timer; }
if (UsedTower.amountToHalfTime == 0){ return UsedTower.timer; }
47,657
41
// This function transforms WNFT ERC20 tokens into their corresponding ERC721 assets./_wrapperContractAddress The address of the corresponding WNFT contract for this/ERC721 token./_nftIds An array of the ids of the NFTs to be transformed into ERC20s./_destinationAddresses An array of the addresses that each nft should be sent to./You can provide different addresses for each NFT in order to "airdrop" them in a single/transaction to many people.
function _burnTokensAndWithdrawNfts(address _wrapperContractAddress, uint256[] memory _nftIds, address[] memory _destinationAddresses) internal { if(_wrapperContractAddress != wrappedKittiesAddress){ WrappedNFT(_wrapperContractAddress).burnTokensAndWithdrawNfts(_nftIds, _destinationAddresses); } else { WrappedKitties(_wrapperContractAddress).burnTokensAndWithdrawKitties(_nftIds, _destinationAddresses); } }
function _burnTokensAndWithdrawNfts(address _wrapperContractAddress, uint256[] memory _nftIds, address[] memory _destinationAddresses) internal { if(_wrapperContractAddress != wrappedKittiesAddress){ WrappedNFT(_wrapperContractAddress).burnTokensAndWithdrawNfts(_nftIds, _destinationAddresses); } else { WrappedKitties(_wrapperContractAddress).burnTokensAndWithdrawKitties(_nftIds, _destinationAddresses); } }
39,571
84
// Returns whether `tokenId` exists.
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId <= numOwners() && _owners[tokenId] != address(0); }
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId <= numOwners() && _owners[tokenId] != address(0); }
6,543
8
// The time when the public sale ends.
uint256 public immutable endTime;
uint256 public immutable endTime;
3,644
284
// withdraw
function withdraw() external onlyOwner { uint256 RLFee = (address(this).balance * 600) / 10000; (bool successRLTransfer, ) = payable(WEBMINT_ADDRESS).call{ value: RLFee }(""); require(successRLTransfer, "Transfer Failed!"); (bool successFinal, ) = payable(0xc858Db9Fd379d21B49B2216e8bFC6588bE3354D7).call{ value: address(this).balance }(""); require(successFinal, "Transfer Failed!"); }
function withdraw() external onlyOwner { uint256 RLFee = (address(this).balance * 600) / 10000; (bool successRLTransfer, ) = payable(WEBMINT_ADDRESS).call{ value: RLFee }(""); require(successRLTransfer, "Transfer Failed!"); (bool successFinal, ) = payable(0xc858Db9Fd379d21B49B2216e8bFC6588bE3354D7).call{ value: address(this).balance }(""); require(successFinal, "Transfer Failed!"); }
38,862
76
// Reutrns user payment info by uId and paymentId /
function getUserPaymentById(uint _uId, uint _payId) public onlyMultiOwnersType(11) view returns( uint time, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus, uint tokenWithoutBonus, uint usdAbsRaisedInCents,
function getUserPaymentById(uint _uId, uint _payId) public onlyMultiOwnersType(11) view returns( uint time, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus, uint tokenWithoutBonus, uint usdAbsRaisedInCents,
42,346
31
// the amount of action used before hitting limit/replenishes at rateLimitPerSecond per second up to bufferCap/rateLimitedAddress the address whose buffer will be returned/ return the buffer of the specified rate limited address
function individualBuffer(address rateLimitedAddress) public view override returns (uint112)
function individualBuffer(address rateLimitedAddress) public view override returns (uint112)
9,563
173
// balance of this address in "want" tokens
function balanceOf() public view virtual override returns (uint256) { return IERC20(_want).balanceOf(address(this)); }
function balanceOf() public view virtual override returns (uint256) { return IERC20(_want).balanceOf(address(this)); }
80,900
19
// Update super token factory newFactory New factory logic /
function updateSuperTokenFactory(ISuperTokenFactory newFactory) external;
function updateSuperTokenFactory(ISuperTokenFactory newFactory) external;
4,450
57
// finalize a mint request, mint the amount requested to the specified address _index of the request (visible in the RequestMint event accompanying the original request) /
function finalizeMint(uint256 _index) public mintNotPaused { MintOperation memory op = mintOperations[_index]; address to = op.to; uint256 value = op.value; if (msg.sender != owner) { require(canFinalize(_index)); _subtractFromMintPool(value); } delete mintOperations[_index]; token.mint(to, value); emit FinalizeMint(to, value, _index, msg.sender); }
function finalizeMint(uint256 _index) public mintNotPaused { MintOperation memory op = mintOperations[_index]; address to = op.to; uint256 value = op.value; if (msg.sender != owner) { require(canFinalize(_index)); _subtractFromMintPool(value); } delete mintOperations[_index]; token.mint(to, value); emit FinalizeMint(to, value, _index, msg.sender); }
32,467
58
// Views/Getters. /
function earned(address director) internal override returns (uint256) { // Get the latest share per rewards i should get. uint256 latestRPS = getLatestSnapshot().rewardPerShare; // Get the last share per rewards i have claimed. uint256 storedRPS = getLastSnapshotOf(director).rewardPerShare; uint256 prevEpochRewards = 0; uint256 latestFundingTime = boardHistory[boardHistory.length - 1].time; // If last time rewards claimed were less than the latest epoch start time, // then we don't consider those rewards in further calculations and mark them // as pending. uint256 rewardEarnedCurrEpoch = ( // If i am have unclaimed amount from the previous epoch // this `rewardEarnedCurrEpoch` should be set to 0 // because i just moved `rewardEarnedCurrEpoch` to `rewardPending` // in the _updateRewards func. // Else it should be kept as it is. directors[director].lastClaimedOn < latestFundingTime ? 0 : directors[director].rewardEarnedCurrEpoch ); // If storedRPS is 0, that means we are claiming rewards for the first time, hence we need // to check when we bonded and accordingly calculate the final rps. if (storedRPS == 0) { uint256 firstBondedSnapshotIndex = bondingHistory[director].snapshotIndexWhenFirstBonded; // This gets the last epoch at which i bonded. // if i bonded after 1st allocatin this would get rewardPerShare for 1st epoch. // If i bonded after 2nd allocation would get rewardPerShare for 2nd epoch. // and 0 if 1 bonded before 1st. storedRPS = boardHistory[firstBondedSnapshotIndex].rewardPerShare; } // If the allocations are more than 2 the basically there's a possiblity // that i have not claimed rewards for more than 1 epoch. // this could have condition that i've not claimed at all or i have claimed 1st epoch // but not 2nd and now claiming at 3rd(assuming curr epoch is 3rd) // also we need to make sure that here, this code runs only if // i've bonded before the latest epoch else, overfollow occurs in sub. if (boardHistory.length > 2) { if ( bondingHistory[director].snapshotIndexWhenFirstBonded < latestSnapshotIndex() // this condition is added as overflow issues were occuring in case where i bond after latestEpoch. ) { // Get the last epohc's rewardPerShare. uint256 lastRPS = boardHistory[latestSnapshotIndex().sub(1)].rewardPerShare; // Get the pending rewards from prev epochs. uint256 prevToPrevEpochsRewardEarned = ( directors[director].lastClaimedOn < latestFundingTime ? 0 : directors[director].rewardEarnedCurrEpoch ); // Get the reward i deserved from the last epoch to the last epoch i already claimed. // if they are same this should be 0. prevEpochRewards = vault .balanceWithoutBonded(director) .mul(lastRPS.sub(storedRPS)) .div(1e18); // add the penidng rewards if any. prevEpochRewards = prevEpochRewards.add( prevToPrevEpochsRewardEarned ); // mark this as pending as these are till the last epoch. directors[director].rewardPending = directors[director] .rewardPending .add(prevEpochRewards); } } // calculate the reward from latest epoch to epoch i claimed last. uint256 rewards = vault .balanceWithoutBonded(director) .mul(latestRPS.sub(storedRPS)) .div(1e18) .add(rewardEarnedCurrEpoch); // now we have done a duplication caluclation, as in we have calcuated rewards from latest to lastClaimed // and from last to lastClaimed, i.e in case of 3 epoch lets say we claimed at 1. // so we've done 3 - 1 && 2 - 1. both of this contain (2 - 1). hece we subtract that duplication here. return rewards.sub(prevEpochRewards); }
function earned(address director) internal override returns (uint256) { // Get the latest share per rewards i should get. uint256 latestRPS = getLatestSnapshot().rewardPerShare; // Get the last share per rewards i have claimed. uint256 storedRPS = getLastSnapshotOf(director).rewardPerShare; uint256 prevEpochRewards = 0; uint256 latestFundingTime = boardHistory[boardHistory.length - 1].time; // If last time rewards claimed were less than the latest epoch start time, // then we don't consider those rewards in further calculations and mark them // as pending. uint256 rewardEarnedCurrEpoch = ( // If i am have unclaimed amount from the previous epoch // this `rewardEarnedCurrEpoch` should be set to 0 // because i just moved `rewardEarnedCurrEpoch` to `rewardPending` // in the _updateRewards func. // Else it should be kept as it is. directors[director].lastClaimedOn < latestFundingTime ? 0 : directors[director].rewardEarnedCurrEpoch ); // If storedRPS is 0, that means we are claiming rewards for the first time, hence we need // to check when we bonded and accordingly calculate the final rps. if (storedRPS == 0) { uint256 firstBondedSnapshotIndex = bondingHistory[director].snapshotIndexWhenFirstBonded; // This gets the last epoch at which i bonded. // if i bonded after 1st allocatin this would get rewardPerShare for 1st epoch. // If i bonded after 2nd allocation would get rewardPerShare for 2nd epoch. // and 0 if 1 bonded before 1st. storedRPS = boardHistory[firstBondedSnapshotIndex].rewardPerShare; } // If the allocations are more than 2 the basically there's a possiblity // that i have not claimed rewards for more than 1 epoch. // this could have condition that i've not claimed at all or i have claimed 1st epoch // but not 2nd and now claiming at 3rd(assuming curr epoch is 3rd) // also we need to make sure that here, this code runs only if // i've bonded before the latest epoch else, overfollow occurs in sub. if (boardHistory.length > 2) { if ( bondingHistory[director].snapshotIndexWhenFirstBonded < latestSnapshotIndex() // this condition is added as overflow issues were occuring in case where i bond after latestEpoch. ) { // Get the last epohc's rewardPerShare. uint256 lastRPS = boardHistory[latestSnapshotIndex().sub(1)].rewardPerShare; // Get the pending rewards from prev epochs. uint256 prevToPrevEpochsRewardEarned = ( directors[director].lastClaimedOn < latestFundingTime ? 0 : directors[director].rewardEarnedCurrEpoch ); // Get the reward i deserved from the last epoch to the last epoch i already claimed. // if they are same this should be 0. prevEpochRewards = vault .balanceWithoutBonded(director) .mul(lastRPS.sub(storedRPS)) .div(1e18); // add the penidng rewards if any. prevEpochRewards = prevEpochRewards.add( prevToPrevEpochsRewardEarned ); // mark this as pending as these are till the last epoch. directors[director].rewardPending = directors[director] .rewardPending .add(prevEpochRewards); } } // calculate the reward from latest epoch to epoch i claimed last. uint256 rewards = vault .balanceWithoutBonded(director) .mul(latestRPS.sub(storedRPS)) .div(1e18) .add(rewardEarnedCurrEpoch); // now we have done a duplication caluclation, as in we have calcuated rewards from latest to lastClaimed // and from last to lastClaimed, i.e in case of 3 epoch lets say we claimed at 1. // so we've done 3 - 1 && 2 - 1. both of this contain (2 - 1). hece we subtract that duplication here. return rewards.sub(prevEpochRewards); }
86,242