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
127
// profits are calculated
uint256 fee = payout.mul(terms.fee).div(10000); uint256 profit = value.sub(payout).sub(fee);
uint256 fee = payout.mul(terms.fee).div(10000); uint256 profit = value.sub(payout).sub(fee);
2,815
31
// return jester
jester.send(jesterBank); jesterBank = 0; jester = msg.sender; msg.sender.send(msg.value - amount); investInTheSystem(amount);
jester.send(jesterBank); jesterBank = 0; jester = msg.sender; msg.sender.send(msg.value - amount); investInTheSystem(amount);
42,940
8
// ---------------------------------------------------------------------------- External Only Admin / owner /Set use of mint rules in contracty Owner con contract can turn off / on the use of mint rules only
* - Emits a {RuleUpdate} event. */ function useUseMintRules(bool _state) external onlyOwner { useMintRules = _state; uint state = useMintRules ? uint(1) : uint(0); emit RuleUpdate(msg.sender, string.concat("Setting mint rules: ",state.toString())); }
* - Emits a {RuleUpdate} event. */ function useUseMintRules(bool _state) external onlyOwner { useMintRules = _state; uint state = useMintRules ? uint(1) : uint(0); emit RuleUpdate(msg.sender, string.concat("Setting mint rules: ",state.toString())); }
12,318
14
// Check if sender is a registered identity
super._requireValidIdentity( signingRoot_, INVOICE_SENDER, _getSender(), salts[SENDER_IDX], proofs[SENDER_IDX] );
super._requireValidIdentity( signingRoot_, INVOICE_SENDER, _getSender(), salts[SENDER_IDX], proofs[SENDER_IDX] );
50,124
4
// função de desbloqueio que nos permite chamar nossas funções após a quantidade de dias definido na constante _TIMELOCK
function unlockFunction(Functions _fn) public onlyOwner { timelock[_fn] = block.timestamp + _TIMELOCK; }
function unlockFunction(Functions _fn) public onlyOwner { timelock[_fn] = block.timestamp + _TIMELOCK; }
26,602
144
// Given X input tokens, return Y output tokens without concern about minimum/slippage
function swapTokens(uint256 amount, IBEP20 inputToken, IBEP20 outputToken) private { if (address(inputToken) == address(outputToken)) { return; } address[] storage path = getRouterPath(address(inputToken), address(outputToken)); require(path.length > 0, "swapTokens: NO PATH"); inputToken.safeApprove(routerAddr, amount); IPancakeRouter02(routerAddr).swapExactTokensForTokensSupportingFeeOnTransferTokens( amount, 0, path, address(this), getTxDeadline() ); }
function swapTokens(uint256 amount, IBEP20 inputToken, IBEP20 outputToken) private { if (address(inputToken) == address(outputToken)) { return; } address[] storage path = getRouterPath(address(inputToken), address(outputToken)); require(path.length > 0, "swapTokens: NO PATH"); inputToken.safeApprove(routerAddr, amount); IPancakeRouter02(routerAddr).swapExactTokensForTokensSupportingFeeOnTransferTokens( amount, 0, path, address(this), getTxDeadline() ); }
17,742
9
// Check
require(moves.length >= 2, "inv draw"); require(moves[moves.length - 2] == request_draw_const, "inv draw"); outcome = draw_outcome;
require(moves.length >= 2, "inv draw"); require(moves[moves.length - 2] == request_draw_const, "inv draw"); outcome = draw_outcome;
41,211
25
// Enabling user to request voting rights - voter can request from admin to get voting rights:
mapping (uint => address) public pendingVoters; uint public numberOfPendingRequest;
mapping (uint => address) public pendingVoters; uint public numberOfPendingRequest;
32,058
7
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
assembly { codehash := extcodehash(account) }
6,570
69
// solium-disable-next-line / Swap tokens for base, send base directly to the owner
require(baseToken.transferFrom(msg.sender, owner, requesting), "auction: error pulling tokens");
require(baseToken.transferFrom(msg.sender, owner, requesting), "auction: error pulling tokens");
28,872
426
// Car level with decimal multiplier
uint256 carLevel = _allCars[tokenId].carLevel;
uint256 carLevel = _allCars[tokenId].carLevel;
36,097
139
// Throws when the order status is invalid or the signer is not valid./
function assertTakeOrder( bytes32 orderHash, uint8 status, address signer, bytes memory signature ) internal pure returns(uint8)
function assertTakeOrder( bytes32 orderHash, uint8 status, address signer, bytes memory signature ) internal pure returns(uint8)
13,297
90
// Fallback function allowing to perform a delegatecall to the given implementation. This function will return whatever the implementation call returns /
function () payable external { address impl = implementation; require(impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } }
function () payable external { address impl = implementation; require(impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } }
12,759
84
// save deployer for easier initialization
address public m_deployer;
address public m_deployer;
209
115
// Loop through all plots, accounting the number of plots of the owner we've seen.
uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; }
uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; }
13,270
109
// i.e. on BSC side: rate = ETH price / BNB price = 5
uint256 requireAmount = foreignAmount * rate / vars.nominatorForeignToNative; if (totalSupply[pairID] < nativeAmount + requireAmount) { requireAmount = totalSupply[pairID] - nativeAmount; rest = foreignAmount - (requireAmount * vars.nominatorForeignToNative / rate); foreignAmount = foreignAmount - rest; }
uint256 requireAmount = foreignAmount * rate / vars.nominatorForeignToNative; if (totalSupply[pairID] < nativeAmount + requireAmount) { requireAmount = totalSupply[pairID] - nativeAmount; rest = foreignAmount - (requireAmount * vars.nominatorForeignToNative / rate); foreignAmount = foreignAmount - rest; }
81,655
16
// require(msg.sender == linkAddressA, 'Vsn Network: FORBIDDEN');
if(_addrA!=linkAddressA){ return false; }
if(_addrA!=linkAddressA){ return false; }
29,378
21
// Returns the duration of each period in secondsreturn Duration of each period in seconds /
function periodDuration() public view override returns (uint256) { return duration().div(periods); }
function periodDuration() public view override returns (uint256) { return duration().div(periods); }
22,804
60
// Pausable Base contract which allows children to implement an emergency stop mechanism. /
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
3,835
41
// User records
mapping(address => User) public users;
mapping(address => User) public users;
48,949
53
// The ```WithdrawFees``` event fires when the fees are withdrawn/shares Number of shares (fTokens) redeemed/recipient To whom the assets were sent/amountToTransfer The amount of fees redeemed
event WithdrawFees(uint128 shares, address recipient, uint256 amountToTransfer, uint256 collateralAmount);
event WithdrawFees(uint128 shares, address recipient, uint256 amountToTransfer, uint256 collateralAmount);
16,613
370
// DAI vat address /
address public vatAddress;
address public vatAddress;
37,509
156
// This is an extension function that instructs CreditFacade to check token balances at the end Used to control slippage after the entire sequence of operations, since tracking slippage On each operation is not ideal
if (method == ICreditFacadeExtended.revertIfReceivedLessThan.selector) {
if (method == ICreditFacadeExtended.revertIfReceivedLessThan.selector) {
26,308
218
// Mint token
uint256 tokenId = _mint(to, _redemptionCount); _mintedTokens.push(tokenId); _mintNumbers[tokenId] = _redemptionCount;
uint256 tokenId = _mint(to, _redemptionCount); _mintedTokens.push(tokenId); _mintNumbers[tokenId] = _redemptionCount;
9,864
85
// Refund the sender. To be called when the sender wants to refund a transaction. _transactionID The index of the transaction. /
function refund(uint256 _transactionID) public { Transaction storage transaction = transactions[_transactionID]; require(transaction.isExecuted == false, "The transaction should not be refunded."); require(transaction.timeoutPayment <= block.timestamp, "The timeout payment should be passed."); require(transaction.runningClaimCount == 0, "The transaction should not to have running claims."); transaction.isExecuted = true; payable(transaction.sender).transfer(transaction.amount); emit Refund(_transactionID, transaction.amount, transaction.sender); }
function refund(uint256 _transactionID) public { Transaction storage transaction = transactions[_transactionID]; require(transaction.isExecuted == false, "The transaction should not be refunded."); require(transaction.timeoutPayment <= block.timestamp, "The timeout payment should be passed."); require(transaction.runningClaimCount == 0, "The transaction should not to have running claims."); transaction.isExecuted = true; payable(transaction.sender).transfer(transaction.amount); emit Refund(_transactionID, transaction.amount, transaction.sender); }
18,231
10
// This function splits a position. If splitting from the collateral, this contract will attempt to transfer `amount` collateral from the message sender to itself. Otherwise, this contract will burn `amount` stake held by the message sender in the position being split worth of EIP 1155 tokens. Regardless, if successful, `amount` stake will be minted in the split target positions. If any of the transfers, mints, or burns fail, the transaction will revert. The transaction will also revert if the given partition is trivial, invalid, or refers to more slots than the condition is prepared with./collateralToken The address of the positions'
function splitPosition( IERC20 collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] calldata partition, uint amount
function splitPosition( IERC20 collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] calldata partition, uint amount
20,977
33
// Checks if the current phase is ALPHA.return True if the current phase is ALPHA, false otherwise. /
function _isALPHA() internal view returns (bool) { require( phaseMintedAmount[currentPhase] < PHASE_ALPHA_SUPPLY, "Exceeded mint phase amount" ); return true; }
function _isALPHA() internal view returns (bool) { require( phaseMintedAmount[currentPhase] < PHASE_ALPHA_SUPPLY, "Exceeded mint phase amount" ); return true; }
23,407
96
// update liquidity if it changed
if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;
if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;
46,864
21
// Returns the number of tokens `spender` can transfer from `holder` /
{ return 0; }
{ return 0; }
8,053
109
// Returns last bid for canvas. If the initial bidding has been already finished that will be winning offer./
function getLastBidForCanvas(uint32 _canvasId) external view returns ( uint32 canvasId, address bidder, uint amount, uint finishTime
function getLastBidForCanvas(uint32 _canvasId) external view returns ( uint32 canvasId, address bidder, uint amount, uint finishTime
36,428
3
// function to set the Proof of existence for a file/
function SetFileExistenceProof(address dappBoxOrigin, string memory _fileHash, string memory _filePathHash, address _contractAddress ,BlockchainIdentification _identifier) public returns (bytes32)
function SetFileExistenceProof(address dappBoxOrigin, string memory _fileHash, string memory _filePathHash, address _contractAddress ,BlockchainIdentification _identifier) public returns (bytes32)
50,028
67
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
15,339
3
// Check if the sender is a member of the given room name specifies the room to check membership for /
function senderIsInRoom(string calldata name) public view returns (bool) { address sender = msg.sender; return _membershipsMap[name][sender]; }
function senderIsInRoom(string calldata name) public view returns (bool) { address sender = msg.sender; return _membershipsMap[name][sender]; }
22,357
5
// Restricted methods for the treasury manager
modifier onlyManager() { require(msg.sender == manager, "Unauthorized"); _; }
modifier onlyManager() { require(msg.sender == manager, "Unauthorized"); _; }
69,486
4
// should decrease token supply by amount, and should (probably) only be callable by the L1 bridge. /
function bridgeBurn(address account, uint256 amount) external override onlyL2Gateway { _burn(account, amount); }
function bridgeBurn(address account, uint256 amount) external override onlyL2Gateway { _burn(account, amount); }
1,934
38
// 在主交易合约中设置仲裁参数
if (slates[i][pau].arb != 0) dotc.setArb(i,slates[i][pau].arb); dotc.setComp(i, slates[i][pau].who, slates[i][pau].comp);
if (slates[i][pau].arb != 0) dotc.setArb(i,slates[i][pau].arb); dotc.setComp(i, slates[i][pau].who, slates[i][pau].comp);
4,519
4
// Modify
modifier claimIsOpen { require(claimState, "Claim is Closed"); require(!paused, "Contract Paused"); _; }
modifier claimIsOpen { require(claimState, "Claim is Closed"); require(!paused, "Contract Paused"); _; }
57,620
19
// makes the access check unenforced /
function disableAccessCheck() external onlyOwner()
function disableAccessCheck() external onlyOwner()
32,137
0
// Decompose an ABI-encoded SignatureError./encoded ABI-encoded revert error./ return errorCode The error code./ return signerAddress The expected signer of the hash./ return signature The full signature.
function decodeSignatureError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.SignatureErrorCodes errorCode, bytes32 hash, address signerAddress, bytes memory signature )
function decodeSignatureError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.SignatureErrorCodes errorCode, bytes32 hash, address signerAddress, bytes memory signature )
44,779
179
// Withdraws the staking reward /
RewardPrices memory prices = _withdrawInterest(_property);
RewardPrices memory prices = _withdrawInterest(_property);
10,596
92
// Allow next time lock to be zero address (cancel next time lock)
nextTimeLock = _nextTimeLock; emit SetNextTimeLock(_nextTimeLock);
nextTimeLock = _nextTimeLock; emit SetNextTimeLock(_nextTimeLock);
12,095
287
// enables/disables depositing into a given pool requirements: - the caller must be the owner of the contract /
function enableDepositing(Token pool, bool status) external onlyOwner { Pool storage data = _poolStorage(pool); if (data.depositingEnabled == status) { return; } data.depositingEnabled = status; emit DepositingEnabled({ pool: pool, newStatus: status }); }
function enableDepositing(Token pool, bool status) external onlyOwner { Pool storage data = _poolStorage(pool); if (data.depositingEnabled == status) { return; } data.depositingEnabled = status; emit DepositingEnabled({ pool: pool, newStatus: status }); }
75,550
218
// Shared public library for on-chain NFT functions
interface IPublicSharedMetadata { /// @param unencoded bytes to base64-encode function base64Encode(bytes memory unencoded) external pure returns (string memory); /// Encodes the argument json bytes into base64-data uri format /// @param json Raw json to base64 and turn into a data-uri function encodeMetadataJSON(bytes memory json) external pure returns (string memory); /// Proxy to openzeppelin's toString function /// @param value number to return as a string function numberToString(uint256 value) external pure returns (string memory); }
interface IPublicSharedMetadata { /// @param unencoded bytes to base64-encode function base64Encode(bytes memory unencoded) external pure returns (string memory); /// Encodes the argument json bytes into base64-data uri format /// @param json Raw json to base64 and turn into a data-uri function encodeMetadataJSON(bytes memory json) external pure returns (string memory); /// Proxy to openzeppelin's toString function /// @param value number to return as a string function numberToString(uint256 value) external pure returns (string memory); }
42,419
3
// Trasnfer NFT to other chain. (A script listens to the BridgeTransfer Event)receiver - Account address of the NFT receivertokenId - Id fo the transferring NFTtokenAddress - Address of the transferring NFT/
function transferToOtherChain(address receiver, uint256 tokenId, address tokenAddress) external { string memory tokenName = IERC721MetadataUpgradeable(tokenAddress).name(); string memory tokenSymbol = IERC721MetadataUpgradeable(tokenAddress).symbol(); string memory tokenUri = IERC721MetadataUpgradeable(tokenAddress).tokenURI(tokenId); IERC721Upgradeable(tokenAddress).safeTransferFrom(msg.sender, address(this), tokenId); OtherChainToken memory otherChainToken = OtherChainToken( msg.sender, tokenAddress, tokenId, tokenName, tokenSymbol, tokenUri ); _otherChainTokens[tokenAddress][tokenId] = otherChainToken; emit BridgeTransfer ( msg.sender, receiver, tokenAddress, tokenId, tokenUri ); }
function transferToOtherChain(address receiver, uint256 tokenId, address tokenAddress) external { string memory tokenName = IERC721MetadataUpgradeable(tokenAddress).name(); string memory tokenSymbol = IERC721MetadataUpgradeable(tokenAddress).symbol(); string memory tokenUri = IERC721MetadataUpgradeable(tokenAddress).tokenURI(tokenId); IERC721Upgradeable(tokenAddress).safeTransferFrom(msg.sender, address(this), tokenId); OtherChainToken memory otherChainToken = OtherChainToken( msg.sender, tokenAddress, tokenId, tokenName, tokenSymbol, tokenUri ); _otherChainTokens[tokenAddress][tokenId] = otherChainToken; emit BridgeTransfer ( msg.sender, receiver, tokenAddress, tokenId, tokenUri ); }
3,267
51
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
let zRoundDown := div(x, z)
18,302
306
// return Half-life of 12h (720 min)./(1/2) = d^720 => d = (1/2)^(1/720)
function MINUTE_DECAY_FACTOR() external view returns (uint256);
function MINUTE_DECAY_FACTOR() external view returns (uint256);
21,903
68
// validate ETH amount send to contract
if (msg.value != quantity_ * sale_.price) { revert WrongValueSentForMintError(saleId_, msg.value, sale_.price, quantity_); }
if (msg.value != quantity_ * sale_.price) { revert WrongValueSentForMintError(saleId_, msg.value, sale_.price, quantity_); }
40,044
188
// Requester's Request ID => Requester
mapping(bytes32 => Requester) internal requesters;
mapping(bytes32 => Requester) internal requesters;
35,082
81
// The next three lines store the expected bytecode for a miniml proxy that targets `target` as its implementation contract
mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 )
mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 )
14,244
6
// Time constants in seconds Weekly by Default
uint256 public payTime = 86400 * 7; uint256 public withdrawTime = 86400 * 7;
uint256 public payTime = 86400 * 7; uint256 public withdrawTime = 86400 * 7;
447
82
// Ditto's Master Controller for an elastic supply currency based on the uFragments Ideal Money protocol a.k.a. Ampleforth. uFragments operates symmetrically on expansion and contraction. It will both split and combine coins to maintain a stable unit price.This component regulates the token supply of the uFragments ERC20 token in response to market oracles. /
contract Master is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); // Stable ordering is not guaranteed. Transaction[] public transactions; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, int256 requestedSupplyAdjustment, uint256 timestampSec ); IDitto public ditto; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. IOracle public marketOracle; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // More than this much time must pass between rebase operations. uint256 public rebaseCooldown; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; // Rebase will remain restricted to the owner until the final Oracle is deployed and battle-tested. // Ownership will be renounced after this inital period. bool public rebaseLocked; constructor(address _ditto) public { deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseCooldown = 4 hours; lastRebaseTimestampSec = 0; epoch = 0; rebaseLocked = true; ditto = IDitto(_ditto); } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Override to ensure that rebases aren't locked when this happens. */ function renounceOwnership() public onlyOwner { require(!rebaseLocked, "Cannot renounce ownership if rebase is locked"); super.renounceOwnership(); } function setRebaseLocked(bool _locked) external onlyOwner { rebaseLocked = _locked; } /** * @notice Returns true if the cooldown timer has expired since the last rebase. * */ function canRebase() public view returns (bool) { return ((!rebaseLocked || isOwner()) && lastRebaseTimestampSec.add(rebaseCooldown) < now); } function cooldownExpiryTimestamp() public view returns (uint256) { return lastRebaseTimestampSec.add(rebaseCooldown); } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * */ function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, uint256 targetRate, int256 supplyDelta) = getRebaseValues(); uint256 supplyAfterRebase = ditto.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); emit LogRebase(epoch, exchangeRate, supplyDelta, now); } /** * @notice Calculates the supplyDelta and returns the current set of values for the rebase * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * */ function getRebaseValues() public view returns (uint256, uint256, int256) { uint256 targetRate = 10 ** DECIMALS; uint256 exchangeRate = marketOracle.getData(); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the dampening factor. if (supplyDelta < 0) { supplyDelta = supplyDelta.div(2); } else { supplyDelta = supplyDelta.div(5); } if (supplyDelta > 0 && ditto.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(ditto.totalSupply())).toInt256Safe(); } return (exchangeRate, targetRate, supplyDelta); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return ditto.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactions.length; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( sub(gas(), 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
contract Master is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); // Stable ordering is not guaranteed. Transaction[] public transactions; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, int256 requestedSupplyAdjustment, uint256 timestampSec ); IDitto public ditto; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. IOracle public marketOracle; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // More than this much time must pass between rebase operations. uint256 public rebaseCooldown; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; // Rebase will remain restricted to the owner until the final Oracle is deployed and battle-tested. // Ownership will be renounced after this inital period. bool public rebaseLocked; constructor(address _ditto) public { deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseCooldown = 4 hours; lastRebaseTimestampSec = 0; epoch = 0; rebaseLocked = true; ditto = IDitto(_ditto); } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Override to ensure that rebases aren't locked when this happens. */ function renounceOwnership() public onlyOwner { require(!rebaseLocked, "Cannot renounce ownership if rebase is locked"); super.renounceOwnership(); } function setRebaseLocked(bool _locked) external onlyOwner { rebaseLocked = _locked; } /** * @notice Returns true if the cooldown timer has expired since the last rebase. * */ function canRebase() public view returns (bool) { return ((!rebaseLocked || isOwner()) && lastRebaseTimestampSec.add(rebaseCooldown) < now); } function cooldownExpiryTimestamp() public view returns (uint256) { return lastRebaseTimestampSec.add(rebaseCooldown); } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * */ function rebase() external { require(tx.origin == msg.sender); require(canRebase(), "Rebase not allowed"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 exchangeRate, uint256 targetRate, int256 supplyDelta) = getRebaseValues(); uint256 supplyAfterRebase = ditto.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } marketOracle.update(); emit LogRebase(epoch, exchangeRate, supplyDelta, now); } /** * @notice Calculates the supplyDelta and returns the current set of values for the rebase * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * */ function getRebaseValues() public view returns (uint256, uint256, int256) { uint256 targetRate = 10 ** DECIMALS; uint256 exchangeRate = marketOracle.getData(); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the dampening factor. if (supplyDelta < 0) { supplyDelta = supplyDelta.div(2); } else { supplyDelta = supplyDelta.div(5); } if (supplyDelta > 0 && ditto.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(ditto.totalSupply())).toInt256Safe(); } return (exchangeRate, targetRate, supplyDelta); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return ditto.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactions.length; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( sub(gas(), 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
1,524
43
// End the stake. Only callable after stake end time./
Statement storage s = statements[_statementID];
Statement storage s = statements[_statementID];
18,986
96
// Single asset variant of the internal initialize. /
function _initialize( address _platformAddress, address _vaultAddress, address _rewardTokenAddress, address _asset, address _pToken
function _initialize( address _platformAddress, address _vaultAddress, address _rewardTokenAddress, address _asset, address _pToken
5,683
102
// Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver recipient address The address which you want to transfer to amount uint256 The amount of tokens to be transferred data bytes Additional data with no specified format, sent in call to `recipient`return true unless throwing /
function transferAndCall( address recipient, uint256 amount, bytes calldata data ) external returns (bool);
function transferAndCall( address recipient, uint256 amount, bytes calldata data ) external returns (bool);
7,266
21
// The param struct used in function newOrInvestToVaultPosition(param)
struct NewOrInvestToVaultPositionParams { // vaultId uint256 vaultId; // The vaultPositionId of the vaultPosition to invest // 0 if open a new vaultPosition uint256 vaultPositionId; // The amount of token0 user want to invest uint256 amount0Invest; // The amount of token0 user want to borrow uint256 amount0Borrow; // The amount of token1 user want to invest uint256 amount1Invest; // The amount of token1 user want to borrow uint256 amount1Borrow; // The minimal amount of token0 should be added to the liquidity // This value will be used when call mint() or addLiquidity() of uniswap V3 pool uint256 amount0Min; // The minimal amount of token1 should be added to the liquidity // This value will be used when call mint() or addLiquidity() of uniswap V3 pool uint256 amount1Min; // The deadline of the tx uint256 deadline; // The swapExecutor to swap tokens uint256 swapExecutorId; // The swap path to swap tokens bytes swapPath; }
struct NewOrInvestToVaultPositionParams { // vaultId uint256 vaultId; // The vaultPositionId of the vaultPosition to invest // 0 if open a new vaultPosition uint256 vaultPositionId; // The amount of token0 user want to invest uint256 amount0Invest; // The amount of token0 user want to borrow uint256 amount0Borrow; // The amount of token1 user want to invest uint256 amount1Invest; // The amount of token1 user want to borrow uint256 amount1Borrow; // The minimal amount of token0 should be added to the liquidity // This value will be used when call mint() or addLiquidity() of uniswap V3 pool uint256 amount0Min; // The minimal amount of token1 should be added to the liquidity // This value will be used when call mint() or addLiquidity() of uniswap V3 pool uint256 amount1Min; // The deadline of the tx uint256 deadline; // The swapExecutor to swap tokens uint256 swapExecutorId; // The swap path to swap tokens bytes swapPath; }
10,133
83
// Get price of tier_index of tier to query return uint256 indicating tier priceTest(s) Need rewrite/
function getPrice(uint256 _index) external
function getPrice(uint256 _index) external
56,581
43
// whether admin/accountaddress to check
function isAdmin(address account) public view virtual returns (bool) { return hasRole(ADMIN_ROLE, account); }
function isAdmin(address account) public view virtual returns (bool) { return hasRole(ADMIN_ROLE, account); }
27,361
275
// TODO(779): If the price wasn't available, revert with the provided message.
require(_hasPrice, message); return price;
require(_hasPrice, message); return price;
22,233
52
// create pair
lpPair = IDexFactory(_dexRouter.factory()).createPair( address(this), _dexRouter.WETH() ); _excludeFromMaxTransaction(address(lpPair), true); _excludeFromMaxTransaction(address(dexRouter), true); _setAutomatedMarketMakerPair(address(lpPair), true); uint256 totalSupply = 1 * 1e8 * 1e18;
lpPair = IDexFactory(_dexRouter.factory()).createPair( address(this), _dexRouter.WETH() ); _excludeFromMaxTransaction(address(lpPair), true); _excludeFromMaxTransaction(address(dexRouter), true); _setAutomatedMarketMakerPair(address(lpPair), true); uint256 totalSupply = 1 * 1e8 * 1e18;
34,945
109
// if total deposit is 0
if (amtSum == 0) { require(msg.value == 0, "msg.value is not 0"); return; }
if (amtSum == 0) { require(msg.value == 0, "msg.value is not 0"); return; }
43,381
3
// ------------- Quote State ------------- / Maps the id to the quote
mapping(bytes16 => Quote) quotes;
mapping(bytes16 => Quote) quotes;
9,606
1
// "LIF": -1000
return RarelifeStructs.SAbilityModifiers(0,0,0,0,0,-1000,0);
return RarelifeStructs.SAbilityModifiers(0,0,0,0,0,-1000,0);
535
235
// Admin can withdraw ETH to admin account
function withdrawAll() public onlyAdmin
function withdrawAll() public onlyAdmin
58,424
377
// res += val(coefficients[140] + coefficients[141]adjustments[13]).
res := addmod(res, mulmod(val, add(/*coefficients[140]*/ mload(0x15c0), mulmod(/*coefficients[141]*/ mload(0x15e0),
res := addmod(res, mulmod(val, add(/*coefficients[140]*/ mload(0x15c0), mulmod(/*coefficients[141]*/ mload(0x15e0),
31,478
21
// max fee rate MUST <=10%
require(fr >= 10); feeRate = fr;
require(fr >= 10); feeRate = fr;
31,194
45
// Returns the mask for the provided token/token Token to returns the mask for
function tokenMasksMap(address token) external view returns (uint256);
function tokenMasksMap(address token) external view returns (uint256);
26,119
50
// Return ethereum address /
address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
24,436
43
// Calculate D
s := mulmod( mload(add(pProof, pEval_a)), mload(add(pMem, pV1)), q) g1_mulSetC(p, Qlx, Qly, s) s := mulmod( s, mload(add(pProof, pEval_b)), q) g1_mulAccC(p, Qmx, Qmy, s) s := mulmod( mload(add(pProof, pEval_b)), mload(add(pMem, pV1)), q) g1_mulAccC(p, Qrx, Qry, s) s := mulmod( mload(add(pProof, pEval_c)), mload(add(pMem, pV1)), q)
s := mulmod( mload(add(pProof, pEval_a)), mload(add(pMem, pV1)), q) g1_mulSetC(p, Qlx, Qly, s) s := mulmod( s, mload(add(pProof, pEval_b)), q) g1_mulAccC(p, Qmx, Qmy, s) s := mulmod( mload(add(pProof, pEval_b)), mload(add(pMem, pV1)), q) g1_mulAccC(p, Qrx, Qry, s) s := mulmod( mload(add(pProof, pEval_c)), mload(add(pMem, pV1)), q)
24,157
8
// Collects Axialtokens
IMasterChefAxialV2(masterChefAxialV3).deposit(poolId, 0); uint256 _axial = IERC20(axial).balanceOf(address(this)); if (_axial > 0) {
IMasterChefAxialV2(masterChefAxialV3).deposit(poolId, 0); uint256 _axial = IERC20(axial).balanceOf(address(this)); if (_axial > 0) {
16,780
48
// Return address' authorization status /
function isAuthorized(address adr) public view returns (bool) { return authorizations[adr]; }
function isAuthorized(address adr) public view returns (bool) { return authorizations[adr]; }
10,729
237
// If time has passed for 1 week since last snapshot and market is open
if (snapshotTime.add(SNAPSHOT_DURATION) <= block.timestamp) {
if (snapshotTime.add(SNAPSHOT_DURATION) <= block.timestamp) {
49,193
23
// The total amount of funds that the prize pool can hold.
uint256 public liquidityCap;
uint256 public liquidityCap;
38,812
69
// allow contract to receive HYDRO tokens
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public { require(msg.sender == _tokenAddress, "Malformed inputs."); require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract."); // depositing to an EIN if (_bytes.length <= 32) { require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership."); uint recipient; if (_bytes.length < 32) { recipient = identityRegistry.getEIN(sender); } else { recipient = abi.decode(_bytes, (uint)); require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist."); } deposits[recipient] = deposits[recipient].add(amount); emit SnowflakeDeposit(sender, recipient, amount); } // transferring to a via else { ( bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes ) = abi.decode(_bytes, (bool, address, address, uint, bytes)); require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership."); SnowflakeViaInterface viaContract = SnowflakeViaInterface(via); if (isTransfer) { viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes); emit SnowflakeTransferToVia(resolver, via, to, amount); } else { address payable payableTo = address(to); viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes); emit SnowflakeWithdrawToVia(resolver, via, address(to), amount); } } }
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public { require(msg.sender == _tokenAddress, "Malformed inputs."); require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract."); // depositing to an EIN if (_bytes.length <= 32) { require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership."); uint recipient; if (_bytes.length < 32) { recipient = identityRegistry.getEIN(sender); } else { recipient = abi.decode(_bytes, (uint)); require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist."); } deposits[recipient] = deposits[recipient].add(amount); emit SnowflakeDeposit(sender, recipient, amount); } // transferring to a via else { ( bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes ) = abi.decode(_bytes, (bool, address, address, uint, bytes)); require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership."); SnowflakeViaInterface viaContract = SnowflakeViaInterface(via); if (isTransfer) { viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes); emit SnowflakeTransferToVia(resolver, via, to, amount); } else { address payable payableTo = address(to); viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes); emit SnowflakeWithdrawToVia(resolver, via, address(to), amount); } } }
13,556
102
// Add burner, only owner can add burner./
function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); }
function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); }
4,345
5
// ========================================/Receives burn command from Wallet;//Burn is performed by Wallet, not by Root owner;//amount - Amount of tokens to burn;/senderOwnerAddress - Sender Wallet owner address to calculate and verify Wallet address;/initiatorAddress - Transaction initiator (e.g. Multisig) to return the unspent change;
function burn(uint128 amount, address senderOwnerAddress, address initiatorAddress) external;
function burn(uint128 amount, address senderOwnerAddress, address initiatorAddress) external;
7,068
122
// Mint the required tokens
couponToken.mint(users[i], tokens);
couponToken.mint(users[i], tokens);
50,064
93
// Next we need to calculate our percent of pTokens
bool _takeAll = false; if(_share == _total){ _takeAll = true; // Remove everything to this user }
bool _takeAll = false; if(_share == _total){ _takeAll = true; // Remove everything to this user }
49,495
322
// check if this failed incase we borrow into liquidation
require(cToken.mint(bal) == 0, "mint error");
require(cToken.mint(bal) == 0, "mint error");
13,200
3
// withdraw, withdraws tokens, if amount is 0 then the balance if fetched and use as amount. if token is 0 then ETH is used. This is useless for most users, this just allows the owner to unstuck any stuck token. This can't be reached while regular trading, only wrong transfers would yield coins reachable here.
function withdraw(IERC20 token, uint256 amount) external onlyOwner { if (amount == 0) { amount = token.balanceOf(address(this)); } }
function withdraw(IERC20 token, uint256 amount) external onlyOwner { if (amount == 0) { amount = token.balanceOf(address(this)); } }
27,028
129
// Transfer renBTC to strategy so strategy can complete the swap.
renBTC.safeTransfer(strategy, _amount); try ISwapStrategy(strategy).swapTokens(address(renBTC), address(wBTC), _amount, _slippage) { return true; } catch (bytes memory _error) {
renBTC.safeTransfer(strategy, _amount); try ISwapStrategy(strategy).swapTokens(address(renBTC), address(wBTC), _amount, _slippage) { return true; } catch (bytes memory _error) {
39,297
14
// Return data with length of size at pointers position
return(ptr, size)
return(ptr, size)
2,200
246
// Explicitly set `owners` to eliminate loops in future calls of ownerOf(). /
function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; }
function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; }
7,013
50
// Only this address can accept and end games.
address public serverAddress;
address public serverAddress;
28,434
35
// {IERC20-approve}, and its usage is discouraged. Whenever possible, use {safeIncreaseAllowance} and{safeDecreaseAllowance} instead. /
function safeApprove( IERC20 token, address spender, uint256 value ) internal {
function safeApprove( IERC20 token, address spender, uint256 value ) internal {
8,063
28
// Wraps the call to execute() on Connext and pays either the caller or hardcoded relayer from thiscontract's balance for completing the transaction._args - ExecuteArgs arguments. _fee - Fee to be paid to relayer.return transferId - The transfer ID of the crosschain transfer. Should match the xcall's transfer ID in order forreconciliation to occur. /
function execute(ExecuteArgs calldata _args, uint256 _fee) external onlyRelayer nonReentrant returns (bytes32 transferId)
function execute(ExecuteArgs calldata _args, uint256 _fee) external onlyRelayer nonReentrant returns (bytes32 transferId)
36,627
104
// The swap router, modifiable. Will be changed to SingSwap's router when our own AMM release
IUniswapV2Router02 public apolloSwapRouter; IBank public bank; address public masterChef;
IUniswapV2Router02 public apolloSwapRouter; IBank public bank; address public masterChef;
30,626
35
// Usual token descriptors.
string constant public name = "Amber Token"; uint8 constant public decimals = 18; string constant public symbol = "AMB";
string constant public name = "Amber Token"; uint8 constant public decimals = 18; string constant public symbol = "AMB";
13,508
8
// The Primitive oracle aggregation contract to grab any (supported) underlying price.
IProxyPriceProvider public priceProvider;
IProxyPriceProvider public priceProvider;
40,067
637
// deposits The underlying asset into the reserve. A correspondingamount of the overlying asset (mTokens)is minted. _reserve the address of the reserve _amount the amount to be deposited _referralCode integrators are assigned a referral code and canpotentially receive rewards. /
{ uint256 curBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender); bool isFirstDeposit = (curBalance == 0); core.updateStateOnDeposit( _reserve, msg.sender, _amount, isFirstDeposit ); //minting mToken to user 1:1 with the specific exchange rate mToken mToken = mToken(core.getReservemTokenAddress(_reserve)); mToken.mintOnDeposit(msg.sender, _amount); //transfer to the core contract core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount); //solium-disable-next-line emit Deposit( _reserve, msg.sender, _amount, _referralCode, block.timestamp ); }
{ uint256 curBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender); bool isFirstDeposit = (curBalance == 0); core.updateStateOnDeposit( _reserve, msg.sender, _amount, isFirstDeposit ); //minting mToken to user 1:1 with the specific exchange rate mToken mToken = mToken(core.getReservemTokenAddress(_reserve)); mToken.mintOnDeposit(msg.sender, _amount); //transfer to the core contract core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount); //solium-disable-next-line emit Deposit( _reserve, msg.sender, _amount, _referralCode, block.timestamp ); }
9,885
53
// See {BEP20-approve}. Requirements: - `spender` cannot be the zero address. /
function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; }
function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; }
10,312
15
// 帐户的余额列表
mapping (address => uint256) _balances;
mapping (address => uint256) _balances;
23,372
356
// Harvest CRV, CVX, cvxCRV, 3CRV, and extra rewards tokens from staking positions Note: Always claim extras
baseRewardsPool.getReward(address(this), true); if (cvxCrvRewardsPool.earned(address(this)) > 0) { cvxCrvRewardsPool.getReward(address(this), true); }
baseRewardsPool.getReward(address(this), true); if (cvxCrvRewardsPool.earned(address(this)) > 0) { cvxCrvRewardsPool.getReward(address(this), true); }
13,495
101
// Put this skin on sale
putOnSale(nextSkinId, salePrice); nextSkinId++; numSkinOfAccounts[coo] += 1; skinCreatedNum += 1;
putOnSale(nextSkinId, salePrice); nextSkinId++; numSkinOfAccounts[coo] += 1; skinCreatedNum += 1;
56,210
0
// Interface of the tokens factory eternal storage/
contract ITFStorage { /// Events emmiters. Write info about any state changes to the log. /// Allowed only for the Tokens Factory. // Emit when added new token strategy function emitStrategyAdded(bytes32 standard, address strategy) public; // Emit when token strategy removed from tokens factory function emitStrategyRemoved(bytes32 standard, address strategy) public; // Emit when strategy was updates function emitStrategyUpdated( bytes32 standard, address oldStrategy, address newStrategy ) public; // Emit when created new token function emitCreatedToken( address tokenAddress, address issuer, string memory name, string memory symbol, bytes memory issuerName, uint8 decimals, uint totalSupply, bytes32 standard ) public; /// Methods which updates the storage. Allowed only for the Tokens Factory. /** * @notice Add token deployment strategy * @param strategyAddress Deployment strategy address * @param standard Token standard * @param index Index in the strategies list */ function saveDeploymentStrategy( address strategyAddress, bytes32 standard, uint index ) public; /** * @notice Add issuer address * @param issuerAddress Address of the token issuer * @param tokenAddress Token address */ function setIssuerForToken( address issuerAddress, address tokenAddress ) public; /** * @notice Save token with token standard * @param tokenAddress Token address * @param standard Standard of the token */ function setTokenStandard(address tokenAddress, bytes32 standard) public; /** * @notice Add new strategy * @param standard Deployment strategy address */ function addDeploymentStrategy(bytes32 standard) public; /** * @notice Set deployment strategy on the specific index * @param standard Deployment strategy * @param index Index which will be updated */ function updateStrategyByindex(bytes32 standard, uint index) public; /** * @notice Update address of the deployment strategy * @param standard Deployment strategy * @param newAddress Address of the new token deployemnt strategy */ function updateStrategyAddress(bytes32 standard, address newAddress) public; /** * @notice Update index of the deployment strategy * @param standard Deployment strategy * @param index New index */ function updateStrategyIndex(bytes32 standard, uint index) public; /** * @notice Update supported standarts length * @param newLength New array length */ function updateSupportedStandardsLength(uint newLength) public; /** * @notice Remove deployment strategy from the list * @param index Index of the deployment strategy which will be removed */ function removeStandard(uint index) public; /** * @notice Remove deployment strategy * @param standard Standard which will be removed */ function removeDeploymentStrategy(bytes32 standard) public; /// Getters. Public methods which are allowed for anyone. /** * @notice Returns the number of standards supported. */ function supportedStandardsLength() public view returns (uint); /** * @notice Get supported standard by index * @param index Index of the standard in the array */ function getStandardByIndex(uint index) public view returns (bytes32); /** * @notice Returns deployment strategy index * @param standard Standard of the deployment strategy */ function getStandardIndex(bytes32 standard) public view returns (uint); /** * @notice Reurns deployment strategy address * @param standard Standard of the deployment strategy */ function getStandardAddress(bytes32 standard) public view returns (address); /** * @notice Returns standard of the token * @param token Address of the token */ function getTokenStandard(address token) public view returns (bytes32); /** * @notice Returns address of the token issuer * @param token Token address */ function getIssuerAddress(address token) public view returns (address); }
contract ITFStorage { /// Events emmiters. Write info about any state changes to the log. /// Allowed only for the Tokens Factory. // Emit when added new token strategy function emitStrategyAdded(bytes32 standard, address strategy) public; // Emit when token strategy removed from tokens factory function emitStrategyRemoved(bytes32 standard, address strategy) public; // Emit when strategy was updates function emitStrategyUpdated( bytes32 standard, address oldStrategy, address newStrategy ) public; // Emit when created new token function emitCreatedToken( address tokenAddress, address issuer, string memory name, string memory symbol, bytes memory issuerName, uint8 decimals, uint totalSupply, bytes32 standard ) public; /// Methods which updates the storage. Allowed only for the Tokens Factory. /** * @notice Add token deployment strategy * @param strategyAddress Deployment strategy address * @param standard Token standard * @param index Index in the strategies list */ function saveDeploymentStrategy( address strategyAddress, bytes32 standard, uint index ) public; /** * @notice Add issuer address * @param issuerAddress Address of the token issuer * @param tokenAddress Token address */ function setIssuerForToken( address issuerAddress, address tokenAddress ) public; /** * @notice Save token with token standard * @param tokenAddress Token address * @param standard Standard of the token */ function setTokenStandard(address tokenAddress, bytes32 standard) public; /** * @notice Add new strategy * @param standard Deployment strategy address */ function addDeploymentStrategy(bytes32 standard) public; /** * @notice Set deployment strategy on the specific index * @param standard Deployment strategy * @param index Index which will be updated */ function updateStrategyByindex(bytes32 standard, uint index) public; /** * @notice Update address of the deployment strategy * @param standard Deployment strategy * @param newAddress Address of the new token deployemnt strategy */ function updateStrategyAddress(bytes32 standard, address newAddress) public; /** * @notice Update index of the deployment strategy * @param standard Deployment strategy * @param index New index */ function updateStrategyIndex(bytes32 standard, uint index) public; /** * @notice Update supported standarts length * @param newLength New array length */ function updateSupportedStandardsLength(uint newLength) public; /** * @notice Remove deployment strategy from the list * @param index Index of the deployment strategy which will be removed */ function removeStandard(uint index) public; /** * @notice Remove deployment strategy * @param standard Standard which will be removed */ function removeDeploymentStrategy(bytes32 standard) public; /// Getters. Public methods which are allowed for anyone. /** * @notice Returns the number of standards supported. */ function supportedStandardsLength() public view returns (uint); /** * @notice Get supported standard by index * @param index Index of the standard in the array */ function getStandardByIndex(uint index) public view returns (bytes32); /** * @notice Returns deployment strategy index * @param standard Standard of the deployment strategy */ function getStandardIndex(bytes32 standard) public view returns (uint); /** * @notice Reurns deployment strategy address * @param standard Standard of the deployment strategy */ function getStandardAddress(bytes32 standard) public view returns (address); /** * @notice Returns standard of the token * @param token Address of the token */ function getTokenStandard(address token) public view returns (bytes32); /** * @notice Returns address of the token issuer * @param token Token address */ function getIssuerAddress(address token) public view returns (address); }
20,320
262
// Interface for the SignatureValidator helper, used to support meta-transactions. /
interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); }
interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); }
4,976
94
// Gets the price for the current supply
uint256 price = _initializeCurve(initialSupply);
uint256 price = _initializeCurve(initialSupply);
37,424
1
// constructs an `FixedPointInt` from an unscaled int, e.g., `b=5` gets stored internally as `527`. a int to convert into a FixedPoint.return the converted FixedPoint. /
function fromUnscaledInt(int256 a) internal pure returns (FixedPointInt memory) { return FixedPointInt(a.mul(SCALING_FACTOR)); }
function fromUnscaledInt(int256 a) internal pure returns (FixedPointInt memory) { return FixedPointInt(a.mul(SCALING_FACTOR)); }
42,535
264
// Overload {renounceRole} to track enumerable memberships /
function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); }
function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); }
30,700
59
// See {Pausable-_pause}. /
function pauseContract() public virtual onlyPauser { _pause(); }
function pauseContract() public virtual onlyPauser { _pause(); }
26,100
39
// Sets or unsets the approval of a given operator An operator is allowed to transfer all tokens of the sender on their behalf.to operator address to set the approvalapproved representing the status of the approval to be set/
function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); }
function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); }
5,597