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
30
// fees wrt to tax percentage
uint256 public _rfiFee = 10; // divided by 100 uint256 private _previousRfiFee = _rfiFee; uint256 public _lpFee = 10; // divided by 100 uint256 private _previousLpFee = _lpFee; mapping(address => bool) private bots; IUniswapV2Router02 private uniswapV2Router; address public uniswapV2Pair; uint256 private _maxTxAmount; uint256 private _maxWalletLimit;
uint256 public _rfiFee = 10; // divided by 100 uint256 private _previousRfiFee = _rfiFee; uint256 public _lpFee = 10; // divided by 100 uint256 private _previousLpFee = _lpFee; mapping(address => bool) private bots; IUniswapV2Router02 private uniswapV2Router; address public uniswapV2Pair; uint256 private _maxTxAmount; uint256 private _maxWalletLimit;
43,811
62
// returns the currently running tier index as per time Return -1 if no tier is running currently /
function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; }
function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; }
38,078
63
// the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick
uint160 secondsPerLiquidityCumulativeX128;
uint160 secondsPerLiquidityCumulativeX128;
4,245
100
// To paga usando NFTK y se le envia el NFT
function buyNFTWithNFTK(address _to, string memory _cid, uint256 _account) public { NFTMetadata memory _obj = indexOfCid[_cid]; //Se valida: // El NFT no este bloqueado para la venta (status), que el contrato no este pausado (pause) // El detinatario (_to) es el sender de la TX que autoriza la salida de NFTK (ERC20) require(_obj.status && !pause && _to==msg.sender,"NFT Not access"); _totalNFT=_totalNFT.add(_account); //Si son gratis solo puede tomarse 1 if (_obj.price>=0) { _account=1; //Transfer Tokens ERC20 - NFTKs To Owner of NFT _setTransferNFTK(_to, _obj.owner, _obj.price*_account); //Si aun tiene opciones de pagar fee if ( _obj.numberOfFee>0) { //Transfer To Address1 if (_obj.recipient_address1!=address(0)) { _setTransferNFTK(_to, _obj.recipient_address1, _obj.fee_address1*_account); } //Transfer To Address2 if (_obj.recipient_address2!=address(0)) { _setTransferNFTK(_to, _obj.recipient_address2, _obj.fee_address2*_account); } //Transfer To Address3 if (_obj.recipient_address3!=address(0)) { _setTransferNFTK(_to, _obj.recipient_address3, _obj.fee_address3*_account); } //Se reduce las veces que pagó regalías _obj.numberOfFee=_obj.numberOfFee.sub(1); } } //Transfer To NFT Item _safeTransferFrom(_obj.owner, _to, indexOfCid[_cid].id, _account, "Transfer"); //First transfer if ( _obj.owner== indexOfCid[_cid].creator) { indexOfCid[_cid].available = indexOfCid[_cid].available.sub(_account,"NFT Transfer ammount exceeds balance of NFT "); } }
function buyNFTWithNFTK(address _to, string memory _cid, uint256 _account) public { NFTMetadata memory _obj = indexOfCid[_cid]; //Se valida: // El NFT no este bloqueado para la venta (status), que el contrato no este pausado (pause) // El detinatario (_to) es el sender de la TX que autoriza la salida de NFTK (ERC20) require(_obj.status && !pause && _to==msg.sender,"NFT Not access"); _totalNFT=_totalNFT.add(_account); //Si son gratis solo puede tomarse 1 if (_obj.price>=0) { _account=1; //Transfer Tokens ERC20 - NFTKs To Owner of NFT _setTransferNFTK(_to, _obj.owner, _obj.price*_account); //Si aun tiene opciones de pagar fee if ( _obj.numberOfFee>0) { //Transfer To Address1 if (_obj.recipient_address1!=address(0)) { _setTransferNFTK(_to, _obj.recipient_address1, _obj.fee_address1*_account); } //Transfer To Address2 if (_obj.recipient_address2!=address(0)) { _setTransferNFTK(_to, _obj.recipient_address2, _obj.fee_address2*_account); } //Transfer To Address3 if (_obj.recipient_address3!=address(0)) { _setTransferNFTK(_to, _obj.recipient_address3, _obj.fee_address3*_account); } //Se reduce las veces que pagó regalías _obj.numberOfFee=_obj.numberOfFee.sub(1); } } //Transfer To NFT Item _safeTransferFrom(_obj.owner, _to, indexOfCid[_cid].id, _account, "Transfer"); //First transfer if ( _obj.owner== indexOfCid[_cid].creator) { indexOfCid[_cid].available = indexOfCid[_cid].available.sub(_account,"NFT Transfer ammount exceeds balance of NFT "); } }
1,131
16
// sets the lockRewards variable/_rewards The address of the rewards contract
function setRewardContracts(address _rewards) external onlyAddress(owner) { if (lockRewards == address(0)) { lockRewards = _rewards; } }
function setRewardContracts(address _rewards) external onlyAddress(owner) { if (lockRewards == address(0)) { lockRewards = _rewards; } }
32,272
192
// CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address
if (uint(AssetInterface(ofAsset).balanceOf(address(this))) < ownershipQuantities[i]) { isShutDown = true; emit ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; }
if (uint(AssetInterface(ofAsset).balanceOf(address(this))) < ownershipQuantities[i]) { isShutDown = true; emit ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; }
8,602
50
// if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = _amount / 2; token1Bought = _token2Token( _toContractAddress, _ToSushipoolToken1, amountToSwap ); token0Bought = _amount.sub(amountToSwap);
if (amountToSwap <= 0) amountToSwap = _amount / 2; token1Bought = _token2Token( _toContractAddress, _ToSushipoolToken1, amountToSwap ); token0Bought = _amount.sub(amountToSwap);
7,350
42
// Get the amount of each underlying token in each NFT
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper);
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper);
11,561
193
// Retrieve Replicants by GenerationReplicant[] replicants = replicantsByGeneration[uint8(_generation)] /
mapping(uint8 => Replicant[]) internal replicantsByGeneration;
mapping(uint8 => Replicant[]) internal replicantsByGeneration;
53,300
17
// Override the tokenURI
function tokenURI(uint256 _tokenId) public view override returns (string memory) { if (ownerOf(_tokenId) == address(0)) revert NonExistentTokenURI(); // Check if using on-chain metadata or not if (!useOnChainMetadata) { // Return the baseURI return baseURI; } // Return the on-chain metadata return getMetadata(); }
function tokenURI(uint256 _tokenId) public view override returns (string memory) { if (ownerOf(_tokenId) == address(0)) revert NonExistentTokenURI(); // Check if using on-chain metadata or not if (!useOnChainMetadata) { // Return the baseURI return baseURI; } // Return the on-chain metadata return getMetadata(); }
5,609
191
// Set the fee that it would cost a minter to be able to burn/validtion mint a token on this contract.
function setRedemptionSurcharge(uint256 _newSurchargeInWei) public onlyTeamOrOwner { redemptionSurcharge = _newSurchargeInWei; }
function setRedemptionSurcharge(uint256 _newSurchargeInWei) public onlyTeamOrOwner { redemptionSurcharge = _newSurchargeInWei; }
38,256
19
// Returns the auction configuration settings of a specific universe. universeId The id of the universereturn the struct containing the auction configuration settings of the specified universe. /
function universeAuctionConfig(uint256 universeId)
function universeAuctionConfig(uint256 universeId)
26,378
9
// override if the SuperApp shall have custom logic invoked when an existing flow/to it is updated (flowrate change).
function onFlowUpdated( ISuperToken /*superToken*/, address /*sender*/, int96 /*previousFlowRate*/, uint256 /*lastUpdated*/, bytes calldata ctx
function onFlowUpdated( ISuperToken /*superToken*/, address /*sender*/, int96 /*previousFlowRate*/, uint256 /*lastUpdated*/, bytes calldata ctx
21,502
150
// calcCallOptionPrice() imposes the restrictions of spotPrice, lbtPrice and nd1E8. /
function _calcLbtLeverage( uint256 spotPrice, uint256 lbtPrice, int256 nd1E8
function _calcLbtLeverage( uint256 spotPrice, uint256 lbtPrice, int256 nd1E8
41,478
7
// Only accept addresses that at least have contract code /
modifier onlyContract(address _contract) { require(Address.isContract(_contract), "!contract"); _; }
modifier onlyContract(address _contract) { require(Address.isContract(_contract), "!contract"); _; }
10,596
41
// owner can set the twap period in seconds that is used for calculating twaps for hedging _hedgingTwapPeriod the twap period, in seconds /
function setHedgingTwapPeriod(uint32 _hedgingTwapPeriod) external onlyOwner { require(_hedgingTwapPeriod >= 180, "twap period is too short"); hedgingTwapPeriod = _hedgingTwapPeriod; emit SetHedgingTwapPeriod(_hedgingTwapPeriod); }
function setHedgingTwapPeriod(uint32 _hedgingTwapPeriod) external onlyOwner { require(_hedgingTwapPeriod >= 180, "twap period is too short"); hedgingTwapPeriod = _hedgingTwapPeriod; emit SetHedgingTwapPeriod(_hedgingTwapPeriod); }
3,764
9
// Returns the link of a node `_node` in direction `_direction`./self stored linked list from contract/_node id of the node to step from/_direction direction to step in
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) internal view returns (bool,uint256)
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) internal view returns (bool,uint256)
79,642
61
// A registered transcoder cannot delegate its bonded stake toward another address because it can only be delegated toward itself In the future, if delegation towards another registered transcoder as an already registered transcoder becomes useful (i.e. for transitive delegation), this restriction could be removed
require(!isRegisteredTranscoder(_owner), "registered transcoders can't delegate towards other addresses");
require(!isRegisteredTranscoder(_owner), "registered transcoders can't delegate towards other addresses");
33,873
51
// 4% fee if a user deposits and withdraws after 1 hour but before 1 day.
pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(userFeeStage[2]).div(100)); pool.lpToken.safeTransfer(address(devaddr), _amount.mul(devFeeStage[2]).div(100));
pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(userFeeStage[2]).div(100)); pool.lpToken.safeTransfer(address(devaddr), _amount.mul(devFeeStage[2]).div(100));
13,423
37
// 토큰지갑에서 차감
balanceOf[owner] -= cal;
balanceOf[owner] -= cal;
28,038
161
// The type hash for ERC1155 sell orders, which is: keccak256(abi.encodePacked("ERC1155SellOrder(","address maker,","address taker,","uint256 expiry,","uint256 nonce,","address erc20Token,","uint256 erc20TokenAmount,","Fee[] fees,","address erc1155Token,","uint256 erc1155TokenId,","uint128 erc1155TokenAmount,","uint256 hashNonce",")","Fee(","address recipient,","uint256 amount,","bytes feeData",")" ))
uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda;
uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda;
2,530
25
// Counters.
uint256 public counterStolenAttempted = 0; uint256 public counterStolen = 0; uint256 public counterBail = 0; uint256 public counterJailed = 0;
uint256 public counterStolenAttempted = 0; uint256 public counterStolen = 0; uint256 public counterBail = 0; uint256 public counterJailed = 0;
2,752
125
// Sets the dev fee for this contract defaults at 7.24% Note contract owner is meant to be a governance contract allowing ORCA governance consensus
uint16 DEV_FEE;
uint16 DEV_FEE;
9,429
1
// displays the amount the account has staked on other pkgs
function sentStakeOf(address account) external view returns (address[] memory pkgs, uint256[] memory amounts) { (pkgs, amounts) = PkgStorage.layout().sentStakeOf(account); }
function sentStakeOf(address account) external view returns (address[] memory pkgs, uint256[] memory amounts) { (pkgs, amounts) = PkgStorage.layout().sentStakeOf(account); }
37,664
61
// Mint tokens during the first round
if(rounds.length == 1) { token.mint(msg.sender, newShares); }
if(rounds.length == 1) { token.mint(msg.sender, newShares); }
26,694
4
// Withdraws stake from pool and claims any unlocked rewards._firstIndex of the first array element to claim_last Index of the last array element to claim
function exit(uint256 _first, uint256 _last) external;
function exit(uint256 _first, uint256 _last) external;
48,622
161
// Creating new Wrapped ERC20 asset
return (currentContractAddress, _wrappedTokenTicker);
return (currentContractAddress, _wrappedTokenTicker);
62,203
27
// uintN[10]
function setU8Arr(uint8[10] memory u8a_para) public { u8_array10 = u8a_para; }
function setU8Arr(uint8[10] memory u8a_para) public { u8_array10 = u8a_para; }
28,642
7
// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards; uint256 public pendingYGYRewards; uint256 public YGYReserve;
uint256 public pendingRewards; uint256 public pendingYGYRewards; uint256 public YGYReserve;
32,345
8
// Will update the contract metadata URI _newContractMetadataURI New contract metadata URI /
function _setContractMetadataURI(string memory _newContractMetadataURI) internal
function _setContractMetadataURI(string memory _newContractMetadataURI) internal
33,172
1
// Template/Class which defines a Strategy/name Name of the strategy useful for logging what strategy is executing/creator Address of the user which created the strategy/triggerIds Array of identifiers for trigger - bytes4(keccak256(TriggerName))/actionIds Array of identifiers for actions - bytes4(keccak256(ActionName))/paramMapping Describes how inputs to functions are piped from return/subbed values/continuous If the action is repeated (continuos) or one time
struct Strategy { string name; address creator; bytes4[] triggerIds; bytes4[] actionIds; uint8[][] paramMapping; bool continuous; }
struct Strategy { string name; address creator; bytes4[] triggerIds; bytes4[] actionIds; uint8[][] paramMapping; bool continuous; }
49,510
12
// when constructing an account, validate constructor code and parameters we trust our factory (and that it doesn't have any other public methods)
function _validateConstructor(UserOperation calldata userOp) internal virtual view { address factory = address(bytes20(userOp.initCode[0 : 20])); require(factory == theFactory, "TokenPaymaster: wrong account factory"); }
function _validateConstructor(UserOperation calldata userOp) internal virtual view { address factory = address(bytes20(userOp.initCode[0 : 20])); require(factory == theFactory, "TokenPaymaster: wrong account factory"); }
21,771
27
// _Available since v3.1._ /
interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); }
interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); }
5,550
2
// Event emitted when controlled token is added
event ControlledTokenAdded(ITicket indexed token); event AwardCaptured(uint256 amount);
event ControlledTokenAdded(ITicket indexed token); event AwardCaptured(uint256 amount);
5,090
91
// Token decimals for vault shares
uint8 decimals;
uint8 decimals;
3,861
4
// can later be changed with {transferOwnership}./ Initializes the contract setting the deployer as the initial owner. /
constructor() { _transferOwnership(_msgSender()); }
constructor() { _transferOwnership(_msgSender()); }
116
30
// set date closed
envelopes[txid].closed=block.timestamp;
envelopes[txid].closed=block.timestamp;
26,289
148
// https:docs.peri.finance/contracts/RewardEscrow
contract BaseRewardEscrowV2 is Owned, IRewardEscrowV2, LimitedSetup(8 weeks), MixinResolver { using SafeMath for uint; using SafeDecimalMath for uint; mapping(address => mapping(uint256 => VestingEntries.VestingEntry)) public vestingSchedules; mapping(address => uint256[]) public accountVestingEntryIDs; /*Counter for new vesting entry ids. */ uint256 public nextEntryId; /* An account's total escrowed periFinance balance to save recomputing this for fee extraction purposes. */ mapping(address => uint256) public totalEscrowedAccountBalance; /* An account's total vested reward periFinance. */ mapping(address => uint256) public totalVestedAccountBalance; /* Mapping of nominated address to recieve account merging */ mapping(address => address) public nominatedReceiver; /* The total remaining escrowed balance, for verifying the actual periFinance balance of this contract against. */ uint256 public totalEscrowedBalance; /* Max escrow duration */ uint public max_duration = 2 * 52 weeks; // Default max 2 years duration /* Max account merging duration */ uint public maxAccountMergingDuration = 4 weeks; // Default 4 weeks is max /* ========== ACCOUNT MERGING CONFIGURATION ========== */ uint public accountMergingDuration = 1 weeks; uint public accountMergingStartTime; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_PERIFINANCE = "PeriFinance"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver) { nextEntryId = 1; } /* ========== VIEWS ======================= */ function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function periFinance() internal view returns (IPeriFinance) { return IPeriFinance(requireAndGetAddress(CONTRACT_PERIFINANCE)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function _notImplemented() internal pure { revert("Cannot be run on this layer"); } /* ========== VIEW FUNCTIONS ========== */ // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](3); addresses[0] = CONTRACT_PERIFINANCE; addresses[1] = CONTRACT_FEEPOOL; addresses[2] = CONTRACT_ISSUER; } /** * @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalEscrowedAccountBalance[account]; } /** * @notice The number of vesting dates in an account's schedule. */ function numVestingEntries(address account) external view returns (uint) { return accountVestingEntryIDs[account].length; } /** * @notice Get a particular schedule entry for an account. * @return The vesting entry object and rate per second emission. */ function getVestingEntry(address account, uint256 entryID) external view returns (uint64 endTime, uint256 escrowAmount) { endTime = vestingSchedules[account][entryID].endTime; escrowAmount = vestingSchedules[account][entryID].escrowAmount; } function getVestingSchedules( address account, uint256 index, uint256 pageSize ) external view returns (VestingEntries.VestingEntryWithID[] memory) { uint256 endIndex = index + pageSize; // If index starts after the endIndex return no results if (endIndex <= index) { return new VestingEntries.VestingEntryWithID[](0); } // If the page extends past the end of the accountVestingEntryIDs, truncate it. if (endIndex > accountVestingEntryIDs[account].length) { endIndex = accountVestingEntryIDs[account].length; } uint256 n = endIndex - index; VestingEntries.VestingEntryWithID[] memory vestingEntries = new VestingEntries.VestingEntryWithID[](n); for (uint256 i; i < n; i++) { uint256 entryID = accountVestingEntryIDs[account][i + index]; VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID]; vestingEntries[i] = VestingEntries.VestingEntryWithID({ endTime: uint64(entry.endTime), escrowAmount: entry.escrowAmount, entryID: entryID }); } return vestingEntries; } function getAccountVestingEntryIDs( address account, uint256 index, uint256 pageSize ) external view returns (uint256[] memory) { uint256 endIndex = index + pageSize; // If the page extends past the end of the accountVestingEntryIDs, truncate it. if (endIndex > accountVestingEntryIDs[account].length) { endIndex = accountVestingEntryIDs[account].length; } if (endIndex <= index) { return new uint256[](0); } uint256 n = endIndex - index; uint256[] memory page = new uint256[](n); for (uint256 i; i < n; i++) { page[i] = accountVestingEntryIDs[account][i + index]; } return page; } function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint total) { for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryIDs[i]]; /* Skip entry if escrowAmount == 0 */ if (entry.escrowAmount != 0) { uint256 quantity = _claimableAmount(entry); /* add quantity to total */ total = total.add(quantity); } } } function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint) { VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID]; return _claimableAmount(entry); } function _claimableAmount(VestingEntries.VestingEntry memory _entry) internal view returns (uint256) { uint256 quantity; if (_entry.escrowAmount != 0) { /* Escrow amounts claimable if block.timestamp equal to or after entry endTime */ quantity = block.timestamp >= _entry.endTime ? _entry.escrowAmount : 0; } return quantity; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * Vest escrowed amounts that are claimable * Allows users to vest their vesting entries based on msg.sender */ function vest(uint256[] calldata entryIDs) external { uint256 total; for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[msg.sender][entryIDs[i]]; /* Skip entry if escrowAmount == 0 already vested */ if (entry.escrowAmount != 0) { uint256 quantity = _claimableAmount(entry); /* update entry to remove escrowAmount */ if (quantity > 0) { entry.escrowAmount = 0; } /* add quantity to total */ total = total.add(quantity); } } /* Transfer vested tokens. Will revert if total > totalEscrowedAccountBalance */ if (total != 0) { _transferVestedTokens(msg.sender, total); } } /** * @notice Create an escrow entry to lock PERI for a given duration in seconds * @dev This call expects that the depositor (msg.sender) has already approved the Reward escrow contract to spend the the amount being escrowed. */ function createEscrowEntry( address beneficiary, uint256 deposit, uint256 duration ) external { require(beneficiary != address(0), "Cannot create escrow with address(0)"); /* Transfer PERI from msg.sender */ require(IERC20(address(periFinance())).transferFrom(msg.sender, address(this), deposit), "token transfer failed"); /* Append vesting entry for the beneficiary address */ _appendVestingEntry(beneficiary, deposit, duration); } /** * @notice Add a new vesting entry at a given time and quantity to an account's schedule. * @dev A call to this should accompany a previous successful call to periFinance.transfer(rewardEscrow, amount), * to ensure that when the funds are withdrawn, there is enough balance. * @param account The account to append a new vesting entry to. * @param quantity The quantity of PERI that will be escrowed. * @param duration The duration that PERI will be emitted. */ function appendVestingEntry( address account, uint256 quantity, uint256 duration ) external onlyFeePool { _appendVestingEntry(account, quantity, duration); } /* Transfer vested tokens and update totalEscrowedAccountBalance, totalVestedAccountBalance */ function _transferVestedTokens(address _account, uint256 _amount) internal { _reduceAccountEscrowBalances(_account, _amount); totalVestedAccountBalance[_account] = totalVestedAccountBalance[_account].add(_amount); IERC20(address(periFinance())).transfer(_account, _amount); emit Vested(_account, block.timestamp, _amount); } function _reduceAccountEscrowBalances(address _account, uint256 _amount) internal { // Reverts if amount being vested is greater than the account's existing totalEscrowedAccountBalance totalEscrowedBalance = totalEscrowedBalance.sub(_amount); totalEscrowedAccountBalance[_account] = totalEscrowedAccountBalance[_account].sub(_amount); } /* ========== ACCOUNT MERGING ========== */ function accountMergingIsOpen() public view returns (bool) { return accountMergingStartTime.add(accountMergingDuration) > block.timestamp; } function startMergingWindow() external onlyOwner { accountMergingStartTime = block.timestamp; emit AccountMergingStarted(accountMergingStartTime, accountMergingStartTime.add(accountMergingDuration)); } function setAccountMergingDuration(uint256 duration) external onlyOwner { require(duration <= maxAccountMergingDuration, "exceeds max merging duration"); accountMergingDuration = duration; emit AccountMergingDurationUpdated(duration); } function setMaxAccountMergingWindow(uint256 duration) external onlyOwner { maxAccountMergingDuration = duration; emit MaxAccountMergingDurationUpdated(duration); } function setMaxEscrowDuration(uint256 duration) external onlyOwner { max_duration = duration; emit MaxEscrowDurationUpdated(duration); } /* Nominate an account to merge escrow and vesting schedule */ function nominateAccountToMerge(address account) external { require(account != msg.sender, "Cannot nominate own account to merge"); require(accountMergingIsOpen(), "Account merging has ended"); require(issuer().debtBalanceOf(msg.sender, "pUSD") == 0, "Cannot merge accounts with debt"); nominatedReceiver[msg.sender] = account; emit NominateAccountToMerge(msg.sender, account); } function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external { require(accountMergingIsOpen(), "Account merging has ended"); require(issuer().debtBalanceOf(accountToMerge, "pUSD") == 0, "Cannot merge accounts with debt"); require(nominatedReceiver[accountToMerge] == msg.sender, "Address is not nominated to merge"); uint256 totalEscrowAmountMerged; for (uint i = 0; i < entryIDs.length; i++) { // retrieve entry VestingEntries.VestingEntry memory entry = vestingSchedules[accountToMerge][entryIDs[i]]; /* ignore vesting entries with zero escrowAmount */ if (entry.escrowAmount != 0) { /* copy entry to msg.sender (destination address) */ vestingSchedules[msg.sender][entryIDs[i]] = entry; /* Add the escrowAmount of entry to the totalEscrowAmountMerged */ totalEscrowAmountMerged = totalEscrowAmountMerged.add(entry.escrowAmount); /* append entryID to list of entries for account */ accountVestingEntryIDs[msg.sender].push(entryIDs[i]); /* Delete entry from accountToMerge */ delete vestingSchedules[accountToMerge][entryIDs[i]]; } } /* update totalEscrowedAccountBalance for merged account and accountToMerge */ totalEscrowedAccountBalance[accountToMerge] = totalEscrowedAccountBalance[accountToMerge].sub( totalEscrowAmountMerged ); totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].add(totalEscrowAmountMerged); emit AccountMerged(accountToMerge, msg.sender, totalEscrowAmountMerged, entryIDs, block.timestamp); } /* Internal function for importing vesting entry and creating new entry for escrow liquidations */ function _addVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal returns (uint) { uint entryID = nextEntryId; vestingSchedules[account][entryID] = entry; /* append entryID to list of entries for account */ accountVestingEntryIDs[account].push(entryID); /* Increment the next entry id. */ nextEntryId = nextEntryId.add(1); return entryID; } /* ========== MIGRATION OLD ESCROW ========== */ function migrateVestingSchedule(address) external { _notImplemented(); } function migrateAccountEscrowBalances( address[] calldata, uint256[] calldata, uint256[] calldata ) external { _notImplemented(); } /* ========== L2 MIGRATION ========== */ function burnForMigration(address, uint[] calldata) external returns (uint256, VestingEntries.VestingEntry[] memory) { _notImplemented(); } function importVestingEntries( address, uint256, VestingEntries.VestingEntry[] calldata ) external { _notImplemented(); } /* ========== INTERNALS ========== */ function _appendVestingEntry( address account, uint256 quantity, uint256 duration ) internal { /* No empty or already-passed vesting entries allowed. */ require(quantity != 0, "Quantity cannot be zero"); require(duration > 0 && duration <= max_duration, "Cannot escrow with 0 duration OR above max_duration"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalEscrowedBalance = totalEscrowedBalance.add(quantity); require( totalEscrowedBalance <= IERC20(address(periFinance())).balanceOf(address(this)), "Must be enough balance in the contract to provide for the vesting entry" ); /* Escrow the tokens for duration. */ uint endTime = block.timestamp + duration; /* Add quantity to account's escrowed balance */ totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity); uint entryID = nextEntryId; vestingSchedules[account][entryID] = VestingEntries.VestingEntry({endTime: uint64(endTime), escrowAmount: quantity}); accountVestingEntryIDs[account].push(entryID); /* Increment the next entry id. */ nextEntryId = nextEntryId.add(1); emit VestingEntryCreated(account, block.timestamp, quantity, duration, entryID); } /* ========== MODIFIERS ========== */ modifier onlyFeePool() { require(msg.sender == address(feePool()), "Only the FeePool can perform this action"); _; } /* ========== EVENTS ========== */ event Vested(address indexed beneficiary, uint time, uint value); event VestingEntryCreated(address indexed beneficiary, uint time, uint value, uint duration, uint entryID); event MaxEscrowDurationUpdated(uint newDuration); event MaxAccountMergingDurationUpdated(uint newDuration); event AccountMergingDurationUpdated(uint newDuration); event AccountMergingStarted(uint time, uint endTime); event AccountMerged( address indexed accountToMerge, address destinationAddress, uint escrowAmountMerged, uint[] entryIDs, uint time ); event NominateAccountToMerge(address indexed account, address destination); }
contract BaseRewardEscrowV2 is Owned, IRewardEscrowV2, LimitedSetup(8 weeks), MixinResolver { using SafeMath for uint; using SafeDecimalMath for uint; mapping(address => mapping(uint256 => VestingEntries.VestingEntry)) public vestingSchedules; mapping(address => uint256[]) public accountVestingEntryIDs; /*Counter for new vesting entry ids. */ uint256 public nextEntryId; /* An account's total escrowed periFinance balance to save recomputing this for fee extraction purposes. */ mapping(address => uint256) public totalEscrowedAccountBalance; /* An account's total vested reward periFinance. */ mapping(address => uint256) public totalVestedAccountBalance; /* Mapping of nominated address to recieve account merging */ mapping(address => address) public nominatedReceiver; /* The total remaining escrowed balance, for verifying the actual periFinance balance of this contract against. */ uint256 public totalEscrowedBalance; /* Max escrow duration */ uint public max_duration = 2 * 52 weeks; // Default max 2 years duration /* Max account merging duration */ uint public maxAccountMergingDuration = 4 weeks; // Default 4 weeks is max /* ========== ACCOUNT MERGING CONFIGURATION ========== */ uint public accountMergingDuration = 1 weeks; uint public accountMergingStartTime; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_PERIFINANCE = "PeriFinance"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver) { nextEntryId = 1; } /* ========== VIEWS ======================= */ function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function periFinance() internal view returns (IPeriFinance) { return IPeriFinance(requireAndGetAddress(CONTRACT_PERIFINANCE)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function _notImplemented() internal pure { revert("Cannot be run on this layer"); } /* ========== VIEW FUNCTIONS ========== */ // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](3); addresses[0] = CONTRACT_PERIFINANCE; addresses[1] = CONTRACT_FEEPOOL; addresses[2] = CONTRACT_ISSUER; } /** * @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalEscrowedAccountBalance[account]; } /** * @notice The number of vesting dates in an account's schedule. */ function numVestingEntries(address account) external view returns (uint) { return accountVestingEntryIDs[account].length; } /** * @notice Get a particular schedule entry for an account. * @return The vesting entry object and rate per second emission. */ function getVestingEntry(address account, uint256 entryID) external view returns (uint64 endTime, uint256 escrowAmount) { endTime = vestingSchedules[account][entryID].endTime; escrowAmount = vestingSchedules[account][entryID].escrowAmount; } function getVestingSchedules( address account, uint256 index, uint256 pageSize ) external view returns (VestingEntries.VestingEntryWithID[] memory) { uint256 endIndex = index + pageSize; // If index starts after the endIndex return no results if (endIndex <= index) { return new VestingEntries.VestingEntryWithID[](0); } // If the page extends past the end of the accountVestingEntryIDs, truncate it. if (endIndex > accountVestingEntryIDs[account].length) { endIndex = accountVestingEntryIDs[account].length; } uint256 n = endIndex - index; VestingEntries.VestingEntryWithID[] memory vestingEntries = new VestingEntries.VestingEntryWithID[](n); for (uint256 i; i < n; i++) { uint256 entryID = accountVestingEntryIDs[account][i + index]; VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID]; vestingEntries[i] = VestingEntries.VestingEntryWithID({ endTime: uint64(entry.endTime), escrowAmount: entry.escrowAmount, entryID: entryID }); } return vestingEntries; } function getAccountVestingEntryIDs( address account, uint256 index, uint256 pageSize ) external view returns (uint256[] memory) { uint256 endIndex = index + pageSize; // If the page extends past the end of the accountVestingEntryIDs, truncate it. if (endIndex > accountVestingEntryIDs[account].length) { endIndex = accountVestingEntryIDs[account].length; } if (endIndex <= index) { return new uint256[](0); } uint256 n = endIndex - index; uint256[] memory page = new uint256[](n); for (uint256 i; i < n; i++) { page[i] = accountVestingEntryIDs[account][i + index]; } return page; } function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint total) { for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryIDs[i]]; /* Skip entry if escrowAmount == 0 */ if (entry.escrowAmount != 0) { uint256 quantity = _claimableAmount(entry); /* add quantity to total */ total = total.add(quantity); } } } function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint) { VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID]; return _claimableAmount(entry); } function _claimableAmount(VestingEntries.VestingEntry memory _entry) internal view returns (uint256) { uint256 quantity; if (_entry.escrowAmount != 0) { /* Escrow amounts claimable if block.timestamp equal to or after entry endTime */ quantity = block.timestamp >= _entry.endTime ? _entry.escrowAmount : 0; } return quantity; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * Vest escrowed amounts that are claimable * Allows users to vest their vesting entries based on msg.sender */ function vest(uint256[] calldata entryIDs) external { uint256 total; for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[msg.sender][entryIDs[i]]; /* Skip entry if escrowAmount == 0 already vested */ if (entry.escrowAmount != 0) { uint256 quantity = _claimableAmount(entry); /* update entry to remove escrowAmount */ if (quantity > 0) { entry.escrowAmount = 0; } /* add quantity to total */ total = total.add(quantity); } } /* Transfer vested tokens. Will revert if total > totalEscrowedAccountBalance */ if (total != 0) { _transferVestedTokens(msg.sender, total); } } /** * @notice Create an escrow entry to lock PERI for a given duration in seconds * @dev This call expects that the depositor (msg.sender) has already approved the Reward escrow contract to spend the the amount being escrowed. */ function createEscrowEntry( address beneficiary, uint256 deposit, uint256 duration ) external { require(beneficiary != address(0), "Cannot create escrow with address(0)"); /* Transfer PERI from msg.sender */ require(IERC20(address(periFinance())).transferFrom(msg.sender, address(this), deposit), "token transfer failed"); /* Append vesting entry for the beneficiary address */ _appendVestingEntry(beneficiary, deposit, duration); } /** * @notice Add a new vesting entry at a given time and quantity to an account's schedule. * @dev A call to this should accompany a previous successful call to periFinance.transfer(rewardEscrow, amount), * to ensure that when the funds are withdrawn, there is enough balance. * @param account The account to append a new vesting entry to. * @param quantity The quantity of PERI that will be escrowed. * @param duration The duration that PERI will be emitted. */ function appendVestingEntry( address account, uint256 quantity, uint256 duration ) external onlyFeePool { _appendVestingEntry(account, quantity, duration); } /* Transfer vested tokens and update totalEscrowedAccountBalance, totalVestedAccountBalance */ function _transferVestedTokens(address _account, uint256 _amount) internal { _reduceAccountEscrowBalances(_account, _amount); totalVestedAccountBalance[_account] = totalVestedAccountBalance[_account].add(_amount); IERC20(address(periFinance())).transfer(_account, _amount); emit Vested(_account, block.timestamp, _amount); } function _reduceAccountEscrowBalances(address _account, uint256 _amount) internal { // Reverts if amount being vested is greater than the account's existing totalEscrowedAccountBalance totalEscrowedBalance = totalEscrowedBalance.sub(_amount); totalEscrowedAccountBalance[_account] = totalEscrowedAccountBalance[_account].sub(_amount); } /* ========== ACCOUNT MERGING ========== */ function accountMergingIsOpen() public view returns (bool) { return accountMergingStartTime.add(accountMergingDuration) > block.timestamp; } function startMergingWindow() external onlyOwner { accountMergingStartTime = block.timestamp; emit AccountMergingStarted(accountMergingStartTime, accountMergingStartTime.add(accountMergingDuration)); } function setAccountMergingDuration(uint256 duration) external onlyOwner { require(duration <= maxAccountMergingDuration, "exceeds max merging duration"); accountMergingDuration = duration; emit AccountMergingDurationUpdated(duration); } function setMaxAccountMergingWindow(uint256 duration) external onlyOwner { maxAccountMergingDuration = duration; emit MaxAccountMergingDurationUpdated(duration); } function setMaxEscrowDuration(uint256 duration) external onlyOwner { max_duration = duration; emit MaxEscrowDurationUpdated(duration); } /* Nominate an account to merge escrow and vesting schedule */ function nominateAccountToMerge(address account) external { require(account != msg.sender, "Cannot nominate own account to merge"); require(accountMergingIsOpen(), "Account merging has ended"); require(issuer().debtBalanceOf(msg.sender, "pUSD") == 0, "Cannot merge accounts with debt"); nominatedReceiver[msg.sender] = account; emit NominateAccountToMerge(msg.sender, account); } function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external { require(accountMergingIsOpen(), "Account merging has ended"); require(issuer().debtBalanceOf(accountToMerge, "pUSD") == 0, "Cannot merge accounts with debt"); require(nominatedReceiver[accountToMerge] == msg.sender, "Address is not nominated to merge"); uint256 totalEscrowAmountMerged; for (uint i = 0; i < entryIDs.length; i++) { // retrieve entry VestingEntries.VestingEntry memory entry = vestingSchedules[accountToMerge][entryIDs[i]]; /* ignore vesting entries with zero escrowAmount */ if (entry.escrowAmount != 0) { /* copy entry to msg.sender (destination address) */ vestingSchedules[msg.sender][entryIDs[i]] = entry; /* Add the escrowAmount of entry to the totalEscrowAmountMerged */ totalEscrowAmountMerged = totalEscrowAmountMerged.add(entry.escrowAmount); /* append entryID to list of entries for account */ accountVestingEntryIDs[msg.sender].push(entryIDs[i]); /* Delete entry from accountToMerge */ delete vestingSchedules[accountToMerge][entryIDs[i]]; } } /* update totalEscrowedAccountBalance for merged account and accountToMerge */ totalEscrowedAccountBalance[accountToMerge] = totalEscrowedAccountBalance[accountToMerge].sub( totalEscrowAmountMerged ); totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].add(totalEscrowAmountMerged); emit AccountMerged(accountToMerge, msg.sender, totalEscrowAmountMerged, entryIDs, block.timestamp); } /* Internal function for importing vesting entry and creating new entry for escrow liquidations */ function _addVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal returns (uint) { uint entryID = nextEntryId; vestingSchedules[account][entryID] = entry; /* append entryID to list of entries for account */ accountVestingEntryIDs[account].push(entryID); /* Increment the next entry id. */ nextEntryId = nextEntryId.add(1); return entryID; } /* ========== MIGRATION OLD ESCROW ========== */ function migrateVestingSchedule(address) external { _notImplemented(); } function migrateAccountEscrowBalances( address[] calldata, uint256[] calldata, uint256[] calldata ) external { _notImplemented(); } /* ========== L2 MIGRATION ========== */ function burnForMigration(address, uint[] calldata) external returns (uint256, VestingEntries.VestingEntry[] memory) { _notImplemented(); } function importVestingEntries( address, uint256, VestingEntries.VestingEntry[] calldata ) external { _notImplemented(); } /* ========== INTERNALS ========== */ function _appendVestingEntry( address account, uint256 quantity, uint256 duration ) internal { /* No empty or already-passed vesting entries allowed. */ require(quantity != 0, "Quantity cannot be zero"); require(duration > 0 && duration <= max_duration, "Cannot escrow with 0 duration OR above max_duration"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalEscrowedBalance = totalEscrowedBalance.add(quantity); require( totalEscrowedBalance <= IERC20(address(periFinance())).balanceOf(address(this)), "Must be enough balance in the contract to provide for the vesting entry" ); /* Escrow the tokens for duration. */ uint endTime = block.timestamp + duration; /* Add quantity to account's escrowed balance */ totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity); uint entryID = nextEntryId; vestingSchedules[account][entryID] = VestingEntries.VestingEntry({endTime: uint64(endTime), escrowAmount: quantity}); accountVestingEntryIDs[account].push(entryID); /* Increment the next entry id. */ nextEntryId = nextEntryId.add(1); emit VestingEntryCreated(account, block.timestamp, quantity, duration, entryID); } /* ========== MODIFIERS ========== */ modifier onlyFeePool() { require(msg.sender == address(feePool()), "Only the FeePool can perform this action"); _; } /* ========== EVENTS ========== */ event Vested(address indexed beneficiary, uint time, uint value); event VestingEntryCreated(address indexed beneficiary, uint time, uint value, uint duration, uint entryID); event MaxEscrowDurationUpdated(uint newDuration); event MaxAccountMergingDurationUpdated(uint newDuration); event AccountMergingDurationUpdated(uint newDuration); event AccountMergingStarted(uint time, uint endTime); event AccountMerged( address indexed accountToMerge, address destinationAddress, uint escrowAmountMerged, uint[] entryIDs, uint time ); event NominateAccountToMerge(address indexed account, address destination); }
40,557
19
// ------------------------------------------------------------------------ Transfer the balance from token owner's account to to account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
2,632
1
// Hash of the merkle root of the tallies in Witnet
uint256 tallyHashMerkleRoot;
uint256 tallyHashMerkleRoot;
15,517
267
// Checks if the collateral amount is increased after boost/_cdpId The Id of the CDP
modifier boostCheck(uint _cdpId) { bytes32 ilk = manager.ilks(_cdpId); address urn = manager.urns(_cdpId); (uint collateralBefore, ) = vat.urns(ilk, urn); _; (uint collateralAfter, ) = vat.urns(ilk, urn); require(collateralAfter > collateralBefore); }
modifier boostCheck(uint _cdpId) { bytes32 ilk = manager.ilks(_cdpId); address urn = manager.urns(_cdpId); (uint collateralBefore, ) = vat.urns(ilk, urn); _; (uint collateralAfter, ) = vat.urns(ilk, urn); require(collateralAfter > collateralBefore); }
53,328
31
// Calculate |x|.x quadruple precision numberreturn quadruple precision number /
function abs (bytes16 x) internal pure returns (bytes16) { return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; }
function abs (bytes16 x) internal pure returns (bytes16) { return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; }
40,303
4
// External contracts /
AbstractStarbaseCrowdsale public starbaseCrowdsale;
AbstractStarbaseCrowdsale public starbaseCrowdsale;
5,692
288
// An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory _symbol);
function symbol() external view returns (string memory _symbol);
3,735
18
// View Functions/
function quotePrice(uint256[] memory _dayIds) external view returns (uint256) { uint256 totalPrice = 0; for (uint256 i = 0; i < _dayIds.length; i++) { AdSpace memory ad = adSpaces[_dayIds[i]]; if (ad.adOwner != address(0)) { totalPrice += ad.resalePrice; } else { totalPrice += price; } } return totalPrice; }
function quotePrice(uint256[] memory _dayIds) external view returns (uint256) { uint256 totalPrice = 0; for (uint256 i = 0; i < _dayIds.length; i++) { AdSpace memory ad = adSpaces[_dayIds[i]]; if (ad.adOwner != address(0)) { totalPrice += ad.resalePrice; } else { totalPrice += price; } } return totalPrice; }
24,096
259
// Calldata version of {processProof} _Available since v4.7._ /
function processProofCalldata( bytes32[] calldata proof, bytes32 leaf ) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); }
function processProofCalldata( bytes32[] calldata proof, bytes32 leaf ) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); }
34,392
218
// Set vow in the clip
setContract(_clip, "vow", vow());
setContract(_clip, "vow", vow());
14,028
9
// improvements method to dump wins to enabled account (modifiers)
contract LotteryContract { uint private WinByFactor; uint private randNonce = 0; constructor(uint winByFactor) { WinByFactor = winByFactor; } receive() external payable { } function play(uint8 luckyNumber) public payable canAffordWin(msg.value) returns (string memory) { // receive the money in the contract payable(address(this)).transfer(msg.value); uint drawnNumber = PickUpRandomNumber(); if (drawnNumber == luckyNumber) { uint prizeAmount = CalculatePrizeAmount(msg.value); bool sent = payable(msg.sender).send(prizeAmount); if (sent) { return "You won motherfucker!"; } else { return "You won but something went wrong, sorry!"; } } return "You lost motherfucker!"; } function chargeLottery() public payable returns (string memory) { payable(address(this)).transfer(msg.value); return "Recharged!"; } modifier canAffordWin(uint userBet) { uint balance = address(this).balance; uint winningPrize = CalculatePrizeAmount(userBet); uint maxBetAmount = CalculateMaxBetAmount(); // "The bet amount is too large, you can bet at most " + maxBetAmount + " ether, in order to win " + winningPrize + " ether!" require(balance >= winningPrize, "The bet amount is too large"); _; } function CalculatePrizeAmount(uint userBet) private view returns (uint) { return userBet * WinByFactor; } function CalculateMaxBetAmount() private view returns (uint) { return address(this).balance / WinByFactor; } // check again https://www.sitepoint.com/solidity-pitfalls-random-number-generation-for-ethereum/#:~:text=Solidity%20is%20not%20capable%20of,more%20basic%20solutions%20are%20used. function PickUpRandomNumber() private view returns (uint) { return uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % 100; } }
contract LotteryContract { uint private WinByFactor; uint private randNonce = 0; constructor(uint winByFactor) { WinByFactor = winByFactor; } receive() external payable { } function play(uint8 luckyNumber) public payable canAffordWin(msg.value) returns (string memory) { // receive the money in the contract payable(address(this)).transfer(msg.value); uint drawnNumber = PickUpRandomNumber(); if (drawnNumber == luckyNumber) { uint prizeAmount = CalculatePrizeAmount(msg.value); bool sent = payable(msg.sender).send(prizeAmount); if (sent) { return "You won motherfucker!"; } else { return "You won but something went wrong, sorry!"; } } return "You lost motherfucker!"; } function chargeLottery() public payable returns (string memory) { payable(address(this)).transfer(msg.value); return "Recharged!"; } modifier canAffordWin(uint userBet) { uint balance = address(this).balance; uint winningPrize = CalculatePrizeAmount(userBet); uint maxBetAmount = CalculateMaxBetAmount(); // "The bet amount is too large, you can bet at most " + maxBetAmount + " ether, in order to win " + winningPrize + " ether!" require(balance >= winningPrize, "The bet amount is too large"); _; } function CalculatePrizeAmount(uint userBet) private view returns (uint) { return userBet * WinByFactor; } function CalculateMaxBetAmount() private view returns (uint) { return address(this).balance / WinByFactor; } // check again https://www.sitepoint.com/solidity-pitfalls-random-number-generation-for-ethereum/#:~:text=Solidity%20is%20not%20capable%20of,more%20basic%20solutions%20are%20used. function PickUpRandomNumber() private view returns (uint) { return uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % 100; } }
40,557
15
// ERC223 ERC223 contract interface with ERC20 functions and events Fully backward compatible with ERC20 /
contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
26,164
15
// Allows the current owner to relinquish control of the contract. Renouncing to ownership will leave the contract without an owner.It will not be possible to call the functions with the `onlyOwner`modifier anymore. /
function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
3,017
12
// Tells the bridged token address of a message sent to the AMB bridge.return address of a token contract. /
function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; }
function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; }
24,029
23
// Transfers a specific NFT (`tokenId`) from one account (`from`) to another (`to`). Requirements: - `from`, `to` cannot be zero. - `tokenId` must be owned by `from`. - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; }
* NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; }
10,088
26
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender._spender The address which will spend the funds._value The amount of tokens to be spent./
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); }
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); }
20,957
8
// Deposit staked tokens and collect reward tokens (if any) amount: amount to deposit (in stakedToken) account: future owner of deposit Internal function /
function _deposit(uint256 amount, address account) internal nonReentrant { require(block.number >= startBlock, "Pool is not active yet"); require(block.number < endBlock, "Pool has ended"); UserInfo storage user = userInfo[account]; if (userStakeLimit > 0) { require( amount + user.shares * stakePPS() <= userStakeLimit, "User amount above limit" ); } _updatePool(); uint256 PPS = stakePPS(); uint256 pending = 0; uint256 rewardsAmount = 0; if (user.shares > 0) { pending = (user.shares * accTokenPerShare) / PRECISION_FACTOR - user.rewardDebt; if (pending > 0) { rewardsAmount = _transferReward(account, pending); if (totalPendingReward >= pending) { totalPendingReward -= pending; } else { totalPendingReward = 0; } } } uint256 depositedAmount = 0; { uint256 initialBalance = stakeToken.balanceOf(address(this)); stakeToken.transferFrom(address(msg.sender), address(this), amount); uint256 subsequentBalance = stakeToken.balanceOf(address(this)); depositedAmount = subsequentBalance - initialBalance; } uint256 newShares = depositedAmount / PPS; require(newShares >= 100, "Below minimum amount"); user.shares = user.shares + newShares; stakeTotalShares += newShares; user.rewardDebt = (user.shares * accTokenPerShare) / PRECISION_FACTOR; user.depositBlock = block.number; emit Deposit(account, depositedAmount, newShares, rewardsAmount); }
function _deposit(uint256 amount, address account) internal nonReentrant { require(block.number >= startBlock, "Pool is not active yet"); require(block.number < endBlock, "Pool has ended"); UserInfo storage user = userInfo[account]; if (userStakeLimit > 0) { require( amount + user.shares * stakePPS() <= userStakeLimit, "User amount above limit" ); } _updatePool(); uint256 PPS = stakePPS(); uint256 pending = 0; uint256 rewardsAmount = 0; if (user.shares > 0) { pending = (user.shares * accTokenPerShare) / PRECISION_FACTOR - user.rewardDebt; if (pending > 0) { rewardsAmount = _transferReward(account, pending); if (totalPendingReward >= pending) { totalPendingReward -= pending; } else { totalPendingReward = 0; } } } uint256 depositedAmount = 0; { uint256 initialBalance = stakeToken.balanceOf(address(this)); stakeToken.transferFrom(address(msg.sender), address(this), amount); uint256 subsequentBalance = stakeToken.balanceOf(address(this)); depositedAmount = subsequentBalance - initialBalance; } uint256 newShares = depositedAmount / PPS; require(newShares >= 100, "Below minimum amount"); user.shares = user.shares + newShares; stakeTotalShares += newShares; user.rewardDebt = (user.shares * accTokenPerShare) / PRECISION_FACTOR; user.depositBlock = block.number; emit Deposit(account, depositedAmount, newShares, rewardsAmount); }
1,342
3
// Get the token ID to mint for the user On a fresh mint, the exact token ID minted is determined on tx executionwith sudo randomness using the block number
uint256 tokenId = _mergeTokenId( tierIndex, uint128(block.number % tierTokenCount[tierIndex]) ); _mint(owner, tokenId, uint256(amount), "");
uint256 tokenId = _mergeTokenId( tierIndex, uint128(block.number % tierTokenCount[tierIndex]) ); _mint(owner, tokenId, uint256(amount), "");
1,615
288
// get the locked balances from the store
(uint256[] memory amounts, uint256[] memory expirationTimes) = _store.lockedBalanceRange(msg.sender, startIndex, endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length);
(uint256[] memory amounts, uint256[] memory expirationTimes) = _store.lockedBalanceRange(msg.sender, startIndex, endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length);
33,941
222
// File: contracts/dao/Setters.sol//
contract Setters is State, Getters { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); /** * ERC20 Interface */ function transfer(address recipient, uint256 amount) external returns (bool) { return false; } function approve(address spender, uint256 amount) external returns (bool) { return false; } function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { return false; } /** * Global */ function incrementTotalBonded(uint256 amount) internal { _state.balance.bonded = _state.balance.bonded.add(amount); } function decrementTotalBonded(uint256 amount, string memory reason) internal { _state.balance.bonded = _state.balance.bonded.sub(amount, reason); } function incrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.add(amount); } function decrementTotalDebt(uint256 amount, string memory reason) internal { _state.balance.debt = _state.balance.debt.sub(amount, reason); } function setDebtToZero() internal { _state.balance.debt = 0; } function incrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.add(amount); } function decrementTotalRedeemable(uint256 amount, string memory reason) internal { _state.balance.redeemable = _state.balance.redeemable.sub(amount, reason); } function setEra(Era.Status era, uint256 start) internal { _state8.era.status = era; _state8.era.start = start; } /** * Account */ function incrementBalanceOf(address account, uint256 amount) internal { _state.accounts[account].balance = _state.accounts[account].balance.add(amount); _state.balance.supply = _state.balance.supply.add(amount); emit Transfer(address(0), account, amount); } function decrementBalanceOf(address account, uint256 amount, string memory reason) internal { _state.accounts[account].balance = _state.accounts[account].balance.sub(amount, reason); _state.balance.supply = _state.balance.supply.sub(amount, reason); emit Transfer(account, address(0), amount); } function incrementBalanceOfStaged(address account, uint256 amount) internal { _state.accounts[account].staged = _state.accounts[account].staged.add(amount); _state.balance.staged = _state.balance.staged.add(amount); } function decrementBalanceOfStaged(address account, uint256 amount, string memory reason) internal { _state.accounts[account].staged = _state.accounts[account].staged.sub(amount, reason); _state.balance.staged = _state.balance.staged.sub(amount, reason); } function incrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount, uint256 expiration) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].add(amount); //Adds coupons to user's balance _state.balance.coupons = _state.balance.coupons.add(amount); //increments total outstanding coupons _state3.couponExpirationsByAccount[account][epoch] = expiration; //sets the expiration epoch for the user's coupons _state3.expiringCouponsByEpoch[expiration] = _state3.expiringCouponsByEpoch[expiration].add(amount); //Increments the number of expiring coupons in epoch } function decrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount, string memory reason) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].sub(amount, reason); uint256 expiration = _state3.couponExpirationsByAccount[account][epoch]; _state3.expiringCouponsByEpoch[expiration] = _state3.expiringCouponsByEpoch[expiration].sub(amount, reason); _state.balance.coupons = _state.balance.coupons.sub(amount, reason); } function unfreeze(address account) internal { _state.accounts[account].fluidUntil = epoch().add(Constants.getDAOExitLockupEpochs()); } function updateAllowanceCoupons(address owner, address spender, uint256 amount) internal { _state.accounts[owner].couponAllowances[spender] = amount; } function decrementAllowanceCoupons(address owner, address spender, uint256 amount, string memory reason) internal { _state.accounts[owner].couponAllowances[spender] = _state.accounts[owner].couponAllowances[spender].sub(amount, reason); } /** * Epoch */ function setDAIAdvanceIncentive(uint256 value) internal { _state.epoch.daiAdvanceIncentive = value; } function shouldDistributeDAI(bool should) internal { _state.epoch.shouldDistributeDAI = should; } function setBootstrappingPeriod(uint256 epochs) internal { _state.epoch.bootstrapping = epochs; } function initializeEpochs() internal { _state.epoch.currentStart = block.timestamp; _state.epoch.currentPeriod = Constants.getEpochStrategy().offset; } function incrementEpoch() internal { _state.epoch.current = _state.epoch.current.add(1); _state.epoch.currentStart = _state.epoch.currentStart.add(_state.epoch.currentPeriod); } function storePrice(uint256 epoch, Decimal.D256 memory price) internal { _state6.twapPerEpoch[epoch] = price; } function adjustPeriod(Decimal.D256 memory price) internal { Decimal.D256 memory normalizedPrice; if (price.greaterThan(Decimal.one())) normalizedPrice = Decimal.one().div(price); else normalizedPrice = price; Constants.EpochStrategy memory epochStrategy = Constants.getEpochStrategy(); _state.epoch.currentPeriod = normalizedPrice .mul(epochStrategy.maxPeriod.sub(epochStrategy.minPeriod)) .add(epochStrategy.minPeriod) .asUint256(); } function snapshotTotalBonded() internal { _state.epochs[epoch()].bonded = totalSupply(); } function expireCoupons(uint256 epoch) internal { _state.balance.coupons = _state.balance.coupons.sub( _state3.expiringCouponsByEpoch[epoch]); _state3.expiringCouponsByEpoch[epoch] = 0; } /** * FixedSwap */ function incrementContributions(uint256 amount) internal { _state.bootstrapping.contributions = _state.bootstrapping.contributions.add(amount); } function decrementContributions(uint256 amount) internal { _state.bootstrapping.contributions = _state.bootstrapping.contributions.sub(amount); } /** * Governance */ function createCandidate(address candidate, uint256 period) internal { _state.candidates[candidate].start = epoch(); _state.candidates[candidate].period = period; } function recordVote(address account, address candidate, Candidate.Vote vote) internal { _state.candidates[candidate].votes[account] = vote; } function incrementApproveFor(address candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.add(amount); } function decrementApproveFor(address candidate, uint256 amount, string memory reason) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.sub(amount, reason); } function incrementRejectFor(address candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.add(amount); } function decrementRejectFor(address candidate, uint256 amount, string memory reason) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.sub(amount, reason); } function placeLock(address account, address candidate) internal { uint256 currentLock = _state.accounts[account].lockedUntil; uint256 newLock = startFor(candidate).add(periodFor(candidate)); if (newLock > currentLock) { _state.accounts[account].lockedUntil = newLock; } } function initialized(address candidate) internal { _state.candidates[candidate].initialized = true; } }
contract Setters is State, Getters { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); /** * ERC20 Interface */ function transfer(address recipient, uint256 amount) external returns (bool) { return false; } function approve(address spender, uint256 amount) external returns (bool) { return false; } function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { return false; } /** * Global */ function incrementTotalBonded(uint256 amount) internal { _state.balance.bonded = _state.balance.bonded.add(amount); } function decrementTotalBonded(uint256 amount, string memory reason) internal { _state.balance.bonded = _state.balance.bonded.sub(amount, reason); } function incrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.add(amount); } function decrementTotalDebt(uint256 amount, string memory reason) internal { _state.balance.debt = _state.balance.debt.sub(amount, reason); } function setDebtToZero() internal { _state.balance.debt = 0; } function incrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.add(amount); } function decrementTotalRedeemable(uint256 amount, string memory reason) internal { _state.balance.redeemable = _state.balance.redeemable.sub(amount, reason); } function setEra(Era.Status era, uint256 start) internal { _state8.era.status = era; _state8.era.start = start; } /** * Account */ function incrementBalanceOf(address account, uint256 amount) internal { _state.accounts[account].balance = _state.accounts[account].balance.add(amount); _state.balance.supply = _state.balance.supply.add(amount); emit Transfer(address(0), account, amount); } function decrementBalanceOf(address account, uint256 amount, string memory reason) internal { _state.accounts[account].balance = _state.accounts[account].balance.sub(amount, reason); _state.balance.supply = _state.balance.supply.sub(amount, reason); emit Transfer(account, address(0), amount); } function incrementBalanceOfStaged(address account, uint256 amount) internal { _state.accounts[account].staged = _state.accounts[account].staged.add(amount); _state.balance.staged = _state.balance.staged.add(amount); } function decrementBalanceOfStaged(address account, uint256 amount, string memory reason) internal { _state.accounts[account].staged = _state.accounts[account].staged.sub(amount, reason); _state.balance.staged = _state.balance.staged.sub(amount, reason); } function incrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount, uint256 expiration) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].add(amount); //Adds coupons to user's balance _state.balance.coupons = _state.balance.coupons.add(amount); //increments total outstanding coupons _state3.couponExpirationsByAccount[account][epoch] = expiration; //sets the expiration epoch for the user's coupons _state3.expiringCouponsByEpoch[expiration] = _state3.expiringCouponsByEpoch[expiration].add(amount); //Increments the number of expiring coupons in epoch } function decrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount, string memory reason) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].sub(amount, reason); uint256 expiration = _state3.couponExpirationsByAccount[account][epoch]; _state3.expiringCouponsByEpoch[expiration] = _state3.expiringCouponsByEpoch[expiration].sub(amount, reason); _state.balance.coupons = _state.balance.coupons.sub(amount, reason); } function unfreeze(address account) internal { _state.accounts[account].fluidUntil = epoch().add(Constants.getDAOExitLockupEpochs()); } function updateAllowanceCoupons(address owner, address spender, uint256 amount) internal { _state.accounts[owner].couponAllowances[spender] = amount; } function decrementAllowanceCoupons(address owner, address spender, uint256 amount, string memory reason) internal { _state.accounts[owner].couponAllowances[spender] = _state.accounts[owner].couponAllowances[spender].sub(amount, reason); } /** * Epoch */ function setDAIAdvanceIncentive(uint256 value) internal { _state.epoch.daiAdvanceIncentive = value; } function shouldDistributeDAI(bool should) internal { _state.epoch.shouldDistributeDAI = should; } function setBootstrappingPeriod(uint256 epochs) internal { _state.epoch.bootstrapping = epochs; } function initializeEpochs() internal { _state.epoch.currentStart = block.timestamp; _state.epoch.currentPeriod = Constants.getEpochStrategy().offset; } function incrementEpoch() internal { _state.epoch.current = _state.epoch.current.add(1); _state.epoch.currentStart = _state.epoch.currentStart.add(_state.epoch.currentPeriod); } function storePrice(uint256 epoch, Decimal.D256 memory price) internal { _state6.twapPerEpoch[epoch] = price; } function adjustPeriod(Decimal.D256 memory price) internal { Decimal.D256 memory normalizedPrice; if (price.greaterThan(Decimal.one())) normalizedPrice = Decimal.one().div(price); else normalizedPrice = price; Constants.EpochStrategy memory epochStrategy = Constants.getEpochStrategy(); _state.epoch.currentPeriod = normalizedPrice .mul(epochStrategy.maxPeriod.sub(epochStrategy.minPeriod)) .add(epochStrategy.minPeriod) .asUint256(); } function snapshotTotalBonded() internal { _state.epochs[epoch()].bonded = totalSupply(); } function expireCoupons(uint256 epoch) internal { _state.balance.coupons = _state.balance.coupons.sub( _state3.expiringCouponsByEpoch[epoch]); _state3.expiringCouponsByEpoch[epoch] = 0; } /** * FixedSwap */ function incrementContributions(uint256 amount) internal { _state.bootstrapping.contributions = _state.bootstrapping.contributions.add(amount); } function decrementContributions(uint256 amount) internal { _state.bootstrapping.contributions = _state.bootstrapping.contributions.sub(amount); } /** * Governance */ function createCandidate(address candidate, uint256 period) internal { _state.candidates[candidate].start = epoch(); _state.candidates[candidate].period = period; } function recordVote(address account, address candidate, Candidate.Vote vote) internal { _state.candidates[candidate].votes[account] = vote; } function incrementApproveFor(address candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.add(amount); } function decrementApproveFor(address candidate, uint256 amount, string memory reason) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.sub(amount, reason); } function incrementRejectFor(address candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.add(amount); } function decrementRejectFor(address candidate, uint256 amount, string memory reason) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.sub(amount, reason); } function placeLock(address account, address candidate) internal { uint256 currentLock = _state.accounts[account].lockedUntil; uint256 newLock = startFor(candidate).add(periodFor(candidate)); if (newLock > currentLock) { _state.accounts[account].lockedUntil = newLock; } } function initialized(address candidate) internal { _state.candidates[candidate].initialized = true; } }
11,859
124
// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch;
uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch;
11,965
9
// See which address owns which tokens
function tokensOfOwner(address addr) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(addr); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(addr, i); } return tokensId; }
function tokensOfOwner(address addr) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(addr); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(addr, i); } return tokensId; }
22,541
122
// Obtain the stake balance of this contract/ return wei balace of contract
function totalStakeTokenBalance() public view returns (uint256) { // Return BEO20 balance return stakeToken.balanceOf(address(this)); }
function totalStakeTokenBalance() public view returns (uint256) { // Return BEO20 balance return stakeToken.balanceOf(address(this)); }
35,136
22
// CG: transfer funds
bool couldTransfer = liquidityToken.transferFrom(msg.sender, address(this), _amount); require(couldTransfer, "ABQILO/could-not-transfer");
bool couldTransfer = liquidityToken.transferFrom(msg.sender, address(this), _amount); require(couldTransfer, "ABQILO/could-not-transfer");
7,741
237
// push tokens into the local collection
destination.push32(uint32(_tokenId), uint32(n));
destination.push32(uint32(_tokenId), uint32(n));
24,838
173
// Safe nova transfer function, just in case if rounding error causes pool to not have enough NOVAs.
function safeNovaTransfer(address _to, uint256 _amount) internal { uint256 novaBal = nova.balanceOf(address(this)); if (_amount > novaBal) { nova.transfer(_to, novaBal); } else { nova.transfer(_to, _amount); } }
function safeNovaTransfer(address _to, uint256 _amount) internal { uint256 novaBal = nova.balanceOf(address(this)); if (_amount > novaBal) { nova.transfer(_to, novaBal); } else { nova.transfer(_to, _amount); } }
49,819
36
// Sets the maximum queue length the operator can set/_newMaxQueueLengthSeconds New maximum queue length
function setMaxOperatorQueueLengthSeconds(uint256 _newMaxQueueLengthSeconds) external { _requireSenderIsTimelock(); emit SetMaxOperatorQueueLengthSeconds({ oldMaxQueueLengthSecs: maxOperatorQueueLengthSeconds, newMaxQueueLengthSecs: _newMaxQueueLengthSeconds }); maxOperatorQueueLengthSeconds = _newMaxQueueLengthSeconds; }
function setMaxOperatorQueueLengthSeconds(uint256 _newMaxQueueLengthSeconds) external { _requireSenderIsTimelock(); emit SetMaxOperatorQueueLengthSeconds({ oldMaxQueueLengthSecs: maxOperatorQueueLengthSeconds, newMaxQueueLengthSecs: _newMaxQueueLengthSeconds }); maxOperatorQueueLengthSeconds = _newMaxQueueLengthSeconds; }
33,898
64
// Adds another token to the accepted coins for printingCalling conditions: - Address of the contract to be added- Only can be added by founding fathers/
{ require( hasRole(FOUNDING_FATHER, msg.sender), "Caller is not a Founding Father" ); _acceptedStableCoins[_contract] = true; _contract_address_to_oracle[_contract] = _oracleAddress; return _acceptedStableCoins[_contract]; }
{ require( hasRole(FOUNDING_FATHER, msg.sender), "Caller is not a Founding Father" ); _acceptedStableCoins[_contract] = true; _contract_address_to_oracle[_contract] = _oracleAddress; return _acceptedStableCoins[_contract]; }
17,492
254
// Repay debt
uint256 maxRepay = want.balanceOf(address(this)); if (_debtOutstanding > maxRepay) {
uint256 maxRepay = want.balanceOf(address(this)); if (_debtOutstanding > maxRepay) {
11,092
54
// Deprecate the subgraph and do cleanup
subgraphData.disabled = true; subgraphData.vSignal = 0; subgraphData.reserveRatioDeprecated = 0;
subgraphData.disabled = true; subgraphData.vSignal = 0; subgraphData.reserveRatioDeprecated = 0;
20,055
103
// This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. implement alternative mechanisms to perform token transfer, such as signature-based. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `tokenId` token must exist and be owned by `from`. - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event./
function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); }
function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); }
35,124
57
// CG: We require that the DAI contract indicate a successful transfer.
require(couldTransfer, "ABQDAO/could-not-trasfer");
require(couldTransfer, "ABQDAO/could-not-trasfer");
54,733
71
// Changes YEL token reward per second. Use this function to moderate the `lockup amount`. Essentially this function changes the amount of the reward which is entitled to the user for his token staking by the time the `endTime` is passed. Good practice to update pools without messing up the contract
function setYelPerSecond(uint256 _yelPerSecond, bool _withUpdate) external onlyOwner { if (_withUpdate) { massUpdatePools(); } yelPerSecond = _yelPerSecond; }
function setYelPerSecond(uint256 _yelPerSecond, bool _withUpdate) external onlyOwner { if (_withUpdate) { massUpdatePools(); } yelPerSecond = _yelPerSecond; }
72,050
3
// Thrown when minting when an allowance proof is invalid.
error InvalidProof();
error InvalidProof();
14,429
9
// Handles the arithmetic operations of calculating the minting cap.NOTE: If an account has the maximum available minting cap, then this functionhas no effect on it. operator Address that used its minting cap by calling minting tokens amount Amount of the minted tokens /
function _spendMintCap(address operator, uint256 amount) internal virtual { uint256 currentMintCap = mintCap(operator); if (currentMintCap != type(uint256).max) { if (currentMintCap < amount) revert InsufficientMintCapError(); unchecked { _setMintCap(operator, currentMintCap - amount); } } }
function _spendMintCap(address operator, uint256 amount) internal virtual { uint256 currentMintCap = mintCap(operator); if (currentMintCap != type(uint256).max) { if (currentMintCap < amount) revert InsufficientMintCapError(); unchecked { _setMintCap(operator, currentMintCap - amount); } } }
14,582
24
// check user
require(IsWhitelist(msg.sender, pid, stakeAmount), "invalid user");
require(IsWhitelist(msg.sender, pid, stakeAmount), "invalid user");
51,160
94
// checkLockedAddress this is a callback for additional contracts to check whether a specified address should be blocked from performing an action in this block/
function checkLockedAddress(address addressToCheck) view public returns(bool){ return addressLocks[addressToCheck] == block.timestamp; }
function checkLockedAddress(address addressToCheck) view public returns(bool){ return addressLocks[addressToCheck] == block.timestamp; }
40,195
3
// Set Pre Reveal URL
function setPreRevealUri(string memory url) external onlyOwner { _hiddenURI = url; }
function setPreRevealUri(string memory url) external onlyOwner { _hiddenURI = url; }
25,541
2
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) { require(denominator > 0, '0 denom'); assembly { result := div(prod0, denominator) }
if (prod1 == 0) { require(denominator > 0, '0 denom'); assembly { result := div(prod0, denominator) }
14,276
1
// Details of the symbol that get registered with the polymath platform
struct SymbolDetails { address owner; uint256 timestamp; string tokenName; bytes32 swarmHash; bool status; }
struct SymbolDetails { address owner; uint256 timestamp; string tokenName; bytes32 swarmHash; bool status; }
43,354
1
// Mapping of address => reserve
mapping(address => Reserve) internal reserves;
mapping(address => Reserve) internal reserves;
36,914
12
// Soldity somehow doesn't evaluate this compile timerole which has rights to change permissions and set new policy in contract, keccak256("AccessController")
bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da;
bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da;
41,896
34
// Maximum number of TTC to pre ico sell // Maximum number of TTC to main ico sell // Minimum amount to invest // Crowdsale period // Number of TTC per Ether // Variables// TTC contract reference //Maximum Ether for one address during pre ico or main ico // Multisig contract that will receive the Ether during pre ico// Number of Ether received during pre ico // Number of TTC sent to Ether contributors during pre ico // Multisig contract that will receive the Ether during main ico// Number of Ether received during main ico // Number of TTC sent to
modifier respectTimeFrame() { require((now >= PRE_START_TIME) && (now < PRE_END_TIME ) || (now >= MAIN_START_TIME) && (now < MAIN_END_TIME )); _; }
modifier respectTimeFrame() { require((now >= PRE_START_TIME) && (now < PRE_END_TIME ) || (now >= MAIN_START_TIME) && (now < MAIN_END_TIME )); _; }
38,064
176
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
mapping(uint256 => address) private _owners;
895
92
// Returns the price data for the given base/quote pair. Revert if not available.
function getReferenceData(string memory _base, string memory _quote) external view returns (ReferenceData memory);
function getReferenceData(string memory _base, string memory _quote) external view returns (ReferenceData memory);
7,686
10
// Save proposal data
targets = targets_; values = values_; signatures = signatures_; calldatas = calldatas_; description = description_;
targets = targets_; values = values_; signatures = signatures_; calldatas = calldatas_; description = description_;
29,246
109
// entry point for updating multiple pricesfunction to set prices for a variable number of assets.assets a list of up to assets for which to set a price. required: 0 < assets.length == requestedPriceMantissas.lengthrequestedPriceMantissas requested new prices for the assets, scaled by 1018. required: 0 < assets.length == requestedPriceMantissas.length return uint values in same order as inputs. For each: 0=success, otherwise a failure (see enum OracleError for details)/
function setPrices(address[] assets, uint[] requestedPriceMantissas) public returns (uint[] memory) { uint numAssets = assets.length; uint numPrices = requestedPriceMantissas.length; uint[] memory result; // Fail when msg.sender is not poster if (msg.sender != poster) { result = new uint[](1); result[0] = failOracle(0, OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PRICE_PERMISSION_CHECK); return result; } if ((numAssets == 0) || (numPrices != numAssets)) { result = new uint[](1); result[0] = failOracle(0, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICES_PARAM_VALIDATION); return result; } result = new uint[](numAssets); for (uint i = 0; i < numAssets; i++) { result[i] = setPriceInternal(assets[i], requestedPriceMantissas[i]); } return result; }
function setPrices(address[] assets, uint[] requestedPriceMantissas) public returns (uint[] memory) { uint numAssets = assets.length; uint numPrices = requestedPriceMantissas.length; uint[] memory result; // Fail when msg.sender is not poster if (msg.sender != poster) { result = new uint[](1); result[0] = failOracle(0, OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PRICE_PERMISSION_CHECK); return result; } if ((numAssets == 0) || (numPrices != numAssets)) { result = new uint[](1); result[0] = failOracle(0, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICES_PARAM_VALIDATION); return result; } result = new uint[](numAssets); for (uint i = 0; i < numAssets; i++) { result[i] = setPriceInternal(assets[i], requestedPriceMantissas[i]); } return result; }
12,186
158
// Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _add_max_liquidity_uniswap(address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); }
function _add_max_liquidity_uniswap(address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); }
25,093
302
// NOTE: we don't use any safe math here for efficiency reasons. The assert above is already a pretty good guarantee that nothing goes wrong. Also, all numbers involved are very well smaller than uint256 in the first place.
uint256 _elapsedTotal = _now - lastWithdrawal; uint256 _proRatedYears = _elapsedTotal / SECONDS_PER_MONTH / 12; uint256 _elapsedInYear = _elapsedTotal % MAX_FINITE_LOCK_DURATION_SECONDS;
uint256 _elapsedTotal = _now - lastWithdrawal; uint256 _proRatedYears = _elapsedTotal / SECONDS_PER_MONTH / 12; uint256 _elapsedInYear = _elapsedTotal % MAX_FINITE_LOCK_DURATION_SECONDS;
5,281
99
// Checks if the paramMapping value indicated that we need to inject values/_type Indicated the type of the input
function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; }
function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; }
24,563
25
// orderEpoch
bytes4 constant public ORDER_EPOCH_SELECTOR = 0xd9bfa73e; bytes4 constant public ORDER_EPOCH_SELECTOR_GENERATOR = bytes4(keccak256("orderEpoch(address,address)"));
bytes4 constant public ORDER_EPOCH_SELECTOR = 0xd9bfa73e; bytes4 constant public ORDER_EPOCH_SELECTOR_GENERATOR = bytes4(keccak256("orderEpoch(address,address)"));
41,984
494
// emit Transfer(msg.sender, _to, _value, _data);
if (isContract(_to)) { contractFallback(_to, _value, _data); }
if (isContract(_to)) { contractFallback(_to, _value, _data); }
11,426
239
// Sanity check that no inputs overflow how many bits we've allocated to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice),
require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice),
22,113
174
// data object for a user stake on a pool
struct PoolStakerUser { // saved / withdrawn rewards of user uint256 totalSavedRewards; // total purchased allocation uint256 totalPurchasedAllocation; // native address, if necessary string nativeAddress; // date/time when user has claimed the reward uint256 claimedTime; }
struct PoolStakerUser { // saved / withdrawn rewards of user uint256 totalSavedRewards; // total purchased allocation uint256 totalPurchasedAllocation; // native address, if necessary string nativeAddress; // date/time when user has claimed the reward uint256 claimedTime; }
30,981
183
// Check the borrow succeeded
require( controller.borrowVerify(address(this), _borrower, _delegatee, _amount, _feeAmount, address(_newLoan)), Errors.FAIL_BORROW );
require( controller.borrowVerify(address(this), _borrower, _delegatee, _amount, _feeAmount, address(_newLoan)), Errors.FAIL_BORROW );
75,001
46
// Decode a `CBOR.Value` structure into a native `string` value. _cborValue An instance of `CBOR.Value`.return The value represented by the input, as a `string` value. /
function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } }
function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } }
27,303
67
// Emitted when a new Owner is set.
event NewOwner(address prevOwner, address newOwner);
event NewOwner(address prevOwner, address newOwner);
16,180
3
// mapping(account => tradingNonce)
mapping(address => uint256) _accountTradingNonces;
mapping(address => uint256) _accountTradingNonces;
17,213
72
// since bucket.tail == bucket.haed == cursor case is handled at the above, we only have to handle bucket.tail == cursor != bucket.head
checkPoints[bucket].tail = info.prev;
checkPoints[bucket].tail = info.prev;
31,340
48
// ============ Internal Only Function ============ //PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokensTransfer function which includes only unlocked tokensLocked tokens can always be transfered back to the returns addressTransferring to owner allows re-issuance of funds through registry_from The address to send tokens from _to The address that will receive the tokens _value The amount of tokens to be transferred /
function _transfer( address _from, address _to, uint256 _value
function _transfer( address _from, address _to, uint256 _value
31,903
28
// 1 token1 a day
rewardRate1 = (uint256(365e18)).div(365 * 86400);
rewardRate1 = (uint256(365e18)).div(365 * 86400);
33,614
2
// Community mapping to handle reputation minted or burnt per reactionuint: community IDuint: reactionIDint: amount to mint or burn (if negative) /
mapping(uint => mapping(uint => int)) public communityReactionSettings;
mapping(uint => mapping(uint => int)) public communityReactionSettings;
18,562
37
// message unnecessarily. For custom revert reasons use {tryMod}. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. /
function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; }
function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; }
9,521