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
1
// TimeLockMock Generic TimeLock Cyril Lapinte - <cyril@openfiz.com> Guillaume Goutaudier - <ggoutaudier@swissledger.io>SPDX-License-Identifier: MIT Error messages /
contract TimeLockMock is TimeLock { constructor(address payable _target, uint64 _lockedUntil) TimeLock(_target, _lockedUntil) {} function setLockedUntilTest(uint64 _lockedUntil) public returns (bool) { lockedUntil_ = _lockedUntil; return true; } }
contract TimeLockMock is TimeLock { constructor(address payable _target, uint64 _lockedUntil) TimeLock(_target, _lockedUntil) {} function setLockedUntilTest(uint64 _lockedUntil) public returns (bool) { lockedUntil_ = _lockedUntil; return true; } }
4,478
22
// Increase the amount of ETH that an owner allowed to a spender. approve should be called when allowed[msg.sender][spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.solEmits an Approval event. _spender The address which will spend the funds. _addedValue The amount of ETH to increase the allowance by. /
function increaseAllowance(address _spender, uint _addedValue) public returns (bool) { require(_spender != address(0), "Spender address is 0"); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
function increaseAllowance(address _spender, uint _addedValue) public returns (bool) { require(_spender != address(0), "Spender address is 0"); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
38,123
4
// total amount of SPOOL token vested
uint256 public override total;
uint256 public override total;
34,593
57
// This will remove the liquidity tokens
assets[0] = Common.Asset( CASH_GROUP, 0, maturity,
assets[0] = Common.Asset( CASH_GROUP, 0, maturity,
32,538
3
// Allows the admin to withdraw the performance fee, if applicable. This function can be called only by the contract's admin./Cannot be called before the game ends.
function adminFeeWithdraw() external override onlyOwner whenGameIsCompleted
function adminFeeWithdraw() external override onlyOwner whenGameIsCompleted
26,205
4
// undate fee percentage for claim ape for compound fee new fee percentage /
function setClaimApeForCompoundFee(uint256 fee) external;
function setClaimApeForCompoundFee(uint256 fee) external;
22,556
3
// A record of the highest bid
mapping (uint => Bid) public phaycBids;
mapping (uint => Bid) public phaycBids;
10,203
53
// calculate new accumulated reward per share new acc. reward per share = current acc. reward per share + (newly accumulated rewards / totalStakedAmount)
liquidityMiningPools[tokenAddress].accRewardPerShare = liquidityMiningPools[tokenAddress].accRewardPerShare + ((liquidityMiningPools[tokenAddress].totalRewardAmount - liquidityMiningPools[tokenAddress].lastRewardAmount) * _DIV_PRECISION) / liquidityMiningPools[tokenAddress].totalStakedAmount;
liquidityMiningPools[tokenAddress].accRewardPerShare = liquidityMiningPools[tokenAddress].accRewardPerShare + ((liquidityMiningPools[tokenAddress].totalRewardAmount - liquidityMiningPools[tokenAddress].lastRewardAmount) * _DIV_PRECISION) / liquidityMiningPools[tokenAddress].totalStakedAmount;
33,238
20
// If the user sent a 0 ETH transaction, withdraw their SNT.
if(msg.value == 0) { withdraw(); }
if(msg.value == 0) { withdraw(); }
25,262
10
// update holding info for `from`
staker.setHoldingInfoData(from, uint32(id), holding);
staker.setHoldingInfoData(from, uint32(id), holding);
26,697
115
// can be called only once
require(!isPreallocated);
require(!isPreallocated);
50,438
45
// Deduct fee (currenly 3%)
uint _trueInchToSell = _inchToSell.mul(conserveRate).div(conserveRateDigits);
uint _trueInchToSell = _inchToSell.mul(conserveRate).div(conserveRateDigits);
78,275
520
// PerpetualLiquidatable Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. The liquidation has a liveness period before expiring successfully, during which someone can "dispute" theliquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based ona DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute falseliquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, aprospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.NOTE: this contract does _not_ work with ERC777 collateral
contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculating using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt.Therefore the TRV consideres the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } }
contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculating using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt.Therefore the TRV consideres the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } }
5,853
8
// Sell OUSD for USDC/amount Amount of OUSD to sell, in 18 fixed decimals.
function sellOusdForUsdc(uint256 amount) external { require(amount <= MAXIMUM_PER_TRADE, "Amount too large"); require(usdc.transfer(msg.sender, amount / 1e12)); require(ousd.transferFrom(msg.sender, address(this), amount)); }
function sellOusdForUsdc(uint256 amount) external { require(amount <= MAXIMUM_PER_TRADE, "Amount too large"); require(usdc.transfer(msg.sender, amount / 1e12)); require(ousd.transferFrom(msg.sender, address(this), amount)); }
21,620
70
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length);
bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length);
40,392
77
// How much system liquidity is provided by this asset
function _utilization(address token, uint amount) internal view returns (uint) { address _pair = UniswapFactory(UNI.factory()).getPair(token, address(this)); uint _ratio = BASE.sub(BASE.mul(balanceOf(_pair).add(amount)).div(totalSupply())); if (_ratio == 0) { return MAX; } return _ratio > MAX ? MAX : _ratio; }
function _utilization(address token, uint amount) internal view returns (uint) { address _pair = UniswapFactory(UNI.factory()).getPair(token, address(this)); uint _ratio = BASE.sub(BASE.mul(balanceOf(_pair).add(amount)).div(totalSupply())); if (_ratio == 0) { return MAX; } return _ratio > MAX ? MAX : _ratio; }
56,960
103
// withdraw non-invoice tokens
function withdrawTokens(address _token) external nonReentrant { if (_token == token) { withdraw(); } else { require(block.timestamp > terminationTime, "!terminated"); uint256 balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, "balance is 0"); IERC20(token).safeTransfer(client, balance); } }
function withdrawTokens(address _token) external nonReentrant { if (_token == token) { withdraw(); } else { require(block.timestamp > terminationTime, "!terminated"); uint256 balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, "balance is 0"); IERC20(token).safeTransfer(client, balance); } }
9,302
5
// returns roundId, answer, startedAt, updatedAt, answeredInRound
function getRoundData(uint80 _roundId) public override view returns (uint80, int256, uint256, uint256, uint80)
function getRoundData(uint80 _roundId) public override view returns (uint80, int256, uint256, uint256, uint80)
49,053
6
// Gets the Merkle root associated with the current sale/ return The Merkle root, as a bytes32 hash
function getMerkleRoot() external view returns (bytes32) { return _merkleRoot; }
function getMerkleRoot() external view returns (bytes32) { return _merkleRoot; }
55,029
29
// Before mutate strategyTokens, convert current strategy tokens to ETH
uint256 ethConverted = _convertStrategyTokensToEth(totalTokenStored(), deadline); delete _strategyTokens; for (uint8 i = 0; i < strategyTokens_.length; i++) { _strategyTokens.push(StategyToken(strategyTokens_[i], tokenPercentage_[i])); }
uint256 ethConverted = _convertStrategyTokensToEth(totalTokenStored(), deadline); delete _strategyTokens; for (uint8 i = 0; i < strategyTokens_.length; i++) { _strategyTokens.push(StategyToken(strategyTokens_[i], tokenPercentage_[i])); }
71,887
28
// Return ERC20 balance
uint256 balance = REWARD_TOKEN.balanceOf(address(this)); if (STAKE_TOKEN == REWARD_TOKEN) { return balance - totalStaked; }
uint256 balance = REWARD_TOKEN.balanceOf(address(this)); if (STAKE_TOKEN == REWARD_TOKEN) { return balance - totalStaked; }
24,989
19
// Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and thedeadline to be reached. Emits a {ProposalExecuted} event. Note: some module can modify the requirements for execution, for example by adding an additional timelock. /
function execute(
function execute(
20,517
231
// ========== MUTATIVE FUNCTIONS ========== // Process the latest pending action of the strategy it yields amount of funds processed as well as the reward buffer of the strategy.The function will auto-compound rewards if requested and supported. Requirements: - the slippages provided must be valid in length- if the redeposit flag is set to true, the strategy must supportcompounding of rewardsslippages slippages to process redeposit if redepositing is to occur swapData swap data for processing /
function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override
function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override
65,171
26
// Increase the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol_spender The address which will spend the funds._addedValue The amount of tokens to increase the allowance by./
function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool)
function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool)
6,450
71
// _relayer New relayer addressOnly the owner can install a new relayer
function installRelayer(address _relayer) onlyOwner public { require(!relayers[_relayer], "Relayer is already installed."); require(_relayer != address(this), "The relay contract cannot be installed as a relayer."); relayers[_relayer] = true; emit RelayerInstalled(_relayer); }
function installRelayer(address _relayer) onlyOwner public { require(!relayers[_relayer], "Relayer is already installed."); require(_relayer != address(this), "The relay contract cannot be installed as a relayer."); relayers[_relayer] = true; emit RelayerInstalled(_relayer); }
10,005
6
// : Owner can add, delete or update Receiver requirements /
function updateReceiverRequirements(bytes32[] _attributes, bytes32[] _values) public onlyOwner { uint256 pairsNumber = _attributes.length; require( pairsNumber == _values.length); pairs memory newPair; receiverRequirements.length = 0; if (pairsNumber == 0) emit ReceiverRequirementsUpdated("no requirements", "no requirements", now); for (uint256 i = 0; i < pairsNumber; i++) { newPair.attribute = _attributes[i]; newPair.value =_values[i]; receiverRequirements.push(newPair); emit ReceiverRequirementsUpdated(_attributes[i], _values[i], now); } }
function updateReceiverRequirements(bytes32[] _attributes, bytes32[] _values) public onlyOwner { uint256 pairsNumber = _attributes.length; require( pairsNumber == _values.length); pairs memory newPair; receiverRequirements.length = 0; if (pairsNumber == 0) emit ReceiverRequirementsUpdated("no requirements", "no requirements", now); for (uint256 i = 0; i < pairsNumber; i++) { newPair.attribute = _attributes[i]; newPair.value =_values[i]; receiverRequirements.push(newPair); emit ReceiverRequirementsUpdated(_attributes[i], _values[i], now); } }
14,189
111
// Request VIT token contract to mint the requested tokens for the buyer.
assert(vitToken.mint(_recipient, _tokens)); TokensIssued(_recipient, _tokens);
assert(vitToken.mint(_recipient, _tokens)); TokensIssued(_recipient, _tokens);
14,419
120
// the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty
uint16 maxRoyaltyPercentage; // 1.75% = 175, 100% = 10000
uint16 maxRoyaltyPercentage; // 1.75% = 175, 100% = 10000
34,668
12
// add a chapter TODO: deposit TODO: PRECONDICION comprobar el numero de capitulos; TODO: EVENTO
function addChapter(string _alias, string _chaptertext, string _chaptertitle) external { //comprobacion ojocuidao concurrencia (modificador) //Bucar el primer capitulo nulo //Si no hay se cancela () //Lanzaria evento capitulo añadido uint index = checkIfAddChapter(); require(index<=contestants); contestantchapters[index].author = msg.sender; contestantchapters[index].alias = _alias; contestantchapters[index].chaptertext = _chaptertext; contestantchapters[index].chaptertitle = _chaptertitle; newChapter(true,index); }
function addChapter(string _alias, string _chaptertext, string _chaptertitle) external { //comprobacion ojocuidao concurrencia (modificador) //Bucar el primer capitulo nulo //Si no hay se cancela () //Lanzaria evento capitulo añadido uint index = checkIfAddChapter(); require(index<=contestants); contestantchapters[index].author = msg.sender; contestantchapters[index].alias = _alias; contestantchapters[index].chaptertext = _chaptertext; contestantchapters[index].chaptertitle = _chaptertitle; newChapter(true,index); }
5,361
238
// Hook function after iToken `repayBorrow()`Will `revert()` if any operation fails _iToken The iToken being repaid _payer The account which would repay _borrower The account which has borrowed _repayAmountThe amount of underlying being repaied /
function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount
function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount
40,555
10
// Event that is emitted when an existing token is burned
event Burn(uint256 indexed tokenId);
event Burn(uint256 indexed tokenId);
54,299
0
// Upgrade functions
function initialize( string memory _name, string memory _symbol, string memory _baseTokenURI
function initialize( string memory _name, string memory _symbol, string memory _baseTokenURI
76,880
92
// Subtract `elastic` and `base` to `total`.
function sub( Rebase memory total, uint256 elastic, uint256 base
function sub( Rebase memory total, uint256 elastic, uint256 base
33,567
20
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code }
enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code }
27,543
26
// Human State
string public name; uint8 public decimals; string public symbol; string public version;
string public name; uint8 public decimals; string public symbol; string public version;
32,338
92
// transfer memberEarnings
require(tokenMainnet.approve(address(tokenMediatorMainnet), newTokens), "approve_failed");
require(tokenMainnet.approve(address(tokenMediatorMainnet), newTokens), "approve_failed");
68,223
5
// Mapping from owner address to mapping of operator addresses. /
mapping (address => mapping (address => bool)) internal ownerToOperators;
mapping (address => mapping (address => bool)) internal ownerToOperators;
27,060
14
// Array with all NFT's minted
ModelNFT [] public NFTModels;
ModelNFT [] public NFTModels;
53,014
170
// Emit ReplicaCreated event
emit ReplicaCreated( msg.sender, originalTokenAddress, originalTokenId, replicaTokenId, optionalComment ); return replicaTokenId;
emit ReplicaCreated( msg.sender, originalTokenAddress, originalTokenId, replicaTokenId, optionalComment ); return replicaTokenId;
43,680
7
// Copy remaining bytes
uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) }
uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) }
33,454
6
// Mints `value` tokens to `recipient`, returning true on success. recipient address to mint to. value amount of tokens to mint.return True if the mint succeeded, or False. /
function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool)
function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool)
19,607
4
// Latest checkpoint for this stake. Staking rewards should only be/ calculated from this moment forward. Anything past it should already/ be accounted for in `tokenAmount`
uint256 lastCheckpointAt; uint256 S; bool finishedAccumulating;
uint256 lastCheckpointAt; uint256 S; bool finishedAccumulating;
28,509
68
// create deposit contract address for the default withdraw wallet_wallet the binded default withdraw wallet address /
function createDepositContract(address _wallet) onlyOwner public returns (address) { require(_wallet != address(0)); DepositWithdraw deposWithdr = new DepositWithdraw(_wallet); // new contract for deposit address _deposit = address(deposWithdr); walletDeposits[_wallet] = _deposit; WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; withdrawWalletList.push(WithdrawWallet("default wallet", _wallet)); // depositRepos[_deposit].balance = 0; depositRepos[_deposit].frozen = 0; emit CreateDepositAddress(_wallet, address(deposWithdr)); return deposWithdr; }
function createDepositContract(address _wallet) onlyOwner public returns (address) { require(_wallet != address(0)); DepositWithdraw deposWithdr = new DepositWithdraw(_wallet); // new contract for deposit address _deposit = address(deposWithdr); walletDeposits[_wallet] = _deposit; WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; withdrawWalletList.push(WithdrawWallet("default wallet", _wallet)); // depositRepos[_deposit].balance = 0; depositRepos[_deposit].frozen = 0; emit CreateDepositAddress(_wallet, address(deposWithdr)); return deposWithdr; }
6,725
69
// Swap the baseTokens for a target root. In the case of where the specified token the user wants is part of the childZap, the zap that occurs is to swap the baseTokens to the lpToken specified in the childZap struct. If there is no childZap, then the contract sends the tokens to the recipient
amount = _zapCurveLpOut( _zap, baseTokenAmount, _info.targetNeedsChildZap ? 0 : _info.minRootTokenAmount, _info.targetNeedsChildZap ? payable(address(this)) : _info.recipient );
amount = _zapCurveLpOut( _zap, baseTokenAmount, _info.targetNeedsChildZap ? 0 : _info.minRootTokenAmount, _info.targetNeedsChildZap ? payable(address(this)) : _info.recipient );
21,148
70
// Returns `user`'s Internal Balance for a set of tokens. /
function getInternalBalance(address user, IERC20[] calldata tokens) external view returns (uint256[] memory);
function getInternalBalance(address user, IERC20[] calldata tokens) external view returns (uint256[] memory);
56,600
11
// Function, called by Governance, that cancels a transaction, returns the callData executed target smart contract target value wei value of the transaction signature function signature of the transaction data function arguments of the transaction or callData if signature empty executionTime time at which to execute the transaction withDelegatecall boolean, true = transaction delegatecalls the target, else calls the targetreturn the callData executed as memory bytes /
) public payable override onlyAdmin returns (bytes memory) { bytes32 actionHash = keccak256( abi.encode( target, value, bytes4(keccak256(bytes(signature))), data, executionTime, withDelegatecall ) ); require(_queuedTransactions[actionHash], Errors.TLE_ACTION_NOT_QUEUED); require(block.timestamp >= executionTime, Errors.TLE_TIMELOCK_NOT_FINISHED); require( block.timestamp <= executionTime + GRACE_PERIOD, Errors.TLE_GRACE_PERIOD_FINISHED ); _queuedTransactions[actionHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } bool success; bytes memory resultData; if (withDelegatecall) { require(msg.value >= value, Errors.TLE_NOT_ENOUGH_MSG_VALUE); // solium-disable-next-line security/no-call-value (success, resultData) = target.delegatecall(callData); } else { // solium-disable-next-line security/no-call-value (success, resultData) = target.call{value: value}(callData); } require(success, string(resultData)); emit ExecutedAction( actionHash, target, value, signature, data, executionTime, withDelegatecall, resultData ); return resultData; }
) public payable override onlyAdmin returns (bytes memory) { bytes32 actionHash = keccak256( abi.encode( target, value, bytes4(keccak256(bytes(signature))), data, executionTime, withDelegatecall ) ); require(_queuedTransactions[actionHash], Errors.TLE_ACTION_NOT_QUEUED); require(block.timestamp >= executionTime, Errors.TLE_TIMELOCK_NOT_FINISHED); require( block.timestamp <= executionTime + GRACE_PERIOD, Errors.TLE_GRACE_PERIOD_FINISHED ); _queuedTransactions[actionHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } bool success; bytes memory resultData; if (withDelegatecall) { require(msg.value >= value, Errors.TLE_NOT_ENOUGH_MSG_VALUE); // solium-disable-next-line security/no-call-value (success, resultData) = target.delegatecall(callData); } else { // solium-disable-next-line security/no-call-value (success, resultData) = target.call{value: value}(callData); } require(success, string(resultData)); emit ExecutedAction( actionHash, target, value, signature, data, executionTime, withDelegatecall, resultData ); return resultData; }
30,892
12
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0);
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0);
10,644
290
// Gets the current floor price of the token.
function getPrice() public view returns (uint256)
function getPrice() public view returns (uint256)
5,470
2
// Contains one sensor purchase entity /
contract Purchase is Secured, MetaDataContainer { uint public price; // price per second for which access was purchased uint public startTime; // the time at which the purchaser will gain access to this sensor uint public endTime; // the time at which the purchaser will lose access to this sensor address public purchaser; // address of the user address public sensor; // id of the sensor to which access was purchased constructor( uint _price, uint _startTime, uint _endTime, address _purchaser, address _sensor, address _gateKeeper ) public Secured(_gateKeeper) { price = _price; startTime = _startTime; endTime = _endTime; purchaser = _purchaser; sensor = _sensor; } /** * implementation of metadata methods */ function updateMetaData(string ipfsHash) public { super.updateMetaData(ipfsHash); } }
contract Purchase is Secured, MetaDataContainer { uint public price; // price per second for which access was purchased uint public startTime; // the time at which the purchaser will gain access to this sensor uint public endTime; // the time at which the purchaser will lose access to this sensor address public purchaser; // address of the user address public sensor; // id of the sensor to which access was purchased constructor( uint _price, uint _startTime, uint _endTime, address _purchaser, address _sensor, address _gateKeeper ) public Secured(_gateKeeper) { price = _price; startTime = _startTime; endTime = _endTime; purchaser = _purchaser; sensor = _sensor; } /** * implementation of metadata methods */ function updateMetaData(string ipfsHash) public { super.updateMetaData(ipfsHash); } }
35,505
144
// The RGB TOKEN!
RGBToken public RGB;
RGBToken public RGB;
11,149
15
// addresses of users that voted
mapping(address => bool) voters;
mapping(address => bool) voters;
36,035
8
// We use `pure` bbecause it promises that the value for the function depends ONLY on the function arguments
function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; }
function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; }
3,092
58
// Whether we should store the @BlockInfo for this block on-chain.
bool storeBlockInfoOnchain;
bool storeBlockInfoOnchain;
4,699
7
// Returns a list of prices from a list of assets addresses assets The list of assets addressesreturn The prices of the given assets /
function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory);
function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory);
19,028
77
// creates a new pool token and adds it to the list return new pool token address/
function createToken() public ownerOnly returns (ISmartToken) { // verify that the max limit wasn't reached require(_poolTokens.length < MAX_POOL_TOKENS, "ERR_MAX_LIMIT_REACHED"); string memory poolName = concatStrDigit(name, uint8(_poolTokens.length + 1)); string memory poolSymbol = concatStrDigit(symbol, uint8(_poolTokens.length + 1)); SmartToken token = new SmartToken(poolName, poolSymbol, decimals); _poolTokens.push(token); return token; }
function createToken() public ownerOnly returns (ISmartToken) { // verify that the max limit wasn't reached require(_poolTokens.length < MAX_POOL_TOKENS, "ERR_MAX_LIMIT_REACHED"); string memory poolName = concatStrDigit(name, uint8(_poolTokens.length + 1)); string memory poolSymbol = concatStrDigit(symbol, uint8(_poolTokens.length + 1)); SmartToken token = new SmartToken(poolName, poolSymbol, decimals); _poolTokens.push(token); return token; }
17,250
27
// 释放 {TransferBatch} 事件. /
function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = msg.sender;
function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = msg.sender;
24,500
11
// Returns the provenance hash. /
function provenanceHash() external view returns (bytes32) { return _provenanceHash; }
function provenanceHash() external view returns (bytes32) { return _provenanceHash; }
11,889
460
// StairstepExponentialDecrease/Implements a stairstep like exponential decreasing price curve for the collateral auction/ Uses StairstepExponentialDecrease.sol from DSS (MakerDAO) as a blueprint/ Changes from StairstepExponentialDecrease.sol /:/ - only WAD precision is used (no RAD and RAY)/ - uses a method signature based authentication scheme/ - supports ERC1155, ERC721 style assets by TokenId
contract StairstepExponentialDecrease is Guarded, IPriceCalculator { /// ======== Custom Errors ======== /// error StairstepExponentialDecrease__setParam_factorGtWad(); error StairstepExponentialDecrease__setParam_unrecognizedParam(); /// ======== Storage ======== /// /// @notice Length of time between price drops [seconds] uint256 public step; /// @notice Per-step multiplicative factor [wad] uint256 public factor; /// ======== Events ======== /// event SetParam(bytes32 indexed param, uint256 data); // `factor` and `step` values must be correctly set for this contract to return a valid price constructor() Guarded() {} /// ======== Configuration ======== /// /// @notice Sets various variables for this contract /// @dev Sender has to be allowed to call this method /// @param param Name of the variable to set /// @param data New value to set for the variable [wad] function setParam(bytes32 param, uint256 data) external checkCaller { if (param == "factor") { if (data > WAD) revert StairstepExponentialDecrease__setParam_factorGtWad(); factor = data; } else if (param == "step") step = data; else revert StairstepExponentialDecrease__setParam_unrecognizedParam(); emit SetParam(param, data); } /// ======== Pricing ======== /// /// @notice Price calculation when price is decreased stairstep like, exponential in proportion to time: /// @dev `step` seconds between a price drop, /// `factor` factor encodes the percentage to decrease per step. /// For efficiency, the values is set as (1 - (% value / 100)) * WAD /// So, for a 1% decrease per step, factor would be (1 - 0.01) * WAD /// @param startPrice: Initial price [wad] /// @param time Current seconds since the start of the auction [seconds] /// @return Returns startPrice * (factor ^ time) function price(uint256 startPrice, uint256 time) external view override returns (uint256) { return wmul(startPrice, wpow(factor, time / step, WAD)); } }
contract StairstepExponentialDecrease is Guarded, IPriceCalculator { /// ======== Custom Errors ======== /// error StairstepExponentialDecrease__setParam_factorGtWad(); error StairstepExponentialDecrease__setParam_unrecognizedParam(); /// ======== Storage ======== /// /// @notice Length of time between price drops [seconds] uint256 public step; /// @notice Per-step multiplicative factor [wad] uint256 public factor; /// ======== Events ======== /// event SetParam(bytes32 indexed param, uint256 data); // `factor` and `step` values must be correctly set for this contract to return a valid price constructor() Guarded() {} /// ======== Configuration ======== /// /// @notice Sets various variables for this contract /// @dev Sender has to be allowed to call this method /// @param param Name of the variable to set /// @param data New value to set for the variable [wad] function setParam(bytes32 param, uint256 data) external checkCaller { if (param == "factor") { if (data > WAD) revert StairstepExponentialDecrease__setParam_factorGtWad(); factor = data; } else if (param == "step") step = data; else revert StairstepExponentialDecrease__setParam_unrecognizedParam(); emit SetParam(param, data); } /// ======== Pricing ======== /// /// @notice Price calculation when price is decreased stairstep like, exponential in proportion to time: /// @dev `step` seconds between a price drop, /// `factor` factor encodes the percentage to decrease per step. /// For efficiency, the values is set as (1 - (% value / 100)) * WAD /// So, for a 1% decrease per step, factor would be (1 - 0.01) * WAD /// @param startPrice: Initial price [wad] /// @param time Current seconds since the start of the auction [seconds] /// @return Returns startPrice * (factor ^ time) function price(uint256 startPrice, uint256 time) external view override returns (uint256) { return wmul(startPrice, wpow(factor, time / step, WAD)); } }
43,592
75
// Swap a token to another. tokenAddrIn - the token address to be deposited tokenAddrOut - the token address to be withdrawn tokenAmountIn - the amount (unnormalized) of the token to be deposited tokenAmountOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn /
function swap( address tokenAddrIn, address tokenAddrOut, uint256 tokenAmountIn, uint256 tokenAmountOutMin ) external nonReentrant whenNotPaused
function swap( address tokenAddrIn, address tokenAddrOut, uint256 tokenAmountIn, uint256 tokenAmountOutMin ) external nonReentrant whenNotPaused
22,703
162
// Otherwise, only trigger if it "makes sense" economically (gas cost is <N% of value moved)
uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit));
uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit));
2,787
173
// Check address is in whiteList
function isAddressInWhitelist(address _addr) public view virtual returns(bool) { return whiteList[_addr] == true; }
function isAddressInWhitelist(address _addr) public view virtual returns(bool) { return whiteList[_addr] == true; }
28,060
200
// Whether `a` is greater than `b`. a a FixedPoint.Signed. b a FixedPoint.Signed.return True if `a > b`, or False. /
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; }
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; }
40,694
46
// /
address retval; assembly{ mstore(0x0, or (0x5880730000000000000000000000000000000000000000803b80938091923cF3 , mul(a,0x1000000000000000000))) retval := create(0, 0, 32) switch extcodesize(retval) case 0 { revert(0, 0) }
address retval; assembly{ mstore(0x0, or (0x5880730000000000000000000000000000000000000000803b80938091923cF3 , mul(a,0x1000000000000000000))) retval := create(0, 0, 32) switch extcodesize(retval) case 0 { revert(0, 0) }
14,656
34
// Send a stability fee reward to an addressproposedFeeReceiver The SF receiverreward The system coin amount to send/
function rewardCaller(address proposedFeeReceiver, uint256 reward) internal { if (address(treasury) == proposedFeeReceiver) return; if (either(address(treasury) == address(0), reward == 0)) return; address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver; try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {} catch(bytes memory revertReason) { emit FailRewardCaller(revertReason, finalFeeReceiver, reward); } }
function rewardCaller(address proposedFeeReceiver, uint256 reward) internal { if (address(treasury) == proposedFeeReceiver) return; if (either(address(treasury) == address(0), reward == 0)) return; address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver; try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {} catch(bytes memory revertReason) { emit FailRewardCaller(revertReason, finalFeeReceiver, reward); } }
53,719
65
// Refusing KYC of a user, who contributed in ETH. Send back the ETH funds and deny delivery of TUC tokens._user The account of the user to refuse KYC. /
function kycRefuse(address _user) external onlyKycTeam
function kycRefuse(address _user) external onlyKycTeam
19,642
149
// NFT stage Paused= 0, Presale = 1, Public = 2.
uint8 private _projectStage = 0; bool public reveled = false;
uint8 private _projectStage = 0; bool public reveled = false;
31,849
96
// IChanceToken Prophecy Interface for ChanceToken /
interface IChanceToken { /** * OWNER ALLOWED MINTER: Mint NFT */ function mint(address _account, uint256 _id, uint256 _amount) external; /** * OWNER ALLOWED BURNER: Burn NFT */ function burn(address _account, uint256 _id, uint256 _amount) external; }
interface IChanceToken { /** * OWNER ALLOWED MINTER: Mint NFT */ function mint(address _account, uint256 _id, uint256 _amount) external; /** * OWNER ALLOWED BURNER: Burn NFT */ function burn(address _account, uint256 _id, uint256 _amount) external; }
67,735
87
// and then return the updated output
return amountOut.sub(impliedYieldFee);
return amountOut.sub(impliedYieldFee);
71,244
263
// XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs. If yes, the result should be negative.
result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
26,536
18
// to get the verdict of kyc processstatus is the kyc status _add is the address of member /
function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); }
function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); }
5,231
23
// init method /
function init( ) public initializer
function init( ) public initializer
82,013
54
// Application Bylaws mapping /
function setBylawUint256(bytes32 name, uint256 value) public requireNotInitialised onlyDeployer { BylawsUint256[name] = value; }
function setBylawUint256(bytes32 name, uint256 value) public requireNotInitialised onlyDeployer { BylawsUint256[name] = value; }
38,692
292
// ERC721().approve(msg.sender, _tokenId);
ERC721(address(this)).transferFrom(owner, msg.sender, _tokenId); emit Transfer(owner, msg.sender, _tokenId, _timestamp); lastSoldPrice[_tokenId] = LastSoldPrice(2, _price, _timestamp); delete listedPrice[_tokenId][owner]; delete offeredPricesOfToken[_tokenId][owner]; emit Sold(msg.sender, owner, _tokenId, _price, 2, _timestamp);
ERC721(address(this)).transferFrom(owner, msg.sender, _tokenId); emit Transfer(owner, msg.sender, _tokenId, _timestamp); lastSoldPrice[_tokenId] = LastSoldPrice(2, _price, _timestamp); delete listedPrice[_tokenId][owner]; delete offeredPricesOfToken[_tokenId][owner]; emit Sold(msg.sender, owner, _tokenId, _price, 2, _timestamp);
29,842
6
// disallow empty release manifest URI
revert("escape:ReleaseValidator:invalid-manifest-uri");
revert("escape:ReleaseValidator:invalid-manifest-uri");
7,602
190
// ECC BRIDDGE Send ECC tokens to user
require(IERC20(address(tokenAddress)).transfer(address(account), _withdrawableDividend), "claim failed"); withdrawnDividends[account] += _withdrawableDividend; totalDividendsWithdrawn += _withdrawableDividend; emit DividendWithdrawn(account, _withdrawableDividend); return _withdrawableDividend;
require(IERC20(address(tokenAddress)).transfer(address(account), _withdrawableDividend), "claim failed"); withdrawnDividends[account] += _withdrawableDividend; totalDividendsWithdrawn += _withdrawableDividend; emit DividendWithdrawn(account, _withdrawableDividend); return _withdrawableDividend;
33,220
13
// When the raffle is asked to be cancelled and 30 days have passed, the operator can call a method to transfer the remaining funds and this event is emitted
event RemainingFundsTransferred( uint256 indexed raffleId, uint256 amountInWeis );
event RemainingFundsTransferred( uint256 indexed raffleId, uint256 amountInWeis );
31,829
143
// metadata
string public version = "1.0"; bytes32 public constant MODERATOR_ROLE = keccak256("MODERATOR_ROLE");
string public version = "1.0"; bytes32 public constant MODERATOR_ROLE = keccak256("MODERATOR_ROLE");
39,498
339
// Get the stake and its index
(LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id);
(LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id);
50,475
46
// 토큰 전송 사용 /
function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; }
function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; }
52,410
50
// Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,/ Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, andoptionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. /
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); }
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); }
15,828
33
// Governance Contract/Matter Labs
contract Governance is Config { /// @notice Token added to Franklin net event NewToken(address indexed token, uint16 indexed tokenId); /// @notice Default nft factory has set event SetDefaultNFTFactory(address indexed factory); /// @notice NFT factory registered new creator account event NFTFactoryRegisteredCreator( uint32 indexed creatorAccountId, address indexed creatorAddress, address factoryAddress ); /// @notice Governor changed event NewGovernor(address newGovernor); /// @notice Token Governance changed event NewTokenGovernance(TokenGovernance newTokenGovernance); /// @notice Validator's status changed event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive); event TokenPausedUpdate(address indexed token, bool paused); /// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades address public networkGovernor; /// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 public totalTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice List of permitted validators mapping(address => bool) public validators; /// @notice Paused tokens list, deposits are impossible to create for paused tokens mapping(uint16 => bool) public pausedTokens; /// @notice Address that is authorized to add tokens to the Governance. TokenGovernance public tokenGovernance; /// @notice NFT Creator address to factory address mapping mapping(uint32 => mapping(address => NFTFactory)) public nftFactories; /// @notice Address which will be used if NFT token has no factories NFTFactory public defaultFactory; /// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _networkGovernor The address of network governor function initialize(bytes calldata initializationParameters) external { address _networkGovernor = abi.decode(initializationParameters, (address)); networkGovernor = _networkGovernor; } /// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external {} /// @notice Change current governor /// @param _newGovernor Address of the new governor function changeGovernor(address _newGovernor) external { require(_newGovernor != address(0), "1n"); requireGovernor(msg.sender); if (networkGovernor != _newGovernor) { networkGovernor = _newGovernor; emit NewGovernor(_newGovernor); } } /// @notice Change current token governance /// @param _newTokenGovernance Address of the new token governor function changeTokenGovernance(TokenGovernance _newTokenGovernance) external { requireGovernor(msg.sender); if (tokenGovernance != _newTokenGovernance) { tokenGovernance = _newTokenGovernance; emit NewTokenGovernance(_newTokenGovernance); } } /// @notice Add token to the list of networks tokens /// @param _token Token address function addToken(address _token) external { require(msg.sender == address(tokenGovernance), "1E"); require(tokenIds[_token] == 0, "1e"); // token exists require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens totalTokens++; uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Pause token deposits for the given token /// @param _tokenAddr Token address /// @param _tokenPaused Token paused status function setTokenPaused(address _tokenAddr, bool _tokenPaused) external { requireGovernor(msg.sender); uint16 tokenId = this.validateTokenAddress(_tokenAddr); if (pausedTokens[tokenId] != _tokenPaused) { pausedTokens[tokenId] = _tokenPaused; emit TokenPausedUpdate(_tokenAddr, _tokenPaused); } } /// @notice Change validator status (active or not active) /// @param _validator Validator address /// @param _active Active flag function setValidator(address _validator, bool _active) external { requireGovernor(msg.sender); if (validators[_validator] != _active) { validators[_validator] = _active; emit ValidatorStatusUpdate(_validator, _active); } } /// @notice Check if specified address is is governor /// @param _address Address to check function requireGovernor(address _address) public view { require(_address == networkGovernor, "1g"); // only by governor } /// @notice Checks if validator is active /// @param _address Validator address function requireActiveValidator(address _address) external view { require(validators[_address], "1h"); // validator is not active } /// @notice Validate token id (must be less than or equal to total tokens amount) /// @param _tokenId Token id /// @return bool flag that indicates if token id is less than or equal to total tokens amount function isValidTokenId(uint16 _tokenId) external view returns (bool) { return _tokenId <= totalTokens; } /// @notice Validate token address /// @param _tokenAddr Token address /// @return tokens id function validateTokenAddress(address _tokenAddr) external view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "1i"); // 0 is not a valid token return tokenId; } function packRegisterNFTFactoryMsg( uint32 _creatorAccountId, address _creatorAddress, address _factoryAddress ) internal pure returns (bytes memory) { return abi.encodePacked( "\x19Ethereum Signed Message:\n141", "\nCreator's account ID in zkSync: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAccountId))), "\nCreator: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAddress))), "\nFactory: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_factoryAddress))) ); } /// @notice Register creator corresponding to the factory /// @param _creatorAccountId Creator's zkSync account ID /// @param _creatorAddress NFT creator address /// @param _signature Creator's signature function registerNFTFactoryCreator( uint32 _creatorAccountId, address _creatorAddress, bytes memory _signature ) external { require(address(nftFactories[_creatorAccountId][_creatorAddress]) == address(0), "Q"); bytes32 messageHash = keccak256(packRegisterNFTFactoryMsg(_creatorAccountId, _creatorAddress, msg.sender)); address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, messageHash); require(recoveredAddress == _creatorAddress, "ws"); nftFactories[_creatorAccountId][_creatorAddress] = NFTFactory(msg.sender); emit NFTFactoryRegisteredCreator(_creatorAccountId, _creatorAddress, msg.sender); } /// @notice Set default factory for our contract. This factory will be used to mint an NFT token that has no factory /// @param _factory Address of NFT factory function setDefaultNFTFactory(address _factory) external { requireGovernor(msg.sender); require(address(_factory) != address(0), "mb1"); // Factory should be non zero require(address(defaultFactory) == address(0), "mb2"); // NFTFactory is already set defaultFactory = NFTFactory(_factory); emit SetDefaultNFTFactory(_factory); } function getNFTFactory(uint32 _creatorAccountId, address _creatorAddress) external view returns (NFTFactory) { NFTFactory _factory = nftFactories[_creatorAccountId][_creatorAddress]; // even if the factory is undefined or has been destroyed, the user can mint NFT if (address(_factory) == address(0) || !isContract(address(_factory))) { require(address(defaultFactory) != address(0), "fs"); // NFTFactory does not set return defaultFactory; } else { return _factory; } } /// @return whether the address is a contract or not /// NOTE: for smart contracts that called `selfdestruct` will return a negative result function isContract(address _address) internal view returns (bool) { uint256 contractSize; assembly { contractSize := extcodesize(_address) } return contractSize != 0; } }
contract Governance is Config { /// @notice Token added to Franklin net event NewToken(address indexed token, uint16 indexed tokenId); /// @notice Default nft factory has set event SetDefaultNFTFactory(address indexed factory); /// @notice NFT factory registered new creator account event NFTFactoryRegisteredCreator( uint32 indexed creatorAccountId, address indexed creatorAddress, address factoryAddress ); /// @notice Governor changed event NewGovernor(address newGovernor); /// @notice Token Governance changed event NewTokenGovernance(TokenGovernance newTokenGovernance); /// @notice Validator's status changed event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive); event TokenPausedUpdate(address indexed token, bool paused); /// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades address public networkGovernor; /// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 public totalTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice List of permitted validators mapping(address => bool) public validators; /// @notice Paused tokens list, deposits are impossible to create for paused tokens mapping(uint16 => bool) public pausedTokens; /// @notice Address that is authorized to add tokens to the Governance. TokenGovernance public tokenGovernance; /// @notice NFT Creator address to factory address mapping mapping(uint32 => mapping(address => NFTFactory)) public nftFactories; /// @notice Address which will be used if NFT token has no factories NFTFactory public defaultFactory; /// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _networkGovernor The address of network governor function initialize(bytes calldata initializationParameters) external { address _networkGovernor = abi.decode(initializationParameters, (address)); networkGovernor = _networkGovernor; } /// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external {} /// @notice Change current governor /// @param _newGovernor Address of the new governor function changeGovernor(address _newGovernor) external { require(_newGovernor != address(0), "1n"); requireGovernor(msg.sender); if (networkGovernor != _newGovernor) { networkGovernor = _newGovernor; emit NewGovernor(_newGovernor); } } /// @notice Change current token governance /// @param _newTokenGovernance Address of the new token governor function changeTokenGovernance(TokenGovernance _newTokenGovernance) external { requireGovernor(msg.sender); if (tokenGovernance != _newTokenGovernance) { tokenGovernance = _newTokenGovernance; emit NewTokenGovernance(_newTokenGovernance); } } /// @notice Add token to the list of networks tokens /// @param _token Token address function addToken(address _token) external { require(msg.sender == address(tokenGovernance), "1E"); require(tokenIds[_token] == 0, "1e"); // token exists require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens totalTokens++; uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Pause token deposits for the given token /// @param _tokenAddr Token address /// @param _tokenPaused Token paused status function setTokenPaused(address _tokenAddr, bool _tokenPaused) external { requireGovernor(msg.sender); uint16 tokenId = this.validateTokenAddress(_tokenAddr); if (pausedTokens[tokenId] != _tokenPaused) { pausedTokens[tokenId] = _tokenPaused; emit TokenPausedUpdate(_tokenAddr, _tokenPaused); } } /// @notice Change validator status (active or not active) /// @param _validator Validator address /// @param _active Active flag function setValidator(address _validator, bool _active) external { requireGovernor(msg.sender); if (validators[_validator] != _active) { validators[_validator] = _active; emit ValidatorStatusUpdate(_validator, _active); } } /// @notice Check if specified address is is governor /// @param _address Address to check function requireGovernor(address _address) public view { require(_address == networkGovernor, "1g"); // only by governor } /// @notice Checks if validator is active /// @param _address Validator address function requireActiveValidator(address _address) external view { require(validators[_address], "1h"); // validator is not active } /// @notice Validate token id (must be less than or equal to total tokens amount) /// @param _tokenId Token id /// @return bool flag that indicates if token id is less than or equal to total tokens amount function isValidTokenId(uint16 _tokenId) external view returns (bool) { return _tokenId <= totalTokens; } /// @notice Validate token address /// @param _tokenAddr Token address /// @return tokens id function validateTokenAddress(address _tokenAddr) external view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "1i"); // 0 is not a valid token return tokenId; } function packRegisterNFTFactoryMsg( uint32 _creatorAccountId, address _creatorAddress, address _factoryAddress ) internal pure returns (bytes memory) { return abi.encodePacked( "\x19Ethereum Signed Message:\n141", "\nCreator's account ID in zkSync: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAccountId))), "\nCreator: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAddress))), "\nFactory: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_factoryAddress))) ); } /// @notice Register creator corresponding to the factory /// @param _creatorAccountId Creator's zkSync account ID /// @param _creatorAddress NFT creator address /// @param _signature Creator's signature function registerNFTFactoryCreator( uint32 _creatorAccountId, address _creatorAddress, bytes memory _signature ) external { require(address(nftFactories[_creatorAccountId][_creatorAddress]) == address(0), "Q"); bytes32 messageHash = keccak256(packRegisterNFTFactoryMsg(_creatorAccountId, _creatorAddress, msg.sender)); address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, messageHash); require(recoveredAddress == _creatorAddress, "ws"); nftFactories[_creatorAccountId][_creatorAddress] = NFTFactory(msg.sender); emit NFTFactoryRegisteredCreator(_creatorAccountId, _creatorAddress, msg.sender); } /// @notice Set default factory for our contract. This factory will be used to mint an NFT token that has no factory /// @param _factory Address of NFT factory function setDefaultNFTFactory(address _factory) external { requireGovernor(msg.sender); require(address(_factory) != address(0), "mb1"); // Factory should be non zero require(address(defaultFactory) == address(0), "mb2"); // NFTFactory is already set defaultFactory = NFTFactory(_factory); emit SetDefaultNFTFactory(_factory); } function getNFTFactory(uint32 _creatorAccountId, address _creatorAddress) external view returns (NFTFactory) { NFTFactory _factory = nftFactories[_creatorAccountId][_creatorAddress]; // even if the factory is undefined or has been destroyed, the user can mint NFT if (address(_factory) == address(0) || !isContract(address(_factory))) { require(address(defaultFactory) != address(0), "fs"); // NFTFactory does not set return defaultFactory; } else { return _factory; } } /// @return whether the address is a contract or not /// NOTE: for smart contracts that called `selfdestruct` will return a negative result function isContract(address _address) internal view returns (bool) { uint256 contractSize; assembly { contractSize := extcodesize(_address) } return contractSize != 0; } }
28,850
61
// Add Gnar glasses. /
function _addGlasses(bytes calldata _glasses) internal { glasses.push(_glasses); }
function _addGlasses(bytes calldata _glasses) internal { glasses.push(_glasses); }
39,167
37
// require(sent, "Failed to send Ether");
balances[msg.sender] -= amount;
balances[msg.sender] -= amount;
13,275
69
// Fired in setTokenURI()_by an address which executed update _tokenId token ID which URI was updated _oldVal old _baseURI value _newVal new _baseURI value /
event TokenURIUpdated(address indexed _by, uint256 _tokenId, string _oldVal, string _newVal);
event TokenURIUpdated(address indexed _by, uint256 _tokenId, string _oldVal, string _newVal);
24,725
213
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
set._values[toDeleteIndex] = lastvalue;
3,089
73
// start with the opponent attack to you
totalHits[0] += (allFinalAttackFigures[1][i] > allFinalDefenceFigures[0][i] ? allFinalAttackFigures[1][i] - allFinalDefenceFigures[0][i] : 0);
totalHits[0] += (allFinalAttackFigures[1][i] > allFinalDefenceFigures[0][i] ? allFinalAttackFigures[1][i] - allFinalDefenceFigures[0][i] : 0);
48,493
11
// Presale merkle root is invalid
error Presale_MerkleNotApproved();
error Presale_MerkleNotApproved();
37,948
193
// Allows the trusted aggregator to override the pending stateif it's possible to prove a different state root given the same batches initPendingStateNum Init pending state, 0 if consolidated state is used finalPendingStateNum Final pending state, that will be used to compare with the newStateRoot initNumBatch Batch which the aggregator starts the verification finalNewBatch Last batch aggregator intends to verify newLocalExitRootNew local exit root once the batch is processed newStateRoot New State root once the batch is processed proof fflonk proof /
function overridePendingState( uint64 initPendingStateNum, uint64 finalPendingStateNum, uint64 initNumBatch, uint64 finalNewBatch, bytes32 newLocalExitRoot, bytes32 newStateRoot, bytes calldata proof
function overridePendingState( uint64 initPendingStateNum, uint64 finalPendingStateNum, uint64 initNumBatch, uint64 finalNewBatch, bytes32 newLocalExitRoot, bytes32 newStateRoot, bytes calldata proof
6,314
6
// _rate Number of token units a buyer gets per wei _wallet Address where collected funds will be forwarded to _token Address of the token being sold /
constructor(uint256 _rate, address payable _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); //require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; }
constructor(uint256 _rate, address payable _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); //require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; }
4,165
93
// Now that the balance is updated and the event was emitted, call onERC1155Received if the destination is a contract.
if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data); }
if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data); }
51,709
166
// Ensure account escrow balance pending migration is not zero // Ensure account escrowed balance is not zero - should have been migrated // Add a vestable entry for addresses with totalBalancePendingMigration <= migrateEntriesThreshold amount of PERI // Remove totalBalancePendingMigration[addressToMigrate] // iterate and migrate old escrow schedules from rewardEscrow.vestingSchedulesstarting from the last entry in each staker's vestingSchedules /
for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX];
for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX];
40,559
118
// start community voting to include address in reward
function voteIncludeInReward(address account) external onlyOperator { require(pendingVote == "", "One vote is still running!"); require(_isExcluded[account], "Account is already excluded"); if(isOperator[vault]){ includeInReward(account); return; } string memory voteName = "Include in reward "; uint functionId = 5; setVoteTitelAddr(voteName, account, functionId); }
function voteIncludeInReward(address account) external onlyOperator { require(pendingVote == "", "One vote is still running!"); require(_isExcluded[account], "Account is already excluded"); if(isOperator[vault]){ includeInReward(account); return; } string memory voteName = "Include in reward "; uint functionId = 5; setVoteTitelAddr(voteName, account, functionId); }
3,572
220
// early exit with no other logic if transfering 0 (to prevent 0 transfers from triggering other logic)
if(amount == 0) { super._transfer(from, to, 0); return; }
if(amount == 0) { super._transfer(from, to, 0); return; }
44,722
266
// Adds an address to blockList. _user, address to block. /
function addToBlockedList (address _user) public onlyRole(DEFAULT_ADMIN_ROLE) { isBlocked[_user] = true; emit BlockPlaced(_user); }
function addToBlockedList (address _user) public onlyRole(DEFAULT_ADMIN_ROLE) { isBlocked[_user] = true; emit BlockPlaced(_user); }
28,688
33
// Notify for the Deposit on an existing Channel
emit DepositToChannel(id, msg.sender, msg.value);
emit DepositToChannel(id, msg.sender, msg.value);
45,164
11
// this line is to create an array to keep track of the bonds
Info[] public BondsinExistence; mapping (address => uint[]) public userCreatedBonds;
Info[] public BondsinExistence; mapping (address => uint[]) public userCreatedBonds;
18,213
61
// if transfer is restricted on the contract, we still want to allow burning and minting
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); }
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); }
19,312
109
// Bonus muliplier for early zookeepers.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
56,175
54
// We will replace the token we need to unregister with the last token Only the pos of the last token will need to be updated
address lastToken = addresses[addresses.length - 1];
address lastToken = addresses[addresses.length - 1];
73,187
39
// flag whether transfers are allowed on global scale./When `isTransferable` is `false`, all transfers between wallets are blocked.
bool internal isTransferable = false;
bool internal isTransferable = false;
37,886