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
283
// Create & add new snapshot
uint256 prevRPS = getLatestSnapshot().rewardPerShare; uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(totalSupply)); BoardSnapshot memory newSnapshot = BoardSnapshot({ number: block.number, time: block.timestamp, rewardReceived: amount, rewardPerShare: nextRPS });
uint256 prevRPS = getLatestSnapshot().rewardPerShare; uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(totalSupply)); BoardSnapshot memory newSnapshot = BoardSnapshot({ number: block.number, time: block.timestamp, rewardReceived: amount, rewardPerShare: nextRPS });
22,115
117
// - The Maastricht contract inherits from the FixedRateWrapper andis used to issue and burn legacy synthetic franc tokens _token - The synthetic token to which the franc is pegged (jEUR) /
constructor(IERC20 _token) FixedRateWrapper(_token, 6559570 * 1e12, 'Jarvis Synthetic Franc', 'jFRF')
constructor(IERC20 _token) FixedRateWrapper(_token, 6559570 * 1e12, 'Jarvis Synthetic Franc', 'jFRF')
27,831
17
// set `baseURI` /
function setBaseURI(string calldata uri) external onlyOwner { baseURI = uri; emit BaseURI(uri); }
function setBaseURI(string calldata uri) external onlyOwner { baseURI = uri; emit BaseURI(uri); }
36,897
121
// Remove plugin and calls onRemove to cleanup
function removePlugin(address _address) public onlyOwner
function removePlugin(address _address) public onlyOwner
64,410
36
// Withdrawal LRC.
function withdrawLRC() payable { require(depositStartTime > 0); require(lrcDeposited > 0); var record = records[msg.sender]; require(now >= record.timestamp + WITHDRAWAL_DELAY); require(record.lrcAmount > 0); uint lrcWithdrawalBase = record.lrcAmount; if (msg.value > 0) { lrcWithdrawalBase = lrcWithdrawalBase .min256(msg.value.mul(WITHDRAWAL_SCALE)); } uint lrcBonus = getBonus(lrcWithdrawalBase); uint balance = lrcBalance(); uint lrcAmount = balance.min256(lrcWithdrawalBase + lrcBonus); lrcDeposited -= lrcWithdrawalBase; record.lrcAmount -= lrcWithdrawalBase; if (record.lrcAmount == 0) { delete records[msg.sender]; } else { records[msg.sender] = record; } Withdrawal(withdrawId++, msg.sender, lrcAmount); require(Token(lrcTokenAddress).transfer(msg.sender, lrcAmount)); }
function withdrawLRC() payable { require(depositStartTime > 0); require(lrcDeposited > 0); var record = records[msg.sender]; require(now >= record.timestamp + WITHDRAWAL_DELAY); require(record.lrcAmount > 0); uint lrcWithdrawalBase = record.lrcAmount; if (msg.value > 0) { lrcWithdrawalBase = lrcWithdrawalBase .min256(msg.value.mul(WITHDRAWAL_SCALE)); } uint lrcBonus = getBonus(lrcWithdrawalBase); uint balance = lrcBalance(); uint lrcAmount = balance.min256(lrcWithdrawalBase + lrcBonus); lrcDeposited -= lrcWithdrawalBase; record.lrcAmount -= lrcWithdrawalBase; if (record.lrcAmount == 0) { delete records[msg.sender]; } else { records[msg.sender] = record; } Withdrawal(withdrawId++, msg.sender, lrcAmount); require(Token(lrcTokenAddress).transfer(msg.sender, lrcAmount)); }
25,632
6
// for coin
mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol;
mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol;
21,597
272
// The bounding curve, to enable Early adapters to buy cheap, and make money for charity
function calculatePrice() public view returns (uint256) { require(hasSaleStarted == true, "Sale hasn't started"); require(totalSupply() < MAX_FantasyCity, "Sale has already ended"); //50000000000000000 return 50000000000000000; //0.05 eth }
function calculatePrice() public view returns (uint256) { require(hasSaleStarted == true, "Sale hasn't started"); require(totalSupply() < MAX_FantasyCity, "Sale has already ended"); //50000000000000000 return 50000000000000000; //0.05 eth }
9,568
26
// we calculate daily basis stake amount
function _calculateStake(address _token, address _whom) internal view returns (uint256) { uint256 _lastRound = lastStakeClaimed[_token][_whom]; uint256 totalStakeDays = safeDiv(safeSub(now, _lastRound), 86400); uint256 userTokenBalance = stakeBalance[_token][_whom]; uint256 tokenPercentage = annualMintPercentage[_token]; if (totalStakeDays > 0) { uint256 stakeAmount = safeDiv(safeMul(safeMul(userTokenBalance, tokenPercentage), totalStakeDays), 3650000); return stakeAmount; } return 0; }
function _calculateStake(address _token, address _whom) internal view returns (uint256) { uint256 _lastRound = lastStakeClaimed[_token][_whom]; uint256 totalStakeDays = safeDiv(safeSub(now, _lastRound), 86400); uint256 userTokenBalance = stakeBalance[_token][_whom]; uint256 tokenPercentage = annualMintPercentage[_token]; if (totalStakeDays > 0) { uint256 stakeAmount = safeDiv(safeMul(safeMul(userTokenBalance, tokenPercentage), totalStakeDays), 3650000); return stakeAmount; } return 0; }
19,117
18
// ProductTx /
struct ProductTx { string _txId; string _id; uint256 _depositedAmt; uint256 _receivableAmt; uint256 _feeAmt; uint256 _paymentMode; uint256 _pledgedFeePercent; uint256 _pledgedFeeDivisor; address payable _ownerAddress; }
struct ProductTx { string _txId; string _id; uint256 _depositedAmt; uint256 _receivableAmt; uint256 _feeAmt; uint256 _paymentMode; uint256 _pledgedFeePercent; uint256 _pledgedFeeDivisor; address payable _ownerAddress; }
35,179
6
// Returns the cap on the token's total supply. /
function cap() public view virtual returns (uint256) { return CAP; }
function cap() public view virtual returns (uint256) { return CAP; }
18,122
18
// Returns the vesting schedule information for a given holder and index.return the vesting schedule structure information /
function getVestingScheduleByAddressAndIndex(address holder, uint256 index) external view returns (VestingSchedule memory)
function getVestingScheduleByAddressAndIndex(address holder, uint256 index) external view returns (VestingSchedule memory)
69,852
122
// Get investor lock infoaccount The address want to know the investor lock state. return investor lock info/
function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); }
function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); }
74,086
29
// Check if it's time to swap for liquidity & reward pool
uint256 tokensAvailableForSwap = balanceOf(address(this)); if (tokensAvailableForSwap >= _tokenSwapThreshold) {
uint256 tokensAvailableForSwap = balanceOf(address(this)); if (tokensAvailableForSwap >= _tokenSwapThreshold) {
24,447
20
// operator must have still been active after (or until) the block number either there is a later update, past the specified blockNumber, or they are still active
&& ( operatorStake.nextUpdateBlockNumber >= searchData.metadata.referenceBlockNumber || operatorStake.nextUpdateBlockNumber == 0 ), "DataLayrChallengeBase.freezeOperatorsForLowDegreeChallenge: operator was not active during blockNumber specified by dataStoreId / headerHash" ); if (signatoryRecord.nonSignerPubkeyHashes.length != 0) {
&& ( operatorStake.nextUpdateBlockNumber >= searchData.metadata.referenceBlockNumber || operatorStake.nextUpdateBlockNumber == 0 ), "DataLayrChallengeBase.freezeOperatorsForLowDegreeChallenge: operator was not active during blockNumber specified by dataStoreId / headerHash" ); if (signatoryRecord.nonSignerPubkeyHashes.length != 0) {
38,732
45
// Encode a string of at most 31 chars into a `ShortString`. This will trigger a `StringTooLong` error is the input string is too long. /
function toShortString(string memory str) internal pure returns (ShortString) { bytes memory bstr = bytes(str); if (bstr.length > 31) { revert StringTooLong(str); } return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); }
function toShortString(string memory str) internal pure returns (ShortString) { bytes memory bstr = bytes(str); if (bstr.length > 31) { revert StringTooLong(str); } return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); }
2,970
66
// Emitted when participation factor changed participationFactor New participation factor /
event ParticipationFactorChanged(uint256 participationFactor);
event ParticipationFactorChanged(uint256 participationFactor);
15,582
42
// need to update the vault state with the old value before the rate is changed
_updatePoolState(vaultAddresses.at(i));
_updatePoolState(vaultAddresses.at(i));
43,658
3
// Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner./ Can only be invoked by the current `owner`./newOwner Address of the new owner./direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`./renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
function transferOwnership( address newOwner, bool direct, bool renounce
function transferOwnership( address newOwner, bool direct, bool renounce
4,981
78
// Returns if the auction is currently running. Use endTime() to check when it ends. Start time will always be less than timestamp, as it resets to 0. Start time is only updated for auction progress tracking, not critical functionality.returnboolIf the auction is running. /
function auctionRunning() public view returns (bool) { return endTime > block.timestamp && address(this) == ERC721.ownerOf(ERIC_ORB_ID); }
function auctionRunning() public view returns (bool) { return endTime > block.timestamp && address(this) == ERC721.ownerOf(ERIC_ORB_ID); }
39,307
33
// TRAIT STRUCTS /
struct Material { MaterialId id; string name; string[2] vals; uint256 supply; }
struct Material { MaterialId id; string name; string[2] vals; uint256 supply; }
5,877
13
// Send the winner the remaining balance on the contract.
contributors[winner_index].send(this.balance);
contributors[winner_index].send(this.balance);
231
39
// Withdraw the initial deposit of the specified lender for the specified roundId transfer the initial amount deposited to the lender emits Withdraw event lender, address of the lender roundId, Id of the round amount, amount to withdraw /
function _withdraw( address lender, uint roundId, uint amount
function _withdraw( address lender, uint roundId, uint amount
17,549
193
// emit ApprovalCheck(from, to, tokenId);
return true;
return true;
2,100
62
// Update the fee incurred /
function updateFee(uint256 r,uint256 amt) internal{ uint256 temp = SafeMath.mul(r,1); uint256 reward = SafeMath.div(temp,100); uint256 a = SafeMath.mul(amt,reward); uint256 b = SafeMath.div(a,10**8); fee_collected = SafeMath.add(fee_collected,b); }
function updateFee(uint256 r,uint256 amt) internal{ uint256 temp = SafeMath.mul(r,1); uint256 reward = SafeMath.div(temp,100); uint256 a = SafeMath.mul(amt,reward); uint256 b = SafeMath.div(a,10**8); fee_collected = SafeMath.add(fee_collected,b); }
1,807
3
// Simplified function to sweep all funds
function sweepFunds(address tokenAddress) external { IERC20 token = IERC20(tokenAddress); require(token.transfer(msg.sender, token.balanceOf(address(this))), "Transfer failed"); }
function sweepFunds(address tokenAddress) external { IERC20 token = IERC20(tokenAddress); require(token.transfer(msg.sender, token.balanceOf(address(this))), "Transfer failed"); }
43,085
110
// Emitted when drips from a user's account to a receiver are updated./ Funds are being dripped on every second between the event block's timestamp (inclusively)/ and`endTime` (exclusively) or until the timestamp of the next drips update (exclusively)./user The user/account The dripping account/receiver The receiver of the updated drips/amtPerSec The new amount per second dripped from the user's account/ to the receiver or 0 if the drips are stopped/endTime The timestamp when dripping will stop,/ always larger than the block timestamp or equal to it if the drips are stopped
event Dripping( address indexed user, uint256 indexed account, address indexed receiver, uint128 amtPerSec, uint64 endTime );
event Dripping( address indexed user, uint256 indexed account, address indexed receiver, uint128 amtPerSec, uint64 endTime );
38,947
0
// Compute fee amount. fee Fee value in basis points. Value of 100 is 1% fee. loanAmount Amount of an asset used as a loan credit.return feeAmount Amount of a loan asset that represents a protocol fee.return newLoanAmount New amount of a loan credit asset, after deducting protocol fee. /
function calculateFeeAmount(uint16 fee, uint256 loanAmount) internal pure returns (uint256 feeAmount, uint256 newLoanAmount) { if (fee == 0) return (0, loanAmount); unchecked { if ((loanAmount * fee) / fee == loanAmount) feeAmount = loanAmount * uint256(fee) / 1e4; else feeAmount = loanAmount / 1e4 * uint256(fee); } newLoanAmount = loanAmount - feeAmount; }
function calculateFeeAmount(uint16 fee, uint256 loanAmount) internal pure returns (uint256 feeAmount, uint256 newLoanAmount) { if (fee == 0) return (0, loanAmount); unchecked { if ((loanAmount * fee) / fee == loanAmount) feeAmount = loanAmount * uint256(fee) / 1e4; else feeAmount = loanAmount / 1e4 * uint256(fee); } newLoanAmount = loanAmount - feeAmount; }
12,657
116
// Include an address in the fees
function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; }
function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; }
48,499
32
// Grants pool shares by minting a given amount of the underwriter/ tokens for the recipient address. In result, the recipient/ obtains part of the pool ownership without depositing any/ collateral tokens. Shares are usually granted for notifiers/ reporting about various contract state changes./Can be called only by the contract owner./recipient Address of the underwriter tokens recipient/covAmount Amount of the underwriter tokens which should be minted
function grantShares(address recipient, uint256 covAmount) external onlyOwner
function grantShares(address recipient, uint256 covAmount) external onlyOwner
7,375
84
// Fee dist
uint256 feeamountToPool = feeamount.mul(_feeToDistribute).div(10000); uint256 remamountToPool = feeamount.sub(feeamountToPool).mul(_gonsPerFragment); _balances[_feescollector] = _balances[_feescollector].add(remamountToPool); emit Transfer(sender, _feescollector, remamountToPool); uint256 finalFeeAmount = feeamountToPool.mul(_gonsPerFragment); _balances[_emptyWallet] = _balances[_emptyWallet].add(finalFeeAmount); emit Transfer(sender, _emptyWallet, finalFeeAmount);
uint256 feeamountToPool = feeamount.mul(_feeToDistribute).div(10000); uint256 remamountToPool = feeamount.sub(feeamountToPool).mul(_gonsPerFragment); _balances[_feescollector] = _balances[_feescollector].add(remamountToPool); emit Transfer(sender, _feescollector, remamountToPool); uint256 finalFeeAmount = feeamountToPool.mul(_gonsPerFragment); _balances[_emptyWallet] = _balances[_emptyWallet].add(finalFeeAmount); emit Transfer(sender, _emptyWallet, finalFeeAmount);
13,675
104
// See {ILife-withdrawBidForBio}. /
function withdrawBidForBio(uint256 bioId) external override saleEnded bioExist(bioId) nonReentrant { Bid memory existingBid = _bioWithBids[bioId]; require(existingBid.bidder == msg.sender, "This address doesn't have active bid");
function withdrawBidForBio(uint256 bioId) external override saleEnded bioExist(bioId) nonReentrant { Bid memory existingBid = _bioWithBids[bioId]; require(existingBid.bidder == msg.sender, "This address doesn't have active bid");
76,686
135
//
function protectedTokens() internal virtual view returns (address[] memory);
function protectedTokens() internal virtual view returns (address[] memory);
1,897
2
// OFT `estimateSendFee` parameters structure dstChainId The destination chain identifier toAddress Can be any size depending on the `dstChainId` amount The quantity of tokens in wei useZro The ZRO token payment flag adapterParams LayerZero adapter parameters /
struct EstimateSendFeeParams { uint16 dstChainId; bytes32 toAddress; uint256 amount; bool useZro; bytes adapterParams; }
struct EstimateSendFeeParams { uint16 dstChainId; bytes32 toAddress; uint256 amount; bool useZro; bytes adapterParams; }
23,071
205
// Get array index and isFound flag
uint256 index; bool isFound; (index, isFound) = getIndex(_erc20Address, erc20List);
uint256 index; bool isFound; (index, isFound) = getIndex(_erc20Address, erc20List);
4,427
59
// have not saved enough to pay debt, mint more
uint256 _seigniorage = gameSupply.mul(_percentage).div(1e18); _savedForTheoretics = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForTheoretics); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); }
uint256 _seigniorage = gameSupply.mul(_percentage).div(1e18); _savedForTheoretics = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForTheoretics); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); }
27,701
14
// The number of function selectors in selectorSlots
uint16 selectorCount;
uint16 selectorCount;
18,329
78
// Modifies a function to run only when the contract is paused.
modifier isPaused() { require(paused, "contract is not paused"); _; }
modifier isPaused() { require(paused, "contract is not paused"); _; }
42,169
172
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use D in case we have multiple minters on the pool token.
amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]);
amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]);
20,407
9
// uint256 deadlineAcc = mLiquidation.getLiquidationDeadlineForAccount(account);
require(_deadlinePassed(deadlineAcc), "not ppp"); mSNX.liquidateDelinquentAccount(account, amount);
require(_deadlinePassed(deadlineAcc), "not ppp"); mSNX.liquidateDelinquentAccount(account, amount);
7,806
233
// Collect reward tokens from all strategies and swap for supported stablecoin via Uniswap /
function harvest() external onlyGovernorOrStrategist { for (uint256 i = 0; i < allStrategies.length; i++) { _harvest(allStrategies[i]); } }
function harvest() external onlyGovernorOrStrategist { for (uint256 i = 0; i < allStrategies.length; i++) { _harvest(allStrategies[i]); } }
46,359
42
// CelerLedger interface any changes in this interface must be synchronized to corresponding libraries events in this interface must be exactly same in corresponding used libraries /
interface ICelerLedger { /********** LedgerOperation related functions and events **********/ function openChannel(bytes calldata _openChannelRequest) external payable; function deposit(bytes32 _channelId, address _receiver, uint _transferFromAmount) external payable; function depositInBatch( bytes32[] calldata _channelIds, address[] calldata _receivers, uint[] calldata _transferFromAmounts ) external; function snapshotStates(bytes calldata _signedSimplexStateArray) external; function intendWithdraw(bytes32 _channelId, uint _amount, bytes32 _recipientChannelId) external; function confirmWithdraw(bytes32 _channelId) external; function vetoWithdraw(bytes32 _channelId) external; function cooperativeWithdraw(bytes calldata _cooperativeWithdrawRequest) external; function intendSettle(bytes calldata _signedSimplexStateArray) external; function clearPays(bytes32 _channelId, address _peerFrom, bytes calldata _payIdList) external; function confirmSettle(bytes32 _channelId) external; function cooperativeSettle(bytes calldata _settleRequest) external; function getChannelStatusNum(uint _channelStatus) external view returns(uint); function getEthPool() external view returns(address); function getPayRegistry() external view returns(address); function getCelerWallet() external view returns(address); event OpenChannel( bytes32 indexed channelId, uint tokenType, address indexed tokenAddress, // TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed address[2] peerAddrs, uint[2] initialDeposits ); // TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed event Deposit(bytes32 indexed channelId, address[2] peerAddrs, uint[2] deposits, uint[2] withdrawals); event SnapshotStates(bytes32 indexed channelId, uint[2] seqNums); event IntendSettle(bytes32 indexed channelId, uint[2] seqNums); event ClearOnePay(bytes32 indexed channelId, bytes32 indexed payId, address indexed peerFrom, uint amount); event ConfirmSettle(bytes32 indexed channelId, uint[2] settleBalance); event ConfirmSettleFail(bytes32 indexed channelId); event IntendWithdraw(bytes32 indexed channelId, address indexed receiver, uint amount); event ConfirmWithdraw( bytes32 indexed channelId, uint withdrawnAmount, address indexed receiver, bytes32 indexed recipientChannelId, uint[2] deposits, uint[2] withdrawals ); event VetoWithdraw(bytes32 indexed channelId); event CooperativeWithdraw( bytes32 indexed channelId, uint withdrawnAmount, address indexed receiver, bytes32 indexed recipientChannelId, uint[2] deposits, uint[2] withdrawals, uint seqNum ); event CooperativeSettle(bytes32 indexed channelId, uint[2] settleBalance); /********** End of LedgerOperation related functions and events **********/ /********** LedgerChannel related functions and events **********/ function getSettleFinalizedTime(bytes32 _channelId) external view returns(uint); function getTokenContract(bytes32 _channelId) external view returns(address); function getTokenType(bytes32 _channelId) external view returns(PbEntity.TokenType); function getChannelStatus(bytes32 _channelId) external view returns(LedgerStruct.ChannelStatus); function getCooperativeWithdrawSeqNum(bytes32 _channelId) external view returns(uint); function getTotalBalance(bytes32 _channelId) external view returns(uint); function getBalanceMap(bytes32 _channelId) external view returns(address[2] memory, uint[2] memory, uint[2] memory); function getChannelMigrationArgs(bytes32 _channelId) external view returns(uint, uint, address, uint); function getPeersMigrationInfo(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory, uint[2] memory, uint[2] memory, uint[2] memory, uint[2] memory ); function getDisputeTimeout(bytes32 _channelId) external view returns(uint); function getMigratedTo(bytes32 _channelId) external view returns(address); function getStateSeqNumMap(bytes32 _channelId) external view returns(address[2] memory, uint[2] memory); function getTransferOutMap(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory ); function getNextPayIdListHashMap(bytes32 _channelId) external view returns( address[2] memory, bytes32[2] memory ); function getLastPayResolveDeadlineMap(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory ); function getPendingPayOutMap(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory ); function getWithdrawIntent(bytes32 _channelId) external view returns(address, uint, uint, bytes32); /********** End of LedgerChannel related functions and events **********/ /********** LedgerBalanceLimit related functions and events **********/ function setBalanceLimits(address[] calldata _tokenAddrs, uint[] calldata _limits) external; function disableBalanceLimits() external; function enableBalanceLimits() external; function getBalanceLimit(address _tokenAddr) external view returns(uint); function getBalanceLimitsEnabled() external view returns(bool); /********** End of LedgerBalanceLimit related functions and events **********/ /********** LedgerMigrate related functions and events **********/ function migrateChannelTo(bytes calldata _migrationRequest) external returns(bytes32); function migrateChannelFrom(address _fromLedgerAddr, bytes calldata _migrationRequest) external; event MigrateChannelTo(bytes32 indexed channelId, address indexed newLedgerAddr); event MigrateChannelFrom(bytes32 indexed channelId, address indexed oldLedgerAddr); /********** End of LedgerMigrate related functions and events **********/ }
interface ICelerLedger { /********** LedgerOperation related functions and events **********/ function openChannel(bytes calldata _openChannelRequest) external payable; function deposit(bytes32 _channelId, address _receiver, uint _transferFromAmount) external payable; function depositInBatch( bytes32[] calldata _channelIds, address[] calldata _receivers, uint[] calldata _transferFromAmounts ) external; function snapshotStates(bytes calldata _signedSimplexStateArray) external; function intendWithdraw(bytes32 _channelId, uint _amount, bytes32 _recipientChannelId) external; function confirmWithdraw(bytes32 _channelId) external; function vetoWithdraw(bytes32 _channelId) external; function cooperativeWithdraw(bytes calldata _cooperativeWithdrawRequest) external; function intendSettle(bytes calldata _signedSimplexStateArray) external; function clearPays(bytes32 _channelId, address _peerFrom, bytes calldata _payIdList) external; function confirmSettle(bytes32 _channelId) external; function cooperativeSettle(bytes calldata _settleRequest) external; function getChannelStatusNum(uint _channelStatus) external view returns(uint); function getEthPool() external view returns(address); function getPayRegistry() external view returns(address); function getCelerWallet() external view returns(address); event OpenChannel( bytes32 indexed channelId, uint tokenType, address indexed tokenAddress, // TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed address[2] peerAddrs, uint[2] initialDeposits ); // TODO: there is an issue of setting address[2] as indexed. Need to fix and make this indexed event Deposit(bytes32 indexed channelId, address[2] peerAddrs, uint[2] deposits, uint[2] withdrawals); event SnapshotStates(bytes32 indexed channelId, uint[2] seqNums); event IntendSettle(bytes32 indexed channelId, uint[2] seqNums); event ClearOnePay(bytes32 indexed channelId, bytes32 indexed payId, address indexed peerFrom, uint amount); event ConfirmSettle(bytes32 indexed channelId, uint[2] settleBalance); event ConfirmSettleFail(bytes32 indexed channelId); event IntendWithdraw(bytes32 indexed channelId, address indexed receiver, uint amount); event ConfirmWithdraw( bytes32 indexed channelId, uint withdrawnAmount, address indexed receiver, bytes32 indexed recipientChannelId, uint[2] deposits, uint[2] withdrawals ); event VetoWithdraw(bytes32 indexed channelId); event CooperativeWithdraw( bytes32 indexed channelId, uint withdrawnAmount, address indexed receiver, bytes32 indexed recipientChannelId, uint[2] deposits, uint[2] withdrawals, uint seqNum ); event CooperativeSettle(bytes32 indexed channelId, uint[2] settleBalance); /********** End of LedgerOperation related functions and events **********/ /********** LedgerChannel related functions and events **********/ function getSettleFinalizedTime(bytes32 _channelId) external view returns(uint); function getTokenContract(bytes32 _channelId) external view returns(address); function getTokenType(bytes32 _channelId) external view returns(PbEntity.TokenType); function getChannelStatus(bytes32 _channelId) external view returns(LedgerStruct.ChannelStatus); function getCooperativeWithdrawSeqNum(bytes32 _channelId) external view returns(uint); function getTotalBalance(bytes32 _channelId) external view returns(uint); function getBalanceMap(bytes32 _channelId) external view returns(address[2] memory, uint[2] memory, uint[2] memory); function getChannelMigrationArgs(bytes32 _channelId) external view returns(uint, uint, address, uint); function getPeersMigrationInfo(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory, uint[2] memory, uint[2] memory, uint[2] memory, uint[2] memory ); function getDisputeTimeout(bytes32 _channelId) external view returns(uint); function getMigratedTo(bytes32 _channelId) external view returns(address); function getStateSeqNumMap(bytes32 _channelId) external view returns(address[2] memory, uint[2] memory); function getTransferOutMap(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory ); function getNextPayIdListHashMap(bytes32 _channelId) external view returns( address[2] memory, bytes32[2] memory ); function getLastPayResolveDeadlineMap(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory ); function getPendingPayOutMap(bytes32 _channelId) external view returns( address[2] memory, uint[2] memory ); function getWithdrawIntent(bytes32 _channelId) external view returns(address, uint, uint, bytes32); /********** End of LedgerChannel related functions and events **********/ /********** LedgerBalanceLimit related functions and events **********/ function setBalanceLimits(address[] calldata _tokenAddrs, uint[] calldata _limits) external; function disableBalanceLimits() external; function enableBalanceLimits() external; function getBalanceLimit(address _tokenAddr) external view returns(uint); function getBalanceLimitsEnabled() external view returns(bool); /********** End of LedgerBalanceLimit related functions and events **********/ /********** LedgerMigrate related functions and events **********/ function migrateChannelTo(bytes calldata _migrationRequest) external returns(bytes32); function migrateChannelFrom(address _fromLedgerAddr, bytes calldata _migrationRequest) external; event MigrateChannelTo(bytes32 indexed channelId, address indexed newLedgerAddr); event MigrateChannelFrom(bytes32 indexed channelId, address indexed oldLedgerAddr); /********** End of LedgerMigrate related functions and events **********/ }
43,344
5
// Exchange rate/amount = Ether / return value
function conversion(uint256 amount) public pure returns (uint256) { return amount * 10**9; }
function conversion(uint256 amount) public pure returns (uint256) { return amount * 10**9; }
28,310
18
// ------------------------------------------------------------------------Get the token balance for account `tokenOwner`------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
27,045
109
// Buffer too small
require(to.length >= minLength); // Should be a better way?
require(to.length >= minLength); // Should be a better way?
16,961
39
// Логируем событие с курсом / датой /
emit FullEventLog(msg.sender, "buy", _sellprice, _sellprice.mul(100).div(90), now, _value, msg.value); _sellprice = _money.mul(10**15).mul(98).div(_tokens).div(100); emit Transfer(address(this), msg.sender, _value);
emit FullEventLog(msg.sender, "buy", _sellprice, _sellprice.mul(100).div(90), now, _value, msg.value); _sellprice = _money.mul(10**15).mul(98).div(_tokens).div(100); emit Transfer(address(this), msg.sender, _value);
12,247
43
// The ```getAmountIn``` function calculates how many buyTokens you would need in order to obtain a given number of sellTokens/Maintains compatability with some router implementations/amountOut The amount out of sell tokens/tokenOut The sell token address/ return _amountIn The amount of buyToken needed
function getAmountIn(uint256 amountOut, address tokenOut) external view returns (uint256 _amountIn) { if (tokenOut != SELL_TOKEN) revert InvalidTokenOut(); (_amountIn, , ) = getAmountIn({ _desiredOut: amountOut }); }
function getAmountIn(uint256 amountOut, address tokenOut) external view returns (uint256 _amountIn) { if (tokenOut != SELL_TOKEN) revert InvalidTokenOut(); (_amountIn, , ) = getAmountIn({ _desiredOut: amountOut }); }
15,176
17
// retrieval /
function getInterval(Tree storage tree, uint intervalID) constant internal returns (uint begin, uint end, bytes32 data)
function getInterval(Tree storage tree, uint intervalID) constant internal returns (uint begin, uint end, bytes32 data)
44,358
33
// Rewards
uint256 public rewardDistributionStart; uint256 public rewardDistributedUnits = 0;
uint256 public rewardDistributionStart; uint256 public rewardDistributedUnits = 0;
35,625
30
// Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`./pid The index of the pool. See `poolInfo`./amount LP token amount to withdraw./to Receiver of the LP tokens and BASTION rewards.
function withdrawAndHarvest( uint256 pid, uint256 amount, address to
function withdrawAndHarvest( uint256 pid, uint256 amount, address to
13,563
28
// store the reduction in the doners respective array as a negative value preserving a history of reductions. The sum of this array is their respective donation
campaigns[_campaignID].doners[msg.sender].push(-int(_value)); uint licenses = computeLicenses(_value, campaigns[_campaignID].presalePrice); if (licenses * campaigns[_campaignID].presalePrice <= _value){ if (licenses < fetchCampaignLicenses(_campaignID, msg.sender)) { campaigns[_campaignID].licenses[msg.sender] -= (licenses + 1); } else {
campaigns[_campaignID].doners[msg.sender].push(-int(_value)); uint licenses = computeLicenses(_value, campaigns[_campaignID].presalePrice); if (licenses * campaigns[_campaignID].presalePrice <= _value){ if (licenses < fetchCampaignLicenses(_campaignID, msg.sender)) { campaigns[_campaignID].licenses[msg.sender] -= (licenses + 1); } else {
48,807
42
// Internal function to clear current approval of a given token ID_tokenId uint256 ID of the token to be transferred/
function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; emit Approval(_owner, 0, _tokenId); }
function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; emit Approval(_owner, 0, _tokenId); }
50,183
113
// Allows Schains contract to delete a group of schains /
function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); }
function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); }
83,490
59
// See {ERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
49,048
29
// Allows a Lock manager to add or remove an event hook /
function setEventHooks(
function setEventHooks(
76,437
316
// mint a single token to each address passed in through calldata_addresses Array of addresses to send a single token to
function mintReserveToAddresses(address[] calldata _addresses) external onlyOwner whenNotPaused { uint256 _quantity = _addresses.length; require(_quantity + _owners.length <= maxSupply(),"Purchase exceeds available supply."); for (uint256 i = 0; i < _quantity; i++) { _safeMint(_addresses[i]); } }
function mintReserveToAddresses(address[] calldata _addresses) external onlyOwner whenNotPaused { uint256 _quantity = _addresses.length; require(_quantity + _owners.length <= maxSupply(),"Purchase exceeds available supply."); for (uint256 i = 0; i < _quantity; i++) { _safeMint(_addresses[i]); } }
16,706
48
// Returns type of contract this PolicyBook covers, access: ANY/ return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns (
function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns (
14,467
25
// Determine the current account liquidity wrt collateral requirementsreturn ( possible error code ( semi-opaque ), account shortfall below collateral requirements ) /
function getAccountLiquidity ( address account ) external view returns ( uint256, uint256, uint256 );
function getAccountLiquidity ( address account ) external view returns ( uint256, uint256, uint256 );
5,408
1
// Because elapsed can be represented as a 31 bit unsigned integer, and the received values can be represented as 22 bit signed integers, we don't need to perform checked arithmetic.
int256 elapsed = int256(currentTimestamp - timestamp(sample)); int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed; int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed; int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed; return pack( instLogPairPrice, accLogPairPrice,
int256 elapsed = int256(currentTimestamp - timestamp(sample)); int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed; int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed; int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed; return pack( instLogPairPrice, accLogPairPrice,
4,379
89
// Utility Interface for central Spool implementation
interface ISpool is ISpoolExternal, ISpoolReallocation, ISpoolDoHardWork, ISpoolStrategy, ISpoolBase {} // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path }
interface ISpool is ISpoolExternal, ISpoolReallocation, ISpoolDoHardWork, ISpoolStrategy, ISpoolBase {} // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path }
50,501
20
// Update the reserve snapshot.
reservesSnapshot[cToken] = ReservesSnapshot({ timestamp: getBlockTimestamp(), totalReserves: totalReserves });
reservesSnapshot[cToken] = ReservesSnapshot({ timestamp: getBlockTimestamp(), totalReserves: totalReserves });
27,872
64
// There are two caveats with this computation: 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is stored internally as an int256 ~10^59. 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.42e-18 = 2.8e-18, which would round to 3, but this computation produces the result 2. No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
8,943
5
// Adds two numbers, reverts on overflow./
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
13,134
367
// Do the trade, taking only the maxHeldTokenToBuy if more is returned
uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData )
uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData )
35,222
5
// Withdraws surplus.Callable only by the contract owner.Withdrawing realized surplus is prioritised, unrealized surplus is minted onlyif realized surplus is not enough to cover the requested amount. _surplus surplus amount to withdraw/mint. /
function withdraw(address _to, uint256 _surplus) external onlyOwner { uint256 realized = IERC20(token).balanceOf(address(this)); if (_surplus > realized) { uint256 unrealized = _surplus - realized; require(unrealized <= surplus, "SurplusMinter: exceeds surplus"); unchecked { surplus -= unrealized; } IERC20(token).transfer(_to, realized); IMintableERC20(token).mint(_to, unrealized); emit WithdrawSurplus(_to, realized, unrealized); } else { IERC20(token).transfer(_to, _surplus); emit WithdrawSurplus(_to, _surplus, 0); } }
function withdraw(address _to, uint256 _surplus) external onlyOwner { uint256 realized = IERC20(token).balanceOf(address(this)); if (_surplus > realized) { uint256 unrealized = _surplus - realized; require(unrealized <= surplus, "SurplusMinter: exceeds surplus"); unchecked { surplus -= unrealized; } IERC20(token).transfer(_to, realized); IMintableERC20(token).mint(_to, unrealized); emit WithdrawSurplus(_to, realized, unrealized); } else { IERC20(token).transfer(_to, _surplus); emit WithdrawSurplus(_to, _surplus, 0); } }
18,272
180
// Gets address of randomizer at index `_index` in history of allrandomizers used by this core contract. Index is zero-based. _index Historical index of randomizer to be queried.return randomizerAddress Address of randomizer at index `_index`. If a randomizer is switched away from and then switched back to, itwill show up in the history twice. /
function getHistoricalRandomizerAt(uint256 _index) external view returns (address)
function getHistoricalRandomizerAt(uint256 _index) external view returns (address)
4,245
3
// Allow upgrade agent functionality to kick in only if the crowdsale was a success. /
function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); }
function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); }
17,838
36
// removes all market data about a marketed pack, can only be called by market controller _packId position to be deleted _limit limit of categories to cleanup /
function purgePack(uint256 _packId, uint256 _limit)
function purgePack(uint256 _packId, uint256 _limit)
79,883
57
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = ISakeSwapFactory(factory).feeTo(); feeOn = feeTo != address(0); uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = Math.sqrt(uint256(_reserve0).mul(_reserve1)); uint256 rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } }
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = ISakeSwapFactory(factory).feeTo(); feeOn = feeTo != address(0); uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = Math.sqrt(uint256(_reserve0).mul(_reserve1)); uint256 rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } }
22,426
449
// SafeERC should revert on this call if there's a problem
order.output.token.safeTransfer(order.trader, diff); console.log("Transfer to trader complete"); return (true, "");
order.output.token.safeTransfer(order.trader, diff); console.log("Transfer to trader complete"); return (true, "");
51,852
197
// Set up the user's new dharma key and emit a corresponding event.
_setUserSigningKey(newUserSigningKey);
_setUserSigningKey(newUserSigningKey);
9,785
89
// This will only be hit if a user has misconfigured the stale index and then tried to load father into the past than has been preserved
require(_pastBlock <= blocknumber, "Search Failure"); return (staleIndex, _loadedData);
require(_pastBlock <= blocknumber, "Search Failure"); return (staleIndex, _loadedData);
12,050
6
// Send tokens /
function transfer(address _to, uint256 _value) returns (bool success){ if (_value == 0) return false; // Don&#39;t waste gas on zero-value transaction if (balanceOf[msg.sender] &lt; _value) return false; // Check if the sender has enough if (balanceOf[_to] + _value &lt; balanceOf[_to]) throw; // Check for overflows if (frozenAccount[msg.sender]) throw; // Check if sender is frozen if (frozenAccount[_to]) throw; // Check if target is frozen balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; }
function transfer(address _to, uint256 _value) returns (bool success){ if (_value == 0) return false; // Don&#39;t waste gas on zero-value transaction if (balanceOf[msg.sender] &lt; _value) return false; // Check if the sender has enough if (balanceOf[_to] + _value &lt; balanceOf[_to]) throw; // Check for overflows if (frozenAccount[msg.sender]) throw; // Check if sender is frozen if (frozenAccount[_to]) throw; // Check if target is frozen balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; }
37,037
68
// @inheritdoc ITokensRescuer
function rescueNativeToken( uint256 amount, address receiver
function rescueNativeToken( uint256 amount, address receiver
36,011
335
// RevenueFund The target of all revenue earned in driip settlements and from which accrued revenue is split amongstaccrual beneficiaries. /
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() public payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public { receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string, int256 amount, address currencyCt, uint256 currencyId, string standard) public { require(amount.isNonZeroPositiveInt256()); // Execute transfer TransferController controller = transferController(currencyCt, standard); require( address(controller).delegatecall( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] currencies) public onlyOperator { require(ConstantsLib.PARTS_PER() == totalBeneficiaryFraction); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { address beneficiaryAddress = beneficiaries[j]; if (beneficiaryFraction(beneficiaryAddress) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiaryAddress)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); require( address(controller).delegatecall( controller.getApproveSignature(), beneficiaryAddress, uint256(transferable), currency.ct, currency.id ) ); AccrualBeneficiary(beneficiaryAddress).receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (j = 0; j < beneficiaries.length; j++) { beneficiaryAddress = beneficiaries[j]; // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiaryAddress)) continue; // Close accrual period AccrualBeneficiary(beneficiaryAddress).closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } }
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() public payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public { receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string, int256 amount, address currencyCt, uint256 currencyId, string standard) public { require(amount.isNonZeroPositiveInt256()); // Execute transfer TransferController controller = transferController(currencyCt, standard); require( address(controller).delegatecall( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] currencies) public onlyOperator { require(ConstantsLib.PARTS_PER() == totalBeneficiaryFraction); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { address beneficiaryAddress = beneficiaries[j]; if (beneficiaryFraction(beneficiaryAddress) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiaryAddress)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); require( address(controller).delegatecall( controller.getApproveSignature(), beneficiaryAddress, uint256(transferable), currency.ct, currency.id ) ); AccrualBeneficiary(beneficiaryAddress).receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (j = 0; j < beneficiaries.length; j++) { beneficiaryAddress = beneficiaries[j]; // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiaryAddress)) continue; // Close accrual period AccrualBeneficiary(beneficiaryAddress).closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } }
37,143
199
// Return the balance in locker + unlocked but not withdrawn, better estimate to allow some withdrawals then multiply it by the price per share as we need to convert CVX to bCVX
uint256 valueInLocker = CVXToWant(LOCKER.lockedBalanceOf(address(this))).add( CVXToWant(IERC20Upgradeable(CVX).balanceOf(address(this))) ); return (valueInLocker);
uint256 valueInLocker = CVXToWant(LOCKER.lockedBalanceOf(address(this))).add( CVXToWant(IERC20Upgradeable(CVX).balanceOf(address(this))) ); return (valueInLocker);
9,518
191
// Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); }
function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); }
28,053
65
// check if the dispute period is over _asset asset address _expiryTimestamp expiry timestampreturn True if dispute period is over, False if not /
function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) public view returns (bool) { uint256 price = stablePrice[_asset]; if (price == 0) { // check if the pricer has a price for this expiry timestamp Price memory price = storedPrice[_asset][_expiryTimestamp]; if (price.timestamp == 0) { return false; } address pricer = assetPricer[_asset]; uint256 disputePeriod = pricerDisputePeriod[pricer]; return now > price.timestamp.add(disputePeriod); } return true; }
function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) public view returns (bool) { uint256 price = stablePrice[_asset]; if (price == 0) { // check if the pricer has a price for this expiry timestamp Price memory price = storedPrice[_asset][_expiryTimestamp]; if (price.timestamp == 0) { return false; } address pricer = assetPricer[_asset]; uint256 disputePeriod = pricerDisputePeriod[pricer]; return now > price.timestamp.add(disputePeriod); } return true; }
31,702
14
// IMPORTANT: this function assumes Vat rate of this ilk will always be == 1RAY (no fees). That's why this module converts normalized debt (art) to Vat DAI generated with a simple RAY multiplication or division This module will have an unintended behaviour if rate is changed to some other value.
(, uint256 daiDebt) = vat.urns(ilk, address(direct)); uint256 _bar = direct.bar(); if (_bar == 0) { return daiDebt > 1; // Always attempt to close out if we have debt remaining }
(, uint256 daiDebt) = vat.urns(ilk, address(direct)); uint256 _bar = direct.bar(); if (_bar == 0) { return daiDebt > 1; // Always attempt to close out if we have debt remaining }
44,778
115
// Calculate total profit and allocate 50% to old owner, 50% to bankroll
uint totalProfit = SafeMath.sub(currentPrice, previousPrice); uint oldOwnerProfit = SafeMath.div(totalProfit, 2); uint bankrollProfit = SafeMath.sub(totalProfit, oldOwnerProfit); oldOwnerProfit = SafeMath.add(oldOwnerProfit, previousPrice);
uint totalProfit = SafeMath.sub(currentPrice, previousPrice); uint oldOwnerProfit = SafeMath.div(totalProfit, 2); uint bankrollProfit = SafeMath.sub(totalProfit, oldOwnerProfit); oldOwnerProfit = SafeMath.add(oldOwnerProfit, previousPrice);
76,504
3
// Atomic Token SwapDetermines type (ERC-20 or ERC-721) with ERC-165order Ordersignature Signature/
function swap( Order calldata order, Signature calldata signature ) external payable
function swap( Order calldata order, Signature calldata signature ) external payable
46,326
292
// Shows current Sorbetto's balances/totalAmount0 Current token0 Sorbetto's balance/totalAmount1 Current token1 Sorbetto's balance
event Snapshot(uint256 totalAmount0, uint256 totalAmount1); event TransferGovernance(address indexed previousGovernance, address indexed newGovernance);
event Snapshot(uint256 totalAmount0, uint256 totalAmount1); event TransferGovernance(address indexed previousGovernance, address indexed newGovernance);
14,883
336
// documentPolls: per hash, poll held to determine if the corresponding document is accepted by the galactic senate
mapping(bytes32 => Poll) public documentPolls;
mapping(bytes32 => Poll) public documentPolls;
2,129
12
// Emitted when a message is sent to the child chain
event SentMessagesToChild(Message[] data);
event SentMessagesToChild(Message[] data);
82,549
16
// increse allowances , those will be reduced in transferFrom method again
allowed[ownerAccount][msg.sender] = allowed[ownerAccount][msg.sender].add(tokens); transferFrom(ownerAccount,msg.sender, tokens); ownerAccount.transfer(owneramount);
allowed[ownerAccount][msg.sender] = allowed[ownerAccount][msg.sender].add(tokens); transferFrom(ownerAccount,msg.sender, tokens); ownerAccount.transfer(owneramount);
36,582
61
// Burns CLIMB Token from msg.sender /
function burn(uint256 amount) external { _burn(msg.sender, amount); }
function burn(uint256 amount) external { _burn(msg.sender, amount); }
3,614
60
// Emitted when an bToken is initialized underlyingAsset The address of the underlying asset pool The address of the associated lending pool treasury The address of the treasury incentivesController The address of the incentives controller for this bToken // Initializes the bToken addressProvider The address of the address provider where this bToken will be used treasury The address of the Bend treasury, receiving the fees on this bToken underlyingAsset The address of the underlying asset of this bToken /
function initialize( ILendPoolAddressesProvider addressProvider, address treasury, address underlyingAsset, uint8 bTokenDecimals, string calldata bTokenName, string calldata bTokenSymbol ) external;
function initialize( ILendPoolAddressesProvider addressProvider, address treasury, address underlyingAsset, uint8 bTokenDecimals, string calldata bTokenName, string calldata bTokenSymbol ) external;
68,645
124
// Get up to date cToken data without mutating state./Transmissions11 (https:github.com/transmissions11/libcompound)
library LibFuse { using FixedPointMathLib for uint256; function viewUnderlyingBalanceOf(CERC20 cToken, address user) internal view returns (uint256) { return cToken.balanceOf(user).mulWadDown(viewExchangeRate(cToken)); } function viewExchangeRate(CERC20 cToken) internal view returns (uint256) { uint256 accrualBlockNumberPrior = cToken.accrualBlockNumber(); if (accrualBlockNumberPrior == block.number) return cToken.exchangeRateStored(); uint256 totalCash = cToken.underlying().balanceOf(address(cToken)); uint256 borrowsPrior = cToken.totalBorrows(); uint256 reservesPrior = cToken.totalReserves(); uint256 adminFeesPrior = cToken.totalAdminFees(); uint256 fuseFeesPrior = cToken.totalFuseFees(); uint256 interestAccumulated; // Generated in new scope to avoid stack too deep. { uint256 borrowRateMantissa = cToken.interestRateModel().getBorrowRate( totalCash, borrowsPrior, reservesPrior + adminFeesPrior + fuseFeesPrior ); // Same as borrowRateMaxMantissa in CTokenInterfaces.sol require(borrowRateMantissa <= 0.0005e16, "RATE_TOO_HIGH"); interestAccumulated = (borrowRateMantissa * (block.number - accrualBlockNumberPrior)).mulWadDown( borrowsPrior ); } uint256 totalReserves = cToken.reserveFactorMantissa().mulWadDown(interestAccumulated) + reservesPrior; uint256 totalAdminFees = cToken.adminFeeMantissa().mulWadDown(interestAccumulated) + adminFeesPrior; uint256 totalFuseFees = cToken.fuseFeeMantissa().mulWadDown(interestAccumulated) + fuseFeesPrior; uint256 totalSupply = cToken.totalSupply(); return totalSupply == 0 ? cToken.initialExchangeRateMantissa() : (totalCash + (interestAccumulated + borrowsPrior) - (totalReserves + totalAdminFees + totalFuseFees)) .divWadDown(totalSupply); } }
library LibFuse { using FixedPointMathLib for uint256; function viewUnderlyingBalanceOf(CERC20 cToken, address user) internal view returns (uint256) { return cToken.balanceOf(user).mulWadDown(viewExchangeRate(cToken)); } function viewExchangeRate(CERC20 cToken) internal view returns (uint256) { uint256 accrualBlockNumberPrior = cToken.accrualBlockNumber(); if (accrualBlockNumberPrior == block.number) return cToken.exchangeRateStored(); uint256 totalCash = cToken.underlying().balanceOf(address(cToken)); uint256 borrowsPrior = cToken.totalBorrows(); uint256 reservesPrior = cToken.totalReserves(); uint256 adminFeesPrior = cToken.totalAdminFees(); uint256 fuseFeesPrior = cToken.totalFuseFees(); uint256 interestAccumulated; // Generated in new scope to avoid stack too deep. { uint256 borrowRateMantissa = cToken.interestRateModel().getBorrowRate( totalCash, borrowsPrior, reservesPrior + adminFeesPrior + fuseFeesPrior ); // Same as borrowRateMaxMantissa in CTokenInterfaces.sol require(borrowRateMantissa <= 0.0005e16, "RATE_TOO_HIGH"); interestAccumulated = (borrowRateMantissa * (block.number - accrualBlockNumberPrior)).mulWadDown( borrowsPrior ); } uint256 totalReserves = cToken.reserveFactorMantissa().mulWadDown(interestAccumulated) + reservesPrior; uint256 totalAdminFees = cToken.adminFeeMantissa().mulWadDown(interestAccumulated) + adminFeesPrior; uint256 totalFuseFees = cToken.fuseFeeMantissa().mulWadDown(interestAccumulated) + fuseFeesPrior; uint256 totalSupply = cToken.totalSupply(); return totalSupply == 0 ? cToken.initialExchangeRateMantissa() : (totalCash + (interestAccumulated + borrowsPrior) - (totalReserves + totalAdminFees + totalFuseFees)) .divWadDown(totalSupply); } }
25,941
25
// get hard cap
function getHardCap() external view returns (uint256) { return _hardCap; }
function getHardCap() external view returns (uint256) { return _hardCap; }
1,543
3
// set new listing fee value. _listingFee new listing fee value /
function setListingFee(uint256 _listingFee) public isInteger(_listingFee) onlyOwner
function setListingFee(uint256 _listingFee) public isInteger(_listingFee) onlyOwner
15,156
12
// Used to initialize the contract during delegator contructor timelock_ The address of the NounsDAOExecutor nouns_ The address of the NOUN tokens vetoer_ The address allowed to unilaterally veto proposals votingPeriod_ The initial voting period votingDelay_ The initial voting delay proposalThresholdBPS_ The initial proposal threshold in basis pointsquorumVotesBPS_ The initial quorum votes threshold in basis points /
function initialize( address timelock_, address nouns_, address vetoer_, uint256 votingPeriod_, uint256 votingDelay_, uint256 proposalThresholdBPS_, uint256 quorumVotesBPS_
function initialize( address timelock_, address nouns_, address vetoer_, uint256 votingPeriod_, uint256 votingDelay_, uint256 proposalThresholdBPS_, uint256 quorumVotesBPS_
9,352
179
// See {IERC721-isApprovedForAll}. /
function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; }
function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; }
39,226
23
// amount of rEON due for each fuel index point. address => allowedToCallFunctions
mapping(address => bool) private admins; uint256 public rawEonPerRank = 0; uint256 private totalRankStaked; uint256 public piratesStaked;
mapping(address => bool) private admins; uint256 public rawEonPerRank = 0; uint256 private totalRankStaked; uint256 public piratesStaked;
57,555
466
// returns true if the reserve is active_reserve the reserve address return true if the reserve is active, false otherwise/
function getReserveIsActive(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isActive; }
function getReserveIsActive(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isActive; }
81,166
142
// In order to keep backwards compatibility we have kept the userseed field around. We remove the use of it because given that the blockhashenters later, it overrides whatever randomness the used seed provides.Given that it adds no security, and can easily lead to misunderstandings,we have removed it from usage and can now provide a simpler API. /
uint256 constant private USER_SEED_PLACEHOLDER = 0;
uint256 constant private USER_SEED_PLACEHOLDER = 0;
5,541
1
// Emitted when a new clone is created
event Created(address addr);
event Created(address addr);
24,811
29
// interest is paid before principal
if (loanCloseAmount >= loanInterest) { principalAfter = principalBefore.sub(loanCloseAmount - loanInterest); loanLocal.principal = principalAfter; poolPrincipalTotal[loanLocal.lender] = poolPrincipalTotal[loanLocal.lender] .sub(loanCloseAmount - loanInterest); loanInterestTotal[loanLocal.id] = 0; } else {
if (loanCloseAmount >= loanInterest) { principalAfter = principalBefore.sub(loanCloseAmount - loanInterest); loanLocal.principal = principalAfter; poolPrincipalTotal[loanLocal.lender] = poolPrincipalTotal[loanLocal.lender] .sub(loanCloseAmount - loanInterest); loanInterestTotal[loanLocal.id] = 0; } else {
58,305
247
// Storage for this proxy
bytes32 internal constant IMPLEMENTATION_SLOT = bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc); bytes32 internal constant ADMIN_SLOT = bytes32(0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103);
bytes32 internal constant IMPLEMENTATION_SLOT = bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc); bytes32 internal constant ADMIN_SLOT = bytes32(0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103);
11,198
174
// For more efficient reverts. /
function _revert(bytes4 errorSelector) internal pure { assembly { mstore(0x00, errorSelector) revert(0x00, 0x04) } }
function _revert(bytes4 errorSelector) internal pure { assembly { mstore(0x00, errorSelector) revert(0x00, 0x04) } }
14,680
12
// Returns the cached value for token's rate. Reverts if the token doesn't belong to the pool or has no rateprovider. /
function getTokenRateCache(IERC20 token) external view returns ( uint256 rate, uint256 oldRate, uint256 duration, uint256 expires )
function getTokenRateCache(IERC20 token) external view returns ( uint256 rate, uint256 oldRate, uint256 duration, uint256 expires )
21,257
763
// Castes vote for members who have tokens locked under Claims Assessment claimIdclaim id. verdict 1 for Accept,-1 for Deny. /
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender);
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender);
54,852