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
9
// Global surplus and debt Buffer
IBuffer public immutable buffer;
IBuffer public immutable buffer;
26,545
43
// delete the grant
delete _grants()[_who];
delete _grants()[_who];
27,468
228
// Updates sales addresses for the platform and render providers tothe input parameters. _renderProviderPrimarySalesAddress Address of new primary salespayment address. _renderProviderSecondarySalesAddress Address of new secondary salespayment address. _platformProviderPrimarySalesAddress Address of new primary salespayment address. _platformProviderSecondarySalesAddress Address of new secondary salespayment address. Note that this method does not check that the input address isnot `address(0)`, as it is expected that callers of this method shouldperform input validation where applicable. /
function _updateProviderSalesAddresses( address _renderProviderPrimarySalesAddress, address _renderProviderSecondarySalesAddress, address _platformProviderPrimarySalesAddress, address _platformProviderSecondarySalesAddress
function _updateProviderSalesAddresses( address _renderProviderPrimarySalesAddress, address _renderProviderSecondarySalesAddress, address _platformProviderPrimarySalesAddress, address _platformProviderSecondarySalesAddress
13,132
3
// Error thrown when an invalid signature is provided for a claim operation. /
error InvalidSignature();
error InvalidSignature();
10,304
180
// Returns the amount out received for a given exact input but for a swap of a single pool/tokenIn The token being swapped in/tokenOut The token being swapped out/fee The fee of the token pool to consider for the pair/amountIn The desired input amount/sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap/ return amountOut The amount of `tokenOut` that would be received
function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut);
function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut);
10,312
479
// swap and liquify
if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(swapRouter) != address(0) && swapPair != address(0) && sender != swapPair && sender != owner() && sender != operator() ) { swapAndLiquify();
if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(swapRouter) != address(0) && swapPair != address(0) && sender != swapPair && sender != owner() && sender != operator() ) { swapAndLiquify();
679
158
// Refund 15,000 gas per slot. amount number of slots to free /
function gasRefund15(uint256 amount) internal { // refund gas assembly { // get number of free slots let offset := sload(0xfffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } // get location of first slot let location := add(offset, 0xfffff) // calculate loop end let end := sub(location, amount) // loop until end is reached for { } gt(location, end) { location := sub(location, 1) } { // set storage location to zero // this refunds 15,000 gas sstore(location, 0) } // store new number of free slots sstore(0xfffff, sub(offset, amount)) } }
function gasRefund15(uint256 amount) internal { // refund gas assembly { // get number of free slots let offset := sload(0xfffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } // get location of first slot let location := add(offset, 0xfffff) // calculate loop end let end := sub(location, amount) // loop until end is reached for { } gt(location, end) { location := sub(location, 1) } { // set storage location to zero // this refunds 15,000 gas sstore(location, 0) } // store new number of free slots sstore(0xfffff, sub(offset, amount)) } }
18,835
14
// We check that the address that is trying to assign a diploma is the one that created the diploma.
if(isAutorized(degrees[_idDegree].idSchool,msg.sender)!=0){ diplomaCount ++; diplomas[diplomaCount] = Diploma(_idDegree,_idStudent,_valid,_creator); emit DiplomaCreated(_idDegree,_idStudent,_valid,_creator); }
if(isAutorized(degrees[_idDegree].idSchool,msg.sender)!=0){ diplomaCount ++; diplomas[diplomaCount] = Diploma(_idDegree,_idStudent,_valid,_creator); emit DiplomaCreated(_idDegree,_idStudent,_valid,_creator); }
36,229
41
// Include an address to blackList.Can only be called by the current operator. /
function setIncludeToBlackList(address _account) public onlyOwner { _includeToBlackList[_account] = true; }
function setIncludeToBlackList(address _account) public onlyOwner { _includeToBlackList[_account] = true; }
20,928
6
// Redeem tokens from Staked AAVE Redeem AAVE tokens from Staked AAVE after cooldown period is over amount The amount of AAVE to redeem. uint(-1) for max. getId ID to retrieve amount. setId ID stores the amount of tokens redeemed. /
function redeem( uint256 amount, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam)
function redeem( uint256 amount, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam)
53,380
619
// Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. /
function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; }
function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; }
5,152
18
// 从一个账户转移到另一个账户,前提是需要有允许转移的余额
function transferFrom( address _from, address _to, uint256 _amount
function transferFrom( address _from, address _to, uint256 _amount
47,349
110
// Start looping from the latest tax receiver
uint256 currentSecondaryReceiver = latestSecondaryReceiver;
uint256 currentSecondaryReceiver = latestSecondaryReceiver;
20,676
3
// Total number of tokens this contract has ever received /
uint256 public totalTokensReceived;
uint256 public totalTokensReceived;
20,080
10
// Evaluates the header difficulties in a proof/ Uses the light oracle to source recent difficulty/ _bitcoinHeaders The header chain to evaluate/ return True if acceptable, otherwise revert
function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view { uint256 _reqDiff; uint256 _current = currentBlockDifficulty(_d); uint256 _previous = previousBlockDifficulty(_d); uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty(); if (_firstHeaderDiff == _current) { _reqDiff = _current; } else if (_firstHeaderDiff == _previous) { _reqDiff = _previous; } else { revert("not at current or previous difficulty"); } uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain(); require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain"); require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain"); require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header"); /* TODO: make this better than 6 */ require( _observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()), "Insufficient accumulated difficulty in header chain" ); }
function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view { uint256 _reqDiff; uint256 _current = currentBlockDifficulty(_d); uint256 _previous = previousBlockDifficulty(_d); uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty(); if (_firstHeaderDiff == _current) { _reqDiff = _current; } else if (_firstHeaderDiff == _previous) { _reqDiff = _previous; } else { revert("not at current or previous difficulty"); } uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain(); require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain"); require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain"); require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header"); /* TODO: make this better than 6 */ require( _observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()), "Insufficient accumulated difficulty in header chain" ); }
48,869
0
// uint256 id;
address school; string name;
address school; string name;
15,299
300
// Checks if the new value given for the parameter is consistent (it should be inferior to 1/ if it corresponds to a ratio)/fees Value of the new parameter to check
modifier onlyCompatibleFees(uint64 fees) { require(fees <= BASE_PARAMS, "4"); _; }
modifier onlyCompatibleFees(uint64 fees) { require(fees <= BASE_PARAMS, "4"); _; }
34,324
147
// Returns the hash of the ABI-encoded EIP-712 message for the `CastDisapproval` domain, which can be used to/ recover the signer.
function _getCastDisapprovalTypedDataHash( address policyholder, uint8 role, ActionInfo calldata actionInfo, string calldata reason
function _getCastDisapprovalTypedDataHash( address policyholder, uint8 role, ActionInfo calldata actionInfo, string calldata reason
33,788
1
// Return true when the account belongs to a Customer; otherwise false.
mapping(address => bool) public customers;
mapping(address => bool) public customers;
48,931
13
// Throws if called by any account that's not whitelisted. /
modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; }
modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; }
28,620
22
// Set token uri for a token of an extension /
function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; }
function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; }
28,563
8
// The total number of resolves being staked in this contract
uint256 public dissolvingResolves;
uint256 public dissolvingResolves;
32,865
12
// avoid stack too deep
availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor
availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor
34,391
81
// Fee permille of Monetha fee. 1 permille = 0.1 % 15 permille = 1.5% /
uint public constant FEE_PERMILLE = 15;
uint public constant FEE_PERMILLE = 15;
39,695
1
// tokenId => price
mapping (uint256 => TokenInfo) public tokenInfo; uint256[] public marketTokens;
mapping (uint256 => TokenInfo) public tokenInfo; uint256[] public marketTokens;
28,708
261
// ========== VIEW FUNCTIONS ========== // There is a motion in progress on the specifiedaccount, and votes are being accepted in that motion. /
function motionVoting(uint motionID) public view returns (bool)
function motionVoting(uint motionID) public view returns (bool)
39,660
27
// Decrease the amount of tokens that an owner allowed to a spender.approve should be called when _allowed[msg.sender][spender] == 0. To decrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.solEmits an Approval event. spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by. /
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool)
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool)
35,562
69
// deploy a new token contract with no balance
StarToken public immutable startoken; uint256 constant public ONE_STAR = 1e18;
StarToken public immutable startoken; uint256 constant public ONE_STAR = 1e18;
73,837
7
// Minimum number of cast voted required for a proposal to be successful. Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view override(IGovernor, GovernorVotesQuorumFraction) returns (uint256) { return super.quorum(blockNumber); }
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view override(IGovernor, GovernorVotesQuorumFraction) returns (uint256) { return super.quorum(blockNumber); }
19,188
24
// Set owners
owners = _owners;
owners = _owners;
76,467
17
// Stores the content of a tray, i.e. all tiles
mapping(uint256 => TileData[TILES_PER_TRAY]) private tiles;
mapping(uint256 => TileData[TILES_PER_TRAY]) private tiles;
12,929
125
// cannot execute swap at insufficient balance
if (Token(trustedRewardTokenAddress).balanceOf(address(this)) < _tokensToBeSwapped) { return; }
if (Token(trustedRewardTokenAddress).balanceOf(address(this)) < _tokensToBeSwapped) { return; }
9,125
7
// finally, save messageData in outbound storage and emit `MessageAccepted` event
messages[nonce] = MessageData({ payload: messagePayload, fee: fee // a lowest fee may be required and how to set it });
messages[nonce] = MessageData({ payload: messagePayload, fee: fee // a lowest fee may be required and how to set it });
22,146
13
// Update account `whitelisted` status./account Account to update./_whitelisted If 'true', `account` is `whitelisted`.
function updateWhitelist(address account, bool _whitelisted) external onlyOwner { whitelisted[account] = _whitelisted; emit UpdateWhitelist(account, _whitelisted); }
function updateWhitelist(address account, bool _whitelisted) external onlyOwner { whitelisted[account] = _whitelisted; emit UpdateWhitelist(account, _whitelisted); }
25,401
18
// Gets the approved address for a token ID, or zero if no address set Reverts if the token ID does not exist.tokenId uint256 ID of the token to query the approval ofreturn address currently approved for the given token ID /
function getApproved(uint256 tokenId) public view returns (address);
function getApproved(uint256 tokenId) public view returns (address);
27,638
44
// GuildApp Contract/RaidGuild/Guild app allows you to monetize content and receive recurring subscriptions/uses ERC721 standard to tokenize subscriptions
contract GuildApp is ERC721Upgradeable, AccessControlUpgradeable, SignatureDecoder, IGuild { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using StringsUpgradeable for uint256; using AddressUpgradeable for address; struct Subscription { uint256 tokenId; uint256 expirationTimestamp; } /// @dev flag the contract as initialized bool public override initialized; /// @dev flag to keep track if the Guild is accepting subscriptions bool public isActive; /// @dev CID of Guild metadata stored on i.e. IPFS string public metadataCID; /// @dev current active asset accepted for subscriptions address public tokenAddress; /// @dev current guild subcription price uint256 public subPrice; /// @dev subscription period in seconds (i.e. monthly) uint256 public subscriptionPeriod; /// @dev subscriptions list mapping(address => Subscription) public subscriptionByOwner; /// @dev assets used for subscription payments mapping(address => EnumerableSetUpgradeable.AddressSet) private _approvedTokens; /// @dev Gnosis Safe AllowanceModule address private _allowanceModule; /// @dev next subscriptionID uint256 private _nextId; modifier onlyIfActive() { require(isActive, "GuildApp: The Guild is disabled"); _; } modifier onlyGuildAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "GuildApp: Sender doesn't have an Admin role"); _; } event InitializedGuild(address _creator, address _tokenAddress, uint256 _subPrice, uint256 _subscriptionPeriod, GuildMetadata _metadata); event UpdatedMetadata(string _metadataURI); event PausedGuild(bool _isPaused); event Withdraw(address _tokenAddress, address beneficiary, uint256 _amount); event SubscriptionPriceChanged(address _tokenAddress, uint256 _subPrice); event NewSubscription(address _subscriber, uint256 _tokenId, uint256 _value, uint256 expiry, bytes _data); event RenewSubscription(address _subscriber, uint256 _tokenId, uint256 _value, uint256 expiry, bytes _data); event Unsubscribed(uint256 _tokenId); function __GuildApp_init_unchained(address _creator, string memory baseURI, string memory _metadataCID, address _tokenAddress, uint256 _subPrice, uint256 _subscriptionPeriod, address allowanceModule ) internal initializer { require( _tokenAddress == address(0) || (_tokenAddress != address(0) && IERC20Upgradeable(_tokenAddress).totalSupply() > 0), "GuildApp: Invalid token"); isActive = true; metadataCID = _metadataCID; tokenAddress = _tokenAddress; _approvedTokens[address(this)].add(_tokenAddress); subPrice = _subPrice; subscriptionPeriod =_subscriptionPeriod; _setBaseURI(baseURI); _setupRole(DEFAULT_ADMIN_ROLE, _creator); _nextId = 0; _allowanceModule = allowanceModule; initialized = true; } /// @notice Initialize a new GuildApp contract /// @dev Initialize inherited contracts and perform base GuildApp setup /// @param _creator GuildApp owner /// @param _tokenAddress asset to be accepted for payments /// @param _subPrice subscription price in WEI /// @param _subscriptionPeriod subscription period in seconds /// @param _metadata guild metadata CID /// @param allowanceModule safe module address function initialize(address _creator, address _tokenAddress, uint256 _subPrice, uint256 _subscriptionPeriod, GuildMetadata memory _metadata, address allowanceModule ) public override initializer { __AccessControl_init(); __ERC721_init(_metadata.name, _metadata.symbol); __GuildApp_init_unchained(_creator, _metadata.baseURI, _metadata.metadataCID, _tokenAddress, _subPrice, _subscriptionPeriod, allowanceModule); emit InitializedGuild(_creator, _tokenAddress, _subPrice, _subscriptionPeriod, _metadata); } /// @notice Enable/Disable your GuildApp to accept subscription/payments /// @dev Flag contract as active or not. Only the guild owner can execute /// @param pause boolean to flag the Guild as active function pauseGuild(bool pause) external override onlyGuildAdmin { require(isActive == pause, "GuildApp: Guild already in that state"); emit PausedGuild(pause); isActive = !pause; } /// @notice Withdraw balance from the Guild /// @dev Only the guild owner can execute /// @param _tokenAddress token asset to withdraw some balance /// @param _amount amount to be withdraw in wei /// @param _beneficiary beneficiary to send funds. If 0x is specified, funds will be sent to the guild owner function withdraw( address _tokenAddress, uint256 _amount, address _beneficiary ) public override onlyGuildAdmin { require(_approvedTokens[address(this)].contains(_tokenAddress), "GuildApp: Token has not been approved"); uint256 outstandingBalance = guildBalance(_tokenAddress); require(_amount > 0 && outstandingBalance >= _amount, "GuildApp: Not enough balance to withdraw"); address beneficiary = _beneficiary != address(0) ? _beneficiary : _msgSender(); emit Withdraw(tokenAddress, beneficiary, _amount); IERC20Upgradeable(tokenAddress).safeTransfer(beneficiary, _amount); } /// @notice Update Guild subscription token and price /// @dev can be executed only by guild owner and if guild is active /// @param _tokenAddress token to be accepted for payments /// @param _newSubPrice new subscription price function updateSubscriptionPrice( address _tokenAddress, uint256 _newSubPrice ) public override onlyGuildAdmin onlyIfActive { tokenAddress = _tokenAddress; _approvedTokens[address(this)].add(_tokenAddress); subPrice = _newSubPrice; emit SubscriptionPriceChanged(tokenAddress, subPrice); } /// @notice Validate signature belongs to a Safe owner /// @dev Currently disabled /// @param _safeAddress Gnosis Safe contract /// @param _transferhash Tx hash used for signing /// @param _data owner signature function _validateSignature( address _safeAddress, bytes32 _transferhash, bytes memory _data ) internal view { // Validate signature belongs to a Safe owner IGnosisSafe safe = IGnosisSafe(_safeAddress); (uint8 v, bytes32 r, bytes32 s) = signatureSplit(_data, 0); address safeOwner; if (v > 30) { // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover safeOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _transferhash)), v - 4, r, s); } else { // Use ecrecover with the messageHash for EOA signatures safeOwner = ecrecover(_transferhash, v, r, s); } require(safe.isOwner(safeOwner), "GuildApp: Signer is not a safe owner"); } /// @notice New subscription to the Guild /// @dev Accepts contributions from EOA and Safes w/ enabledAllowanceModule. /// @param _subscriber Account address /// @param _tokenURI URI of subsription metadata /// @param _value subsription payment value send by a user /// @param _data allowance Tx signature used by the safe AllowanceModule function subscribe( address _subscriber, string memory _tokenURI, uint256 _value, bytes memory _data ) public payable override onlyIfActive { address subscriber = _subscriber; uint256 value = _value; if (_data.length == 0) { // condition if not using a safe require((tokenAddress != address(0) && msg.value == 0) || (tokenAddress == address(0) && msg.value == value), "GuildApp: incorrect msg.value"); } else { // require(address(subscriber).isContract() && // keccak256(abi.encodePacked(IGnosisSafe(subscriber).NAME())) == keccak256(abi.encodePacked("Gnosis Safe")), // "GuildApp: Sender is not a Gnosis Safe"); require(msg.value == 0, "GuildApp: ETH should be transferred via AllowanceModule"); } require(value >= subPrice, "GuildApp: Insufficient value sent"); Subscription storage subs = subscriptionByOwner[subscriber]; if (subs.tokenId == 0) { require(subscriber == _msgSender(), "GuildApp: msg.sender must be the subscriber"); _nextId = _nextId.add(1); subs.tokenId = _nextId; _safeMint(subscriber, subs.tokenId); _setTokenURI(subs.tokenId, string(abi.encodePacked(_tokenURI, "#", subs.tokenId.toString()))); subs.expirationTimestamp = subscriptionPeriod.add(block.timestamp); emit NewSubscription(subscriber, subs.tokenId, value, subs.expirationTimestamp, _data); } else { require(subs.expirationTimestamp < block.timestamp, "GuildApp: sill an active subscription"); // renew or extend subscription subs.expirationTimestamp = subs.expirationTimestamp.add(block.timestamp); emit RenewSubscription(subscriber, subs.tokenId, value, subs.expirationTimestamp, _data); } if (tokenAddress != address(0) && _data.length == 0) { // Handle payment using EOA allowances IERC20Upgradeable(tokenAddress).safeTransferFrom(subscriber, address(this), value); return; } // Else Handle payment using Safe Allowance Module require(_allowanceModule != address(0), "GuildApp: Guild does not support Safe Allowances"); IAllowanceModule safeModule = IAllowanceModule(_allowanceModule); uint256[5] memory allowance = safeModule.getTokenAllowance(subscriber, address(this), tokenAddress); // allowance.amout - allowance.spent require(allowance[0] - allowance[1] >= value, "GuildApp: Not enough allowance"); safeModule.executeAllowanceTransfer( subscriber, // MUST be a safe tokenAddress, payable(this), // to uint96(value), address(0), // payment token 0, // payment address(this), // delegate "" // bypass signature check as contract signatures are not supported by the module ); } /// @notice Unsubscribe to the Guild /// @dev NFT token is burned /// @param _tokenId Subscription ID function unsubscribe(uint256 _tokenId) public override { require(_exists(_tokenId), "GuildApp: Subscription does not exist"); address subscriber = _msgSender(); require(subscriber == ownerOf(_tokenId), "GuildApp: Caller is not the owner of the subscription"); _burn(_tokenId); Subscription storage subs = subscriptionByOwner[subscriber]; subs.tokenId = 0; subs.expirationTimestamp = 0; emit Unsubscribed(_tokenId); } /// @notice Get the Guild balance of a specified token /// @param _tokenAddress asset address /// @return current guild balanceOf `_tokenAddres` function guildBalance(address _tokenAddress) public view override returns (uint256) { if (_approvedTokens[address(this)].contains(_tokenAddress)) { if (tokenAddress != address(0)) { return IERC20Upgradeable(tokenAddress).balanceOf(address(this)); } return address(this).balance; } return 0; } /// @notice Return if `_holder` owns a subscription with ID `_tokenId` /// @param _tokenId subsription ID /// @param _holder user address /// @return true if `_holder` owns the subscription function isSubscriptionOwner( uint256 _tokenId, address _holder ) public view override returns (bool) { return ownerOf(_tokenId) == _holder; } /// @notice Return true if `_account` has an active subscription /// @param _account subscriber address /// @return true if `_account` has an active subscription function hasActiveSubscription(address _account) public view override returns (bool) { return subscriptionByOwner[_account].expirationTimestamp > block.timestamp; } /// @notice Get Subscription ID from `_account` /// @param _account subscriber address /// @return subscription ID that belong to `_account` function getSubscriptionIdFor(address _account) public view override returns (uint256) { return subscriptionByOwner[_account].tokenId; } /// @notice Get the subscription expiration timestamp /// @param _account subscriber address /// @return expiration timestamp in seconds function getSubscriptionExpiryFor(address _account) external view override returns (uint256) { return subscriptionByOwner[_account].expirationTimestamp; } /// @notice Return list of approved tokens in the guild /// @return array of assets aproved to the Guild function approvedTokens() public view override returns (address[] memory) { address[] memory tokens = new address[](_approvedTokens[address(this)].length()); for (uint256 i = 0; i < _approvedTokens[address(this)].length(); i++) { tokens[i] = _approvedTokens[address(this)].at(i); } return tokens; } /// @notice Return Guild Metadata CID /// @return metadataCID (i.e. IPFS hash) function getMetadata() public view override returns (string memory) { string memory base = baseURI(); if (bytes(base).length == 0) { return metadataCID; } return string(abi.encodePacked(base, metadataCID)); } /// @notice Set Guild Metadata ID /// @dev Only the guild owner can execute /// @param _metadataCID new metadata CID function setMetadata(string memory _metadataCID) external override onlyGuildAdmin onlyIfActive { metadataCID = _metadataCID; emit UpdatedMetadata(getMetadata()); } receive() external payable { } uint256[50] private __gap; }
contract GuildApp is ERC721Upgradeable, AccessControlUpgradeable, SignatureDecoder, IGuild { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using StringsUpgradeable for uint256; using AddressUpgradeable for address; struct Subscription { uint256 tokenId; uint256 expirationTimestamp; } /// @dev flag the contract as initialized bool public override initialized; /// @dev flag to keep track if the Guild is accepting subscriptions bool public isActive; /// @dev CID of Guild metadata stored on i.e. IPFS string public metadataCID; /// @dev current active asset accepted for subscriptions address public tokenAddress; /// @dev current guild subcription price uint256 public subPrice; /// @dev subscription period in seconds (i.e. monthly) uint256 public subscriptionPeriod; /// @dev subscriptions list mapping(address => Subscription) public subscriptionByOwner; /// @dev assets used for subscription payments mapping(address => EnumerableSetUpgradeable.AddressSet) private _approvedTokens; /// @dev Gnosis Safe AllowanceModule address private _allowanceModule; /// @dev next subscriptionID uint256 private _nextId; modifier onlyIfActive() { require(isActive, "GuildApp: The Guild is disabled"); _; } modifier onlyGuildAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "GuildApp: Sender doesn't have an Admin role"); _; } event InitializedGuild(address _creator, address _tokenAddress, uint256 _subPrice, uint256 _subscriptionPeriod, GuildMetadata _metadata); event UpdatedMetadata(string _metadataURI); event PausedGuild(bool _isPaused); event Withdraw(address _tokenAddress, address beneficiary, uint256 _amount); event SubscriptionPriceChanged(address _tokenAddress, uint256 _subPrice); event NewSubscription(address _subscriber, uint256 _tokenId, uint256 _value, uint256 expiry, bytes _data); event RenewSubscription(address _subscriber, uint256 _tokenId, uint256 _value, uint256 expiry, bytes _data); event Unsubscribed(uint256 _tokenId); function __GuildApp_init_unchained(address _creator, string memory baseURI, string memory _metadataCID, address _tokenAddress, uint256 _subPrice, uint256 _subscriptionPeriod, address allowanceModule ) internal initializer { require( _tokenAddress == address(0) || (_tokenAddress != address(0) && IERC20Upgradeable(_tokenAddress).totalSupply() > 0), "GuildApp: Invalid token"); isActive = true; metadataCID = _metadataCID; tokenAddress = _tokenAddress; _approvedTokens[address(this)].add(_tokenAddress); subPrice = _subPrice; subscriptionPeriod =_subscriptionPeriod; _setBaseURI(baseURI); _setupRole(DEFAULT_ADMIN_ROLE, _creator); _nextId = 0; _allowanceModule = allowanceModule; initialized = true; } /// @notice Initialize a new GuildApp contract /// @dev Initialize inherited contracts and perform base GuildApp setup /// @param _creator GuildApp owner /// @param _tokenAddress asset to be accepted for payments /// @param _subPrice subscription price in WEI /// @param _subscriptionPeriod subscription period in seconds /// @param _metadata guild metadata CID /// @param allowanceModule safe module address function initialize(address _creator, address _tokenAddress, uint256 _subPrice, uint256 _subscriptionPeriod, GuildMetadata memory _metadata, address allowanceModule ) public override initializer { __AccessControl_init(); __ERC721_init(_metadata.name, _metadata.symbol); __GuildApp_init_unchained(_creator, _metadata.baseURI, _metadata.metadataCID, _tokenAddress, _subPrice, _subscriptionPeriod, allowanceModule); emit InitializedGuild(_creator, _tokenAddress, _subPrice, _subscriptionPeriod, _metadata); } /// @notice Enable/Disable your GuildApp to accept subscription/payments /// @dev Flag contract as active or not. Only the guild owner can execute /// @param pause boolean to flag the Guild as active function pauseGuild(bool pause) external override onlyGuildAdmin { require(isActive == pause, "GuildApp: Guild already in that state"); emit PausedGuild(pause); isActive = !pause; } /// @notice Withdraw balance from the Guild /// @dev Only the guild owner can execute /// @param _tokenAddress token asset to withdraw some balance /// @param _amount amount to be withdraw in wei /// @param _beneficiary beneficiary to send funds. If 0x is specified, funds will be sent to the guild owner function withdraw( address _tokenAddress, uint256 _amount, address _beneficiary ) public override onlyGuildAdmin { require(_approvedTokens[address(this)].contains(_tokenAddress), "GuildApp: Token has not been approved"); uint256 outstandingBalance = guildBalance(_tokenAddress); require(_amount > 0 && outstandingBalance >= _amount, "GuildApp: Not enough balance to withdraw"); address beneficiary = _beneficiary != address(0) ? _beneficiary : _msgSender(); emit Withdraw(tokenAddress, beneficiary, _amount); IERC20Upgradeable(tokenAddress).safeTransfer(beneficiary, _amount); } /// @notice Update Guild subscription token and price /// @dev can be executed only by guild owner and if guild is active /// @param _tokenAddress token to be accepted for payments /// @param _newSubPrice new subscription price function updateSubscriptionPrice( address _tokenAddress, uint256 _newSubPrice ) public override onlyGuildAdmin onlyIfActive { tokenAddress = _tokenAddress; _approvedTokens[address(this)].add(_tokenAddress); subPrice = _newSubPrice; emit SubscriptionPriceChanged(tokenAddress, subPrice); } /// @notice Validate signature belongs to a Safe owner /// @dev Currently disabled /// @param _safeAddress Gnosis Safe contract /// @param _transferhash Tx hash used for signing /// @param _data owner signature function _validateSignature( address _safeAddress, bytes32 _transferhash, bytes memory _data ) internal view { // Validate signature belongs to a Safe owner IGnosisSafe safe = IGnosisSafe(_safeAddress); (uint8 v, bytes32 r, bytes32 s) = signatureSplit(_data, 0); address safeOwner; if (v > 30) { // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover safeOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _transferhash)), v - 4, r, s); } else { // Use ecrecover with the messageHash for EOA signatures safeOwner = ecrecover(_transferhash, v, r, s); } require(safe.isOwner(safeOwner), "GuildApp: Signer is not a safe owner"); } /// @notice New subscription to the Guild /// @dev Accepts contributions from EOA and Safes w/ enabledAllowanceModule. /// @param _subscriber Account address /// @param _tokenURI URI of subsription metadata /// @param _value subsription payment value send by a user /// @param _data allowance Tx signature used by the safe AllowanceModule function subscribe( address _subscriber, string memory _tokenURI, uint256 _value, bytes memory _data ) public payable override onlyIfActive { address subscriber = _subscriber; uint256 value = _value; if (_data.length == 0) { // condition if not using a safe require((tokenAddress != address(0) && msg.value == 0) || (tokenAddress == address(0) && msg.value == value), "GuildApp: incorrect msg.value"); } else { // require(address(subscriber).isContract() && // keccak256(abi.encodePacked(IGnosisSafe(subscriber).NAME())) == keccak256(abi.encodePacked("Gnosis Safe")), // "GuildApp: Sender is not a Gnosis Safe"); require(msg.value == 0, "GuildApp: ETH should be transferred via AllowanceModule"); } require(value >= subPrice, "GuildApp: Insufficient value sent"); Subscription storage subs = subscriptionByOwner[subscriber]; if (subs.tokenId == 0) { require(subscriber == _msgSender(), "GuildApp: msg.sender must be the subscriber"); _nextId = _nextId.add(1); subs.tokenId = _nextId; _safeMint(subscriber, subs.tokenId); _setTokenURI(subs.tokenId, string(abi.encodePacked(_tokenURI, "#", subs.tokenId.toString()))); subs.expirationTimestamp = subscriptionPeriod.add(block.timestamp); emit NewSubscription(subscriber, subs.tokenId, value, subs.expirationTimestamp, _data); } else { require(subs.expirationTimestamp < block.timestamp, "GuildApp: sill an active subscription"); // renew or extend subscription subs.expirationTimestamp = subs.expirationTimestamp.add(block.timestamp); emit RenewSubscription(subscriber, subs.tokenId, value, subs.expirationTimestamp, _data); } if (tokenAddress != address(0) && _data.length == 0) { // Handle payment using EOA allowances IERC20Upgradeable(tokenAddress).safeTransferFrom(subscriber, address(this), value); return; } // Else Handle payment using Safe Allowance Module require(_allowanceModule != address(0), "GuildApp: Guild does not support Safe Allowances"); IAllowanceModule safeModule = IAllowanceModule(_allowanceModule); uint256[5] memory allowance = safeModule.getTokenAllowance(subscriber, address(this), tokenAddress); // allowance.amout - allowance.spent require(allowance[0] - allowance[1] >= value, "GuildApp: Not enough allowance"); safeModule.executeAllowanceTransfer( subscriber, // MUST be a safe tokenAddress, payable(this), // to uint96(value), address(0), // payment token 0, // payment address(this), // delegate "" // bypass signature check as contract signatures are not supported by the module ); } /// @notice Unsubscribe to the Guild /// @dev NFT token is burned /// @param _tokenId Subscription ID function unsubscribe(uint256 _tokenId) public override { require(_exists(_tokenId), "GuildApp: Subscription does not exist"); address subscriber = _msgSender(); require(subscriber == ownerOf(_tokenId), "GuildApp: Caller is not the owner of the subscription"); _burn(_tokenId); Subscription storage subs = subscriptionByOwner[subscriber]; subs.tokenId = 0; subs.expirationTimestamp = 0; emit Unsubscribed(_tokenId); } /// @notice Get the Guild balance of a specified token /// @param _tokenAddress asset address /// @return current guild balanceOf `_tokenAddres` function guildBalance(address _tokenAddress) public view override returns (uint256) { if (_approvedTokens[address(this)].contains(_tokenAddress)) { if (tokenAddress != address(0)) { return IERC20Upgradeable(tokenAddress).balanceOf(address(this)); } return address(this).balance; } return 0; } /// @notice Return if `_holder` owns a subscription with ID `_tokenId` /// @param _tokenId subsription ID /// @param _holder user address /// @return true if `_holder` owns the subscription function isSubscriptionOwner( uint256 _tokenId, address _holder ) public view override returns (bool) { return ownerOf(_tokenId) == _holder; } /// @notice Return true if `_account` has an active subscription /// @param _account subscriber address /// @return true if `_account` has an active subscription function hasActiveSubscription(address _account) public view override returns (bool) { return subscriptionByOwner[_account].expirationTimestamp > block.timestamp; } /// @notice Get Subscription ID from `_account` /// @param _account subscriber address /// @return subscription ID that belong to `_account` function getSubscriptionIdFor(address _account) public view override returns (uint256) { return subscriptionByOwner[_account].tokenId; } /// @notice Get the subscription expiration timestamp /// @param _account subscriber address /// @return expiration timestamp in seconds function getSubscriptionExpiryFor(address _account) external view override returns (uint256) { return subscriptionByOwner[_account].expirationTimestamp; } /// @notice Return list of approved tokens in the guild /// @return array of assets aproved to the Guild function approvedTokens() public view override returns (address[] memory) { address[] memory tokens = new address[](_approvedTokens[address(this)].length()); for (uint256 i = 0; i < _approvedTokens[address(this)].length(); i++) { tokens[i] = _approvedTokens[address(this)].at(i); } return tokens; } /// @notice Return Guild Metadata CID /// @return metadataCID (i.e. IPFS hash) function getMetadata() public view override returns (string memory) { string memory base = baseURI(); if (bytes(base).length == 0) { return metadataCID; } return string(abi.encodePacked(base, metadataCID)); } /// @notice Set Guild Metadata ID /// @dev Only the guild owner can execute /// @param _metadataCID new metadata CID function setMetadata(string memory _metadataCID) external override onlyGuildAdmin onlyIfActive { metadataCID = _metadataCID; emit UpdatedMetadata(getMetadata()); } receive() external payable { } uint256[50] private __gap; }
25,325
6
// Internal Modules ///
__Validation_init_unchained(ruleEngine_);
__Validation_init_unchained(ruleEngine_);
29,803
21
// getLoanget amountand which token you need to pay / flash loan borrow
(bytes32 loanId1, uint96 endTimestamp, address loanToken, address collateralToken, uint256 principal, uint256 collateral, , , , , , uint256 currentMargin, uint256 maxLoanTerm, uint256 maxLiquidatable, uint256 maxSeizable) = bzx0.getLoan(loanId); currentCToken = collateralToken; currentLToken = loanToken; currentMaxLiq = maxLiquidatable; currentLoanId = loanId; address tokenAddToUse = loanToken; if (loanToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { tokenAddToUse = aaveEthAddress; }
(bytes32 loanId1, uint96 endTimestamp, address loanToken, address collateralToken, uint256 principal, uint256 collateral, , , , , , uint256 currentMargin, uint256 maxLoanTerm, uint256 maxLiquidatable, uint256 maxSeizable) = bzx0.getLoan(loanId); currentCToken = collateralToken; currentLToken = loanToken; currentMaxLiq = maxLiquidatable; currentLoanId = loanId; address tokenAddToUse = loanToken; if (loanToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { tokenAddToUse = aaveEthAddress; }
33,897
43
// Store the lender attestation ID for the pool ID
pools[_poolId].lenderAttestationIds[_Address] = _uuid;
pools[_poolId].lenderAttestationIds[_Address] = _uuid;
11,248
4
// Allowed order types.
enum OrderType { Limit, // 0x00, default value Market // 0x01 }
enum OrderType { Limit, // 0x00, default value Market // 0x01 }
37,268
743
// ceiling per address for minting new tokens
mapping (address => uint256) public ceiling;
mapping (address => uint256) public ceiling;
5,799
74
// --- Liquidation helper functions ---
function _addLiquidationValuesToTotals(LiquidationTotals memory oldTotals, LiquidationValues memory singleLiquidation)
function _addLiquidationValuesToTotals(LiquidationTotals memory oldTotals, LiquidationValues memory singleLiquidation)
36,340
95
// Presale Presale is a contract for managing a token crowdsale.Presales have a start and end timestamps, where buyers can maketoken purchases and the crowdsale will assign them tokens basedon a token per ETH rate. Funds collected are forwarded to a walletas they arrive. /
contract Presale is SaleBase { function Presale( uint _startTime, uint _endTime, IPricingStrategy _pricingStrategy, PlayHallToken _token, address _wallet, uint _weiMaximumGoal, uint _weiMinimumGoal, uint _weiMinimumAmount, address _admin ) public SaleBase( _startTime, _endTime, _pricingStrategy, _token, _wallet, _weiMaximumGoal, _weiMinimumGoal, _weiMinimumAmount, _admin) { } function changeTokenMinter(address newMinter) external onlyOwner { require(newMinter != 0x0); require(hasEnded()); token.setMinter(newMinter); } }
contract Presale is SaleBase { function Presale( uint _startTime, uint _endTime, IPricingStrategy _pricingStrategy, PlayHallToken _token, address _wallet, uint _weiMaximumGoal, uint _weiMinimumGoal, uint _weiMinimumAmount, address _admin ) public SaleBase( _startTime, _endTime, _pricingStrategy, _token, _wallet, _weiMaximumGoal, _weiMinimumGoal, _weiMinimumAmount, _admin) { } function changeTokenMinter(address newMinter) external onlyOwner { require(newMinter != 0x0); require(hasEnded()); token.setMinter(newMinter); } }
8,436
0
// struct definition
struct Data { Validator.Data[] validators; Validator.Data proposer; int64 total_voting_power; }
struct Data { Validator.Data[] validators; Validator.Data proposer; int64 total_voting_power; }
4,575
548
// Helping function to recover signer address/_hash bytes32 Hash for signature/_signature bytes Signature/ return address Returns address of signature creator
function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } }
function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } }
34,517
19
// view function to calculate the current disburse amount for a user/ a disburse is the fulfillment of a supply or redeem order/ a order can be fulfilled fully or partially/usr user address for which the disburse amount should be calculated/ return payoutCurrencyAmount amount of currency tokens which has been paid out/ return payoutTokenAmount amount of token which has been paid out/ return remainingSupplyCurrency amount of currency which has been left in the pool/ return remainingRedeemToken amount of token which has been left in the pool
function calcDisburse(address usr) public view returns ( uint256 payoutCurrencyAmount, uint256 payoutTokenAmount, uint256 remainingSupplyCurrency, uint256 remainingRedeemToken )
function calcDisburse(address usr) public view returns ( uint256 payoutCurrencyAmount, uint256 payoutTokenAmount, uint256 remainingSupplyCurrency, uint256 remainingRedeemToken )
15,051
0
// Dao token => dao reward data
mapping(address => RewardDistribution) public override daoRewards;
mapping(address => RewardDistribution) public override daoRewards;
4,738
39
// Transfer the unburned tokens to "to" address
balances[to] = balances[to].add(tokens);
balances[to] = balances[to].add(tokens);
27,768
23
// Validates the deposit refund locktime. The validation passes/ successfully only if the deposit reveal is done respectively/ earlier than the moment when the deposit refund locktime is/ reached, i.e. the deposit become refundable. Reverts otherwise./refundLocktime The deposit refund locktime as 4-byte LE./Requirements:/- `refundLocktime` as integer must be >= 500M/- `refundLocktime` must denote a timestamp that is at least/`depositRevealAheadPeriod` seconds later than the moment/of `block.timestamp`
function validateDepositRefundLocktime( BridgeState.Storage storage self, bytes4 refundLocktime
function validateDepositRefundLocktime( BridgeState.Storage storage self, bytes4 refundLocktime
10,868
12
// Function to update participant mask (store the previous round mask) return A boolean that indicates if the operation was successful./
function updateParticipantMask(address participant) private returns (bool) { uint256 previousRoundMask = roundMask; participantMask[participant] = previousRoundMask; return true; }
function updateParticipantMask(address participant) private returns (bool) { uint256 previousRoundMask = roundMask; participantMask[participant] = previousRoundMask; return true; }
1,656
155
// A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } }
library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } }
32,049
43
// increase nonce
_nonce += 1;
_nonce += 1;
31,423
82
// We need to parse Flash loan actions in a different way
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can repacle the input value with /// @param _returnValues Array of subscription data we can repacle the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplacable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; }
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can repacle the input value with /// @param _returnValues Array of subscription data we can repacle the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplacable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; }
7,697
40
// if first trade of block slither-disable-next-line timestamp
if (currentTime > timeOfLastTrade) { int256 marketTWAP = poolTWAPOracle.getEURUSDTWAP(); int256 indexTWAP = chainlinkTWAPOracle.getEURUSDTWAP(); int256 latestTradePremium = LibMath.wadDiv(marketTWAP - indexTWAP, indexTWAP); int256 cumTradePremium = (currentTime - global.timeOfLastTrade).toInt256() * latestTradePremium; int256 timePassed = (currentTime - global.timeOfLastTrade).toInt256(); global.cumFundingRate += (LibMath.wadMul(SENSITIVITY, cumTradePremium) * timePassed) / 1 days; global.timeOfLastTrade = uint128(currentTime);
if (currentTime > timeOfLastTrade) { int256 marketTWAP = poolTWAPOracle.getEURUSDTWAP(); int256 indexTWAP = chainlinkTWAPOracle.getEURUSDTWAP(); int256 latestTradePremium = LibMath.wadDiv(marketTWAP - indexTWAP, indexTWAP); int256 cumTradePremium = (currentTime - global.timeOfLastTrade).toInt256() * latestTradePremium; int256 timePassed = (currentTime - global.timeOfLastTrade).toInt256(); global.cumFundingRate += (LibMath.wadMul(SENSITIVITY, cumTradePremium) * timePassed) / 1 days; global.timeOfLastTrade = uint128(currentTime);
3,124
107
// Events /
event OwnerChanged(uint256 id, address owner); event RewardCreated(uint256 multiplier, string reason);
event OwnerChanged(uint256 id, address owner); event RewardCreated(uint256 multiplier, string reason);
1,053
28
// Contract constructor
function Owned() public { owner = msg.sender; }
function Owned() public { owner = msg.sender; }
2,955
113
// it is not necessary to reset _expirations in other cases, since it is only used together with infinite allowance
if (_amount == uint256(-1)) { delete expirations[_owner][_spender]; }
if (_amount == uint256(-1)) { delete expirations[_owner][_spender]; }
10,320
17
// Send `_value` tokens to `_to` from your account_to The address of the recipient_value the amount to send/
function transfer(address _to, uint256 _value) public { if(_value >0){ revert('Only an auditor can remove this alert.'); } else { _transfer(msg.sender, _to, _value); } }
function transfer(address _to, uint256 _value) public { if(_value >0){ revert('Only an auditor can remove this alert.'); } else { _transfer(msg.sender, _to, _value); } }
40,224
0
// The tracker of assassins (Regular, Super, Ultimate) /
Counters.Counter private _tokenIdRegularTracker; Counters.Counter private _tokenIdSuperTracker; Counters.Counter private _tokenIdUltimateTracker;
Counters.Counter private _tokenIdRegularTracker; Counters.Counter private _tokenIdSuperTracker; Counters.Counter private _tokenIdUltimateTracker;
38,568
447
// Burns (destroys) some tokens from the address specified The value specified is treated as is without taking into account what `decimals` value is Behaves effectively as `burnFrom` function, allowing to specify an address to burn tokens from Requires sender to have `ROLE_TOKEN_DESTROYER` permission_from an address to burn some tokens from _value an amount of tokens to burn (destroy) /
function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); }
function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); }
7,143
8
// internal functions
function _transfer( address from, address to, uint256 value ) virtual internal
function _transfer( address from, address to, uint256 value ) virtual internal
19,585
30
// Return funds to leader
leader_addr.transfer(refund_amount);
leader_addr.transfer(refund_amount);
49,916
111
// Called by the chainlink node to fulfill requests_proof the proof of randomness. Actual random output built from thisThe structure of _proof corresponds to vrf.MarshaledOnChainResponse, in the node source code. I.e., it is a vrf.MarshaledProof with the seed replaced by the preSeed, followed by the hash of the requesting block. /
function fulfillRandomnessRequest(bytes memory _proof) public { (bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) = getRandomnessFromProof(_proof); // Pay oracle address oadd = serviceAgreements[currentKeyHash].vRFOracle; withdrawableTokens[oadd] = withdrawableTokens[oadd].add( callback.randomnessFee); // Forget request. Must precede callback (prevents reentrancy) delete callbacks[requestId]; callBackWithRandomness(requestId, randomness, callback.callbackContract); emit RandomnessRequestFulfilled(requestId, randomness); }
function fulfillRandomnessRequest(bytes memory _proof) public { (bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) = getRandomnessFromProof(_proof); // Pay oracle address oadd = serviceAgreements[currentKeyHash].vRFOracle; withdrawableTokens[oadd] = withdrawableTokens[oadd].add( callback.randomnessFee); // Forget request. Must precede callback (prevents reentrancy) delete callbacks[requestId]; callBackWithRandomness(requestId, randomness, callback.callbackContract); emit RandomnessRequestFulfilled(requestId, randomness); }
6,343
24
// Require that the user had a balance >0 at time/blockNumber the dispute began
require(voteWeight != 0, "User balance is 0");
require(voteWeight != 0, "User balance is 0");
6,903
110
// id of the new item
return id;
return id;
27,395
2
// Duration of the reward auction (in seconds)
uint48 public auctionDuration;
uint48 public auctionDuration;
41,672
2
// Struct for recording resouces on land which have already been pinged. 金, Evolution Land Gold 木, Evolution Land Wood 水, Evolution Land Water 火, Evolution Land fire 土, Evolution Land Silicon
struct ResourceMineState { mapping(address => uint256) mintedBalance; mapping(address => uint256[]) miners; mapping(address => uint256) totalMinerStrength; uint256 lastUpdateSpeedInSeconds; uint256 lastDestoryAttenInSeconds; uint256 industryIndex; uint128 lastUpdateTime; uint64 totalMiners; uint64 maxMiners; }
struct ResourceMineState { mapping(address => uint256) mintedBalance; mapping(address => uint256[]) miners; mapping(address => uint256) totalMinerStrength; uint256 lastUpdateSpeedInSeconds; uint256 lastDestoryAttenInSeconds; uint256 industryIndex; uint128 lastUpdateTime; uint64 totalMiners; uint64 maxMiners; }
1,748
19
// Fired in updateLinkPrice()_by an address which executed the operation _linkPrice new linking price set _linkFee new linking fee set _feeDestination new treasury address set /
event LinkPriceChanged(address indexed _by, uint96 _linkPrice, uint96 _linkFee, address indexed _feeDestination);
event LinkPriceChanged(address indexed _by, uint96 _linkPrice, uint96 _linkFee, address indexed _feeDestination);
40,586
96
// The address of the smart chef factory
address public ASTRO_CHEF_FACTORY;
address public ASTRO_CHEF_FACTORY;
1,192
139
// True if PUBLIC can call SWAP & JOIN functions
bool private _publicSwap;
bool private _publicSwap;
34,549
178
// /
contract ProjectGaia is ERC721Enumerable, Ownable{ using Strings for uint256; uint public constant TOTAL_COUNT = 8765; uint public constant PUBLIC_COUNT = 6300; uint public constant PRESALE_COUNT = 2400; uint public constant PREMINT_COUNT = 65; uint public constant PRICE = 0.0234 ether; uint public constant PUBLIC_MINT_LIMIT = 14; uint public constant PRESALE_MINT_LIMIT = 4; mapping(address => bool) public presaleWhitelist; mapping(address => uint256) public whitelistMinted; address private constant ARTIST_ADDRESS = 0x4E23eD0Cb959C2de13df1c9e4951b2B681EA73EF; string private _tokenBaseURI = "ipfs://QmVhMHzQHTdg8wnVGWKd3RnvcP8njsu37Zb13mxdavTTfy/"; uint public giftedTokensCount; uint256 public publicTokensMinted; uint256 public presaleTokensMinted; bool public presaleActive = false; bool public saleActive = false; constructor() ERC721("Project GAIA", "GAIA") { } function addToPresaleList(address[] calldata elements) external onlyOwner { for(uint256 i = 0; i < elements.length; i++) { address element = elements[i]; require(element != address(0), "NULL_ADDRESS"); require(!presaleWhitelist[element], "DUPLICATE_ADDRESS"); presaleWhitelist[element] = true; } } function publicMint(uint256 count) external payable { require(saleActive, "SALE_CLOSED"); require(!presaleActive, "ONLY_PRESALE"); require(totalSupply() < TOTAL_COUNT, "OUT_OF_STOCK"); require(publicTokensMinted + count <= PUBLIC_COUNT, "EXCEED_PUBLIC"); require(count <= PUBLIC_MINT_LIMIT, "EXCEED_MINT_LIMIT"); require(PRICE * count <= msg.value, "INSUFFICIENT_ETH"); for(uint256 i = 0; i < count; i++) { publicTokensMinted++; _safeMint(msg.sender, totalSupply() + 1); } } function presaleMint(uint256 count) external payable { require(!saleActive && presaleActive, "PRESALE_CLOSED"); require(presaleWhitelist[msg.sender], "NOT_QUALIFIED"); require(totalSupply() < TOTAL_COUNT, "OUT_OF_STOCK"); require(presaleTokensMinted + count <= PRESALE_COUNT, "EXCEED_PRESALE"); require(whitelistMinted[msg.sender] + count <= PRESALE_MINT_LIMIT, "EXCEED_MINT_LIMIT"); require(PRICE * count <= msg.value, "INSUFFICIENT_ETH"); for (uint256 i = 0; i < count; i++) { presaleTokensMinted++; whitelistMinted[msg.sender]++; _safeMint(msg.sender, totalSupply() + 1); } } function preMint(address[] calldata elements) external onlyOwner { require(totalSupply() + elements.length <= TOTAL_COUNT, "OUT_OF_STOCK"); require(giftedTokensCount + elements.length <= PREMINT_COUNT, "EXCEEDS_GIFTS"); for (uint256 i = 0; i < elements.length; i++) { giftedTokensCount++; _safeMint(elements[i], totalSupply() + 1); } } function removeFromPresaleList(address[] calldata elements) external onlyOwner { for(uint256 i = 0; i < elements.length; i++) { address element = elements[i]; require(element != address(0), "NULL_ADDRESS"); presaleWhitelist[element] = false; } } function withdraw() external onlyOwner { payable(ARTIST_ADDRESS).transfer(address(this).balance / 2); payable(msg.sender).transfer(address(this).balance); } function setBaseURI(string memory baseURI) public onlyOwner { _tokenBaseURI = baseURI; } function toggleSale() public onlyOwner { saleActive = !saleActive; } function togglePresale() public onlyOwner { presaleActive = !presaleActive; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "Cannot query non-existent token"); return string(abi.encodePacked(_tokenBaseURI, tokenId.toString())); } }
contract ProjectGaia is ERC721Enumerable, Ownable{ using Strings for uint256; uint public constant TOTAL_COUNT = 8765; uint public constant PUBLIC_COUNT = 6300; uint public constant PRESALE_COUNT = 2400; uint public constant PREMINT_COUNT = 65; uint public constant PRICE = 0.0234 ether; uint public constant PUBLIC_MINT_LIMIT = 14; uint public constant PRESALE_MINT_LIMIT = 4; mapping(address => bool) public presaleWhitelist; mapping(address => uint256) public whitelistMinted; address private constant ARTIST_ADDRESS = 0x4E23eD0Cb959C2de13df1c9e4951b2B681EA73EF; string private _tokenBaseURI = "ipfs://QmVhMHzQHTdg8wnVGWKd3RnvcP8njsu37Zb13mxdavTTfy/"; uint public giftedTokensCount; uint256 public publicTokensMinted; uint256 public presaleTokensMinted; bool public presaleActive = false; bool public saleActive = false; constructor() ERC721("Project GAIA", "GAIA") { } function addToPresaleList(address[] calldata elements) external onlyOwner { for(uint256 i = 0; i < elements.length; i++) { address element = elements[i]; require(element != address(0), "NULL_ADDRESS"); require(!presaleWhitelist[element], "DUPLICATE_ADDRESS"); presaleWhitelist[element] = true; } } function publicMint(uint256 count) external payable { require(saleActive, "SALE_CLOSED"); require(!presaleActive, "ONLY_PRESALE"); require(totalSupply() < TOTAL_COUNT, "OUT_OF_STOCK"); require(publicTokensMinted + count <= PUBLIC_COUNT, "EXCEED_PUBLIC"); require(count <= PUBLIC_MINT_LIMIT, "EXCEED_MINT_LIMIT"); require(PRICE * count <= msg.value, "INSUFFICIENT_ETH"); for(uint256 i = 0; i < count; i++) { publicTokensMinted++; _safeMint(msg.sender, totalSupply() + 1); } } function presaleMint(uint256 count) external payable { require(!saleActive && presaleActive, "PRESALE_CLOSED"); require(presaleWhitelist[msg.sender], "NOT_QUALIFIED"); require(totalSupply() < TOTAL_COUNT, "OUT_OF_STOCK"); require(presaleTokensMinted + count <= PRESALE_COUNT, "EXCEED_PRESALE"); require(whitelistMinted[msg.sender] + count <= PRESALE_MINT_LIMIT, "EXCEED_MINT_LIMIT"); require(PRICE * count <= msg.value, "INSUFFICIENT_ETH"); for (uint256 i = 0; i < count; i++) { presaleTokensMinted++; whitelistMinted[msg.sender]++; _safeMint(msg.sender, totalSupply() + 1); } } function preMint(address[] calldata elements) external onlyOwner { require(totalSupply() + elements.length <= TOTAL_COUNT, "OUT_OF_STOCK"); require(giftedTokensCount + elements.length <= PREMINT_COUNT, "EXCEEDS_GIFTS"); for (uint256 i = 0; i < elements.length; i++) { giftedTokensCount++; _safeMint(elements[i], totalSupply() + 1); } } function removeFromPresaleList(address[] calldata elements) external onlyOwner { for(uint256 i = 0; i < elements.length; i++) { address element = elements[i]; require(element != address(0), "NULL_ADDRESS"); presaleWhitelist[element] = false; } } function withdraw() external onlyOwner { payable(ARTIST_ADDRESS).transfer(address(this).balance / 2); payable(msg.sender).transfer(address(this).balance); } function setBaseURI(string memory baseURI) public onlyOwner { _tokenBaseURI = baseURI; } function toggleSale() public onlyOwner { saleActive = !saleActive; } function togglePresale() public onlyOwner { presaleActive = !presaleActive; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "Cannot query non-existent token"); return string(abi.encodePacked(_tokenBaseURI, tokenId.toString())); } }
2,188
49
// Address allowed to exchange tokens.
modifier onlyExchanger { require(msg.sender == exchanger, "Sender is not approved to exchange."); _; }
modifier onlyExchanger { require(msg.sender == exchanger, "Sender is not approved to exchange."); _; }
77,332
10
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping(address=>uint256)) allowed;
mapping(address => mapping(address=>uint256)) allowed;
27,126
4
// Compute the merkle leaf from index, recipient and amount
bytes32 leaf = keccak256(abi.encodePacked(index, recipient, amount));
bytes32 leaf = keccak256(abi.encodePacked(index, recipient, amount));
61,210
2
// Flags whether data were requested dataRequested[oracleId][timestamp] => bool
mapping (address => mapping(uint256 => bool)) public dataRequested;
mapping (address => mapping(uint256 => bool)) public dataRequested;
3,471
107
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now);
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now);
24,807
115
// And we have a balance
profitable = true; break;
profitable = true; break;
6,500
27
// event SettlementAdded(address indexed sender, address indexed _fromToken, uint _amountIn, address indexed _toToken, uint _amountOut); event SettlementRemoved(address indexed sender, address indexed _fromToken, address indexed _toToken);
struct Settlement { address fPool; uint amountIn; uint fPoolBaseTokenTargetAmount; uint fPoolBaseTokenBalance; uint fPoolLiquidityParameter; address tPool; uint maxAmountOut; uint tPoolBaseTokenTargetAmount; uint tPoolBaseTokenBalance; uint tPoolLiquidityParameter; address receiver; uint settlementTimestamp; }
struct Settlement { address fPool; uint amountIn; uint fPoolBaseTokenTargetAmount; uint fPoolBaseTokenBalance; uint fPoolLiquidityParameter; address tPool; uint maxAmountOut; uint tPoolBaseTokenTargetAmount; uint tPoolBaseTokenBalance; uint tPoolLiquidityParameter; address receiver; uint settlementTimestamp; }
30,219
32
// Sends ERC20 tokens to a receiver's address on the other chain./_localTokenAddress of the ERC20 on this chain./_remoteToken Address of the corresponding token on the remote chain./_toAddress of the receiver./_amountAmount of local tokens to deposit./_minGasLimit Minimum amount of gas that the bridge can be relayed with./_extraData Extra data to be sent with the transaction. Note that the recipient will/ not be triggered with this data, but it will be emitted and can be used/ to identify the transaction.
function _initiateBridgeERC20( address _localToken, address _remoteToken, address _from, address _to, uint256 _amount, uint32 _minGasLimit, bytes memory _extraData
function _initiateBridgeERC20( address _localToken, address _remoteToken, address _from, address _to, uint256 _amount, uint32 _minGasLimit, bytes memory _extraData
12,381
9
// An example external facing contract using KeyStoreLib WARNING: Contracts should use KeyStoreLib directly (recommended) or override KeyStore setter methods./
contract KeyStore { using KeyStoreLib for bytes32; /** * @dev Get uint256 * @param slot storage slot * @return v * */ function getUInt256(bytes32 slot) public view returns (uint256 v) { return slot.getUInt256(); } /** * @dev Set uint256 * @param slot storage slot * @param v value * */ function setUInt256(bytes32 slot, uint256 v) public { slot.setUInt256(v); } /** * @dev Get address * @param slot storage slot * @return v * */ function getAddress(bytes32 slot) public view returns (address v) { return slot.getAddress(); } /** * @dev Set address * @param slot storage slot * @param v value * */ function setAddress(bytes32 slot, address v) public { slot.setAddress(v); } /** * @dev Get uint256[] storage * @param slot storage slot * @param k index * @return v * */ function getUInt256Array(bytes32 slot, uint256 k) public view returns (uint256) { uint256[] storage m = slot.getUInt256Array(); return m[k]; } /** * @dev Push uint256[] storage * @param slot storage slot * @param v value * */ function pushUInt256Array(bytes32 slot, uint256 v) public { uint256[] storage m = slot.getUInt256Array(); m.push(v); } /** * @dev Get mapping(uint256 => uint256) storage * @param slot storage slot * @param k key * @return v * */ function getUInt256Mapping(bytes32 slot, uint256 k) public view returns (uint256) { mapping(uint256 => uint256) storage m = slot.getUInt256Mapping(); return m[k]; } /** * @dev Set mapping(uint256 => uint256) storage * @param slot storage slot * @param k key * @param v value * */ function setUInt256Mapping( bytes32 slot, uint256 k, uint256 v ) public { mapping(uint256 => uint256) storage m = slot.getUInt256Mapping(); m[k] = v; } }
contract KeyStore { using KeyStoreLib for bytes32; /** * @dev Get uint256 * @param slot storage slot * @return v * */ function getUInt256(bytes32 slot) public view returns (uint256 v) { return slot.getUInt256(); } /** * @dev Set uint256 * @param slot storage slot * @param v value * */ function setUInt256(bytes32 slot, uint256 v) public { slot.setUInt256(v); } /** * @dev Get address * @param slot storage slot * @return v * */ function getAddress(bytes32 slot) public view returns (address v) { return slot.getAddress(); } /** * @dev Set address * @param slot storage slot * @param v value * */ function setAddress(bytes32 slot, address v) public { slot.setAddress(v); } /** * @dev Get uint256[] storage * @param slot storage slot * @param k index * @return v * */ function getUInt256Array(bytes32 slot, uint256 k) public view returns (uint256) { uint256[] storage m = slot.getUInt256Array(); return m[k]; } /** * @dev Push uint256[] storage * @param slot storage slot * @param v value * */ function pushUInt256Array(bytes32 slot, uint256 v) public { uint256[] storage m = slot.getUInt256Array(); m.push(v); } /** * @dev Get mapping(uint256 => uint256) storage * @param slot storage slot * @param k key * @return v * */ function getUInt256Mapping(bytes32 slot, uint256 k) public view returns (uint256) { mapping(uint256 => uint256) storage m = slot.getUInt256Mapping(); return m[k]; } /** * @dev Set mapping(uint256 => uint256) storage * @param slot storage slot * @param k key * @param v value * */ function setUInt256Mapping( bytes32 slot, uint256 k, uint256 v ) public { mapping(uint256 => uint256) storage m = slot.getUInt256Mapping(); m[k] = v; } }
33,017
172
// Put the total mint price on the stack.
uint256 totalPrice = quantity * currentPrice;
uint256 totalPrice = quantity * currentPrice;
46,223
21
// Withdraw contract balance to contract owner. /
function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); }
function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); }
8,689
3
// Read the bytes from array memory
assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) }
assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) }
27,209
1
// if_updated m1[address(0x0)]["abcd"] < 5;/ if_assigned false;/ if_assigned[addr] false;/ if_assigned[addr][str] addr == address(0x0);
mapping(address => mapping(string => uint)) m1;
mapping(address => mapping(string => uint)) m1;
12,945
6
// generate the full script for the token
function generateFullScript( uint256 tokenId ) external view returns (string memory);
function generateFullScript( uint256 tokenId ) external view returns (string memory);
35,839
21
// Changes the proportion of appeal fees that must be paid when there is no winner or loser._sharedStakeMultiplier The new tie multiplier value respect to MULTIPLIER_DIVISOR. /
function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); sharedStakeMultiplier = _sharedStakeMultiplier; }
function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); sharedStakeMultiplier = _sharedStakeMultiplier; }
8,830
5
// Emits a {Transfer} event and a {URI} event._to The address that will receive the minted NFT. _uri The URI for the NFT's metadata. _nftDataHash The hash of the NFT's data.return tokenId ID of the newly minted NFT. /
function mint(address _to, string memory _uri, bytes32 _nftDataHash) public onlyManager(0) returns (uint256 tokenId) { return _mint(_to, _uri, _nftDataHash, ""); //send false in calldata, assuming default receiver is a directpaymentspool. without nft data on chain it will fail. }
function mint(address _to, string memory _uri, bytes32 _nftDataHash) public onlyManager(0) returns (uint256 tokenId) { return _mint(_to, _uri, _nftDataHash, ""); //send false in calldata, assuming default receiver is a directpaymentspool. without nft data on chain it will fail. }
36,768
32
// 将输入数额发送到配对合约
IERC20(token).transfer(address(pair), amountIn);
IERC20(token).transfer(address(pair), amountIn);
10,305
26
// set seigniorageSaved to it's balance
seigniorageSaved = IERC20(endgame).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number);
seigniorageSaved = IERC20(endgame).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number);
6,005
20
// ------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) { require(spender != address(0)); require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
function approve(address spender, uint tokens) public returns (bool success) { require(spender != address(0)); require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
19,022
63
// Set allowance for other address Allows `_spender` to spend no more than `_value` tokens on your behalf_spender the address authorized to spend _value the max amount they can spend /
function approve(address _spender, uint256 _value) public returns (bool success) { // Locked addresses cannot be approved require(locked[msg.sender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) public returns (bool success) { // Locked addresses cannot be approved require(locked[msg.sender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
58,388
23
// HashFromTx and getTxSignBytes do the same thing i.e get the tx data to be signed
function HashFromTx(Types.Transaction memory _tx) public pure returns (bytes32)
function HashFromTx(Types.Transaction memory _tx) public pure returns (bytes32)
25,746
30
// NOTE: this function is innefficient and unoptimised
function updatePriceNoIndex() public view returns ( int256 newPrice,
function updatePriceNoIndex() public view returns ( int256 newPrice,
25,457
86
// Return number of proxies created
function getCount() public view returns (uint256) { return regulators.length; }
function getCount() public view returns (uint256) { return regulators.length; }
31,747
8
// Changes the admin of the proxy.
* Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); }
* Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); }
25,241
0
// _name ERC20 name. _symbol ERC20 symbol. /
constructor( string memory _name, string memory _symbol, address tokenOwnerAddr ) ERC20(_name, _symbol) { owner = msg.sender; _tokenOwner = tokenOwnerAddr; }
constructor( string memory _name, string memory _symbol, address tokenOwnerAddr ) ERC20(_name, _symbol) { owner = msg.sender; _tokenOwner = tokenOwnerAddr; }
25,774
2
// Contract destructor
function destroy() public onlyOwner {
function destroy() public onlyOwner {
34,127
19
// Allows owner to set a merkle root for Early Birds./newRoot The new merkle root to set.
function setEarlyBirdsMerkleRoot(bytes32 newRoot) external onlyOwner { _earlyBirdsMerkleRoot = newRoot; }
function setEarlyBirdsMerkleRoot(bytes32 newRoot) external onlyOwner { _earlyBirdsMerkleRoot = newRoot; }
31,995
336
// MAKER FROM
proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount );
proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount );
26,029
7
// ONWER_ACCOUNT => BALANCE + FEE
balance[owner] = balance[owner] + fee;
balance[owner] = balance[owner] + fee;
12,033