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
497
// add y^20(20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1;
res = res / 0x21c3677c82b40000 + y + FIXED_1;
33,288
5
// Official record of token balances for each account
mapping (address => uint96) internal balances;
mapping (address => uint96) internal balances;
11,603
16
// Owners Map
mapping(uint256 => address) public tokenOwners;
mapping(uint256 => address) public tokenOwners;
32,089
13
// Set the new contract URI.
_contractURI = newContractURI;
_contractURI = newContractURI;
12,550
11
// setters
bool public reLockProfits; // true if we choose to re-lock profits following each harvest and automatically start another epoch bool public checkTrueHoldings; // bool to reset our profit/loss based on the amount we have if we withdrew everything at once uint256 public slippageMax; // in bips, how much slippage we allow between our optimistic assets and pessimistic. 50 = 0.5% slippage. Remember curve swap costs 0.04%. bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us
bool public reLockProfits; // true if we choose to re-lock profits following each harvest and automatically start another epoch bool public checkTrueHoldings; // bool to reset our profit/loss based on the amount we have if we withdrew everything at once uint256 public slippageMax; // in bips, how much slippage we allow between our optimistic assets and pessimistic. 50 = 0.5% slippage. Remember curve swap costs 0.04%. bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us
18,286
153
// send withdrawn EVRT
uint256 tax = (what * paperHandsPenalty) / MAX_BIPS; uint256 toSend = what - tax;
uint256 tax = (what * paperHandsPenalty) / MAX_BIPS; uint256 toSend = what - tax;
49,510
8
// Refund to `recipient` when buy NFT failed or Seaport gives back remaining ether. NOTE: Caller must guarantee that the `recipient` is the expected refunding receiver.
uint256 refund = address(this).balance; if (refund > 0) { Address.sendValue(payable(recipient), refund); }
uint256 refund = address(this).balance; if (refund > 0) { Address.sendValue(payable(recipient), refund); }
13,946
55
// Sets the signature address of an edition
function setSignerAddress(uint256 _editionId, address _newSignerAddress) external onlyOwner { require(_newSignerAddress != address(0), 'Signer address cannot be 0'); editions[_editionId].signerAddress = _newSignerAddress; emit SignerAddressSet(_editionId, _newSignerAddress); }
function setSignerAddress(uint256 _editionId, address _newSignerAddress) external onlyOwner { require(_newSignerAddress != address(0), 'Signer address cannot be 0'); editions[_editionId].signerAddress = _newSignerAddress; emit SignerAddressSet(_editionId, _newSignerAddress); }
66,877
51
// ERC-777 functions /
function granularity() external pure override returns (uint256) { return 1; } function send(address recipient, uint256 amount, bytes calldata data) external override { _send(msg.sender, msg.sender, recipient, amount, data, "", true); }
function granularity() external pure override returns (uint256) { return 1; } function send(address recipient, uint256 amount, bytes calldata data) external override { _send(msg.sender, msg.sender, recipient, amount, data, "", true); }
5,096
89
// Storage of strategies and templates
contract Subscriptions is StrategyData, AdminAuth { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); string public constant ERR_EMPTY_STRATEGY = "Strategy does not exist"; string public constant ERR_SENDER_NOT_OWNER = "Sender is not strategy owner"; string public constant ERR_USER_POS_EMPTY = "No user positions"; /// @dev The order of strategies might change as they are deleted Strategy[] public strategies; /// @dev Templates are fixed and are non removable Template[] public templates; /// @dev Keeps track of all the users strategies (their indexes in the array) mapping (address => uint[]) public usersPos; /// @dev Increments on state change, used for easier off chain tracking of changes uint public updateCounter; /// @notice Creates a new strategy with an existing template /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function createStrategy( uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public returns (uint) { strategies.push( Strategy({ templateId: _templateId, proxy: msg.sender, active: _active, subData: _subData, triggerData: _triggerData, posInUserArr: (usersPos[msg.sender].length - 1) }) ); usersPos[msg.sender].push(strategies.length - 1); updateCounter++; logger.Log(address(this), msg.sender, "CreateStrategy", abi.encode(strategies.length - 1)); return strategies.length - 1; } /// @notice Creates a new template to use in strategies /// @dev Templates once created can't be changed /// @param _name Name of template, used mainly for logging /// @param _triggerIds Array of trigger ids which translate to trigger addresses /// @param _actionIds Array of actions ids which translate to action addresses /// @param _paramMapping Array that holds metadata of how inputs are mapped to sub/return data function createTemplate( string memory _name, bytes32[] memory _triggerIds, bytes32[] memory _actionIds, uint8[][] memory _paramMapping ) public returns (uint) { templates.push( Template({ name: _name, triggerIds: _triggerIds, actionIds: _actionIds, paramMapping: _paramMapping }) ); updateCounter++; logger.Log(address(this), msg.sender, "CreateTemplate", abi.encode(templates.length - 1)); return templates.length - 1; } /// @notice Updates the users strategy /// @dev Only callable by proxy who created the strategy /// @param _strategyId Id of the strategy to update /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function updateStrategy( uint _strategyId, uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public { Strategy storage s = strategies[_strategyId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); s.templateId = _templateId; s.active = _active; s.subData = _subData; s.triggerData = _triggerData; updateCounter++; logger.Log(address(this), msg.sender, "UpdateStrategy", abi.encode(_strategyId)); } /// @notice Unsubscribe an existing strategy /// @dev Only callable by proxy who created the strategy /// @param _subId Subscription id function removeStrategy(uint256 _subId) public { Strategy memory s = strategies[_subId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); uint lastSub = strategies.length - 1; _removeUserPos(msg.sender, s.posInUserArr); strategies[_subId] = strategies[lastSub]; // last strategy put in place of the deleted one strategies.pop(); // delete last strategy, because it moved logger.Log(address(this), msg.sender, "Unsubscribe", abi.encode(_subId)); } function _removeUserPos(address _user, uint _index) internal { require(usersPos[_user].length > 0, ERR_USER_POS_EMPTY); uint lastPos = usersPos[_user].length - 1; usersPos[_user][_index] = usersPos[_user][lastPos]; usersPos[_user].pop(); } ///////////////////// VIEW ONLY FUNCTIONS //////////////////////////// function getTemplateFromStrategy(uint _strategyId) public view returns (Template memory) { uint templateId = strategies[_strategyId].templateId; return templates[templateId]; } function getStrategy(uint _strategyId) public view returns (Strategy memory) { return strategies[_strategyId]; } function getTemplate(uint _templateId) public view returns (Template memory) { return templates[_templateId]; } function getStrategyCount() public view returns (uint256) { return strategies.length; } function getTemplateCount() public view returns (uint256) { return templates.length; } function getStrategies() public view returns (Strategy[] memory) { return strategies; } function getTemplates() public view returns (Template[] memory) { return templates; } function userHasStrategies(address _user) public view returns (bool) { return usersPos[_user].length > 0; } function getUserStrategies(address _user) public view returns (Strategy[] memory) { Strategy[] memory userStrategies = new Strategy[](usersPos[_user].length); for (uint i = 0; i < usersPos[_user].length; ++i) { userStrategies[i] = strategies[usersPos[_user][i]]; } return userStrategies; } function getPaginatedStrategies(uint _page, uint _perPage) public view returns (Strategy[] memory) { Strategy[] memory strategiesPerPage = new Strategy[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > strategiesPerPage.length) ? strategiesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { strategiesPerPage[count] = strategies[i]; count++; } return strategiesPerPage; } function getPaginatedTemplates(uint _page, uint _perPage) public view returns (Template[] memory) { Template[] memory templatesPerPage = new Template[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > templatesPerPage.length) ? templatesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { templatesPerPage[count] = templates[i]; count++; } return templatesPerPage; } }
contract Subscriptions is StrategyData, AdminAuth { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); string public constant ERR_EMPTY_STRATEGY = "Strategy does not exist"; string public constant ERR_SENDER_NOT_OWNER = "Sender is not strategy owner"; string public constant ERR_USER_POS_EMPTY = "No user positions"; /// @dev The order of strategies might change as they are deleted Strategy[] public strategies; /// @dev Templates are fixed and are non removable Template[] public templates; /// @dev Keeps track of all the users strategies (their indexes in the array) mapping (address => uint[]) public usersPos; /// @dev Increments on state change, used for easier off chain tracking of changes uint public updateCounter; /// @notice Creates a new strategy with an existing template /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function createStrategy( uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public returns (uint) { strategies.push( Strategy({ templateId: _templateId, proxy: msg.sender, active: _active, subData: _subData, triggerData: _triggerData, posInUserArr: (usersPos[msg.sender].length - 1) }) ); usersPos[msg.sender].push(strategies.length - 1); updateCounter++; logger.Log(address(this), msg.sender, "CreateStrategy", abi.encode(strategies.length - 1)); return strategies.length - 1; } /// @notice Creates a new template to use in strategies /// @dev Templates once created can't be changed /// @param _name Name of template, used mainly for logging /// @param _triggerIds Array of trigger ids which translate to trigger addresses /// @param _actionIds Array of actions ids which translate to action addresses /// @param _paramMapping Array that holds metadata of how inputs are mapped to sub/return data function createTemplate( string memory _name, bytes32[] memory _triggerIds, bytes32[] memory _actionIds, uint8[][] memory _paramMapping ) public returns (uint) { templates.push( Template({ name: _name, triggerIds: _triggerIds, actionIds: _actionIds, paramMapping: _paramMapping }) ); updateCounter++; logger.Log(address(this), msg.sender, "CreateTemplate", abi.encode(templates.length - 1)); return templates.length - 1; } /// @notice Updates the users strategy /// @dev Only callable by proxy who created the strategy /// @param _strategyId Id of the strategy to update /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function updateStrategy( uint _strategyId, uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public { Strategy storage s = strategies[_strategyId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); s.templateId = _templateId; s.active = _active; s.subData = _subData; s.triggerData = _triggerData; updateCounter++; logger.Log(address(this), msg.sender, "UpdateStrategy", abi.encode(_strategyId)); } /// @notice Unsubscribe an existing strategy /// @dev Only callable by proxy who created the strategy /// @param _subId Subscription id function removeStrategy(uint256 _subId) public { Strategy memory s = strategies[_subId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); uint lastSub = strategies.length - 1; _removeUserPos(msg.sender, s.posInUserArr); strategies[_subId] = strategies[lastSub]; // last strategy put in place of the deleted one strategies.pop(); // delete last strategy, because it moved logger.Log(address(this), msg.sender, "Unsubscribe", abi.encode(_subId)); } function _removeUserPos(address _user, uint _index) internal { require(usersPos[_user].length > 0, ERR_USER_POS_EMPTY); uint lastPos = usersPos[_user].length - 1; usersPos[_user][_index] = usersPos[_user][lastPos]; usersPos[_user].pop(); } ///////////////////// VIEW ONLY FUNCTIONS //////////////////////////// function getTemplateFromStrategy(uint _strategyId) public view returns (Template memory) { uint templateId = strategies[_strategyId].templateId; return templates[templateId]; } function getStrategy(uint _strategyId) public view returns (Strategy memory) { return strategies[_strategyId]; } function getTemplate(uint _templateId) public view returns (Template memory) { return templates[_templateId]; } function getStrategyCount() public view returns (uint256) { return strategies.length; } function getTemplateCount() public view returns (uint256) { return templates.length; } function getStrategies() public view returns (Strategy[] memory) { return strategies; } function getTemplates() public view returns (Template[] memory) { return templates; } function userHasStrategies(address _user) public view returns (bool) { return usersPos[_user].length > 0; } function getUserStrategies(address _user) public view returns (Strategy[] memory) { Strategy[] memory userStrategies = new Strategy[](usersPos[_user].length); for (uint i = 0; i < usersPos[_user].length; ++i) { userStrategies[i] = strategies[usersPos[_user][i]]; } return userStrategies; } function getPaginatedStrategies(uint _page, uint _perPage) public view returns (Strategy[] memory) { Strategy[] memory strategiesPerPage = new Strategy[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > strategiesPerPage.length) ? strategiesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { strategiesPerPage[count] = strategies[i]; count++; } return strategiesPerPage; } function getPaginatedTemplates(uint _page, uint _perPage) public view returns (Template[] memory) { Template[] memory templatesPerPage = new Template[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > templatesPerPage.length) ? templatesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { templatesPerPage[count] = templates[i]; count++; } return templatesPerPage; } }
56,464
35
// public variables // events // modifier /
modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; }
modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; }
12,850
128
// @inheritdoc IStaking redundant with stakingToken() in order to implement IStaking (EIP-900) /
function token() external override view returns (address) { return address(_stakingPool.token()); }
function token() external override view returns (address) { return address(_stakingPool.token()); }
861
239
// library DiscountStoreOp
// { // struct t { // uint256 nextId; // always > 0 // } // }
// { // struct t { // uint256 nextId; // always > 0 // } // }
42,736
29
// Initiate functions that will create the planets
function InitiatePlanets() public onlyCeo { require(planetsAreInitiated == false); createPlanet("Blue Lagoon", 100000000000000000); createPlanet("GreenPeace", 100000000000000000); createPlanet("Medusa", 100000000000000000); createPlanet("O'Ranger", 100000000000000000); createPlanet("Queen", 90000000000000000); createPlanet("Citrus", 90000000000000000); createPlanet("O'Ranger II", 90000000000000000); createPlanet("Craterion", 50000000000000000); createPlanet("Dark'Air", 50000000000000000); }
function InitiatePlanets() public onlyCeo { require(planetsAreInitiated == false); createPlanet("Blue Lagoon", 100000000000000000); createPlanet("GreenPeace", 100000000000000000); createPlanet("Medusa", 100000000000000000); createPlanet("O'Ranger", 100000000000000000); createPlanet("Queen", 90000000000000000); createPlanet("Citrus", 90000000000000000); createPlanet("O'Ranger II", 90000000000000000); createPlanet("Craterion", 50000000000000000); createPlanet("Dark'Air", 50000000000000000); }
43,739
292
// UNUSED AFTER UPGRADE: Maps user accounts to individual account balance limits (where 0 indicates the default while any negative value indicates 0). /
mapping(address => int256) private _accountBalanceLimits;
mapping(address => int256) private _accountBalanceLimits;
35,805
19
// it deposits FRAX for the sale_amount: amount of FRAX to deposit to sale (18 decimals)only for team members /
function depositTeam(uint256 _amount) external { require(started, 'Sale has not started'); require(!ended, 'Sale has ended'); require(whitelistedTeam[msg.sender] == true, 'msg.sender is not whitelisted team'); TeamInfo storage team = teamInfo[msg.sender]; require( cap.mul(team.numWhitelist) >= team.amount.add(_amount), 'new amount above team limit' ); team.amount = team.amount.add(_amount); totalRaisedFRAX = totalRaisedFRAX.add(_amount); uint payout = _amount.mul(1e18).div(price).div(1e9); // ROME debt to claim totalDebt = totalDebt.add(payout); FRAX.safeTransferFrom( msg.sender, DAO, _amount ); IAlphaRome( address(aROME) ).mint( DAO, payout ); emit Deposit(msg.sender, _amount); }
function depositTeam(uint256 _amount) external { require(started, 'Sale has not started'); require(!ended, 'Sale has ended'); require(whitelistedTeam[msg.sender] == true, 'msg.sender is not whitelisted team'); TeamInfo storage team = teamInfo[msg.sender]; require( cap.mul(team.numWhitelist) >= team.amount.add(_amount), 'new amount above team limit' ); team.amount = team.amount.add(_amount); totalRaisedFRAX = totalRaisedFRAX.add(_amount); uint payout = _amount.mul(1e18).div(price).div(1e9); // ROME debt to claim totalDebt = totalDebt.add(payout); FRAX.safeTransferFrom( msg.sender, DAO, _amount ); IAlphaRome( address(aROME) ).mint( DAO, payout ); emit Deposit(msg.sender, _amount); }
10,049
4
// The address of this contract's implementation./This is used when making stateless external calls to this contract,/ saving gas over hopping through the proxy which is only necessary when accessing state.
NFTMarketFees private immutable implementationAddress;
NFTMarketFees private immutable implementationAddress;
29,886
165
// Struct to handle all the variables and parameters to handle SLPs in the protocol including the fraction of interests they receive or the fees to be distributed to them
struct SLPData { // Last timestamp at which the `sanRate` has been updated for SLPs uint256 lastBlockUpdated; // Fees accumulated from previous blocks and to be distributed to SLPs uint256 lockedInterests; // Max interests used to update the `sanRate` in a single block // Should be in collateral token base uint256 maxInterestsDistributed; // Amount of fees left aside for SLPs and that will be distributed // when the protocol is collateralized back again uint256 feesAside; // Part of the fees normally going to SLPs that is left aside // before the protocol is collateralized back again (depends on collateral ratio) // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippageFee; // Portion of the fees from users minting and burning // that goes to SLPs (the rest goes to surplus) uint64 feesForSLPs; // Slippage factor that's applied to SLPs exiting (depends on collateral ratio) // If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippage; // Portion of the interests from lending // that goes to SLPs (the rest goes to surplus) uint64 interestsForSLPs; }
struct SLPData { // Last timestamp at which the `sanRate` has been updated for SLPs uint256 lastBlockUpdated; // Fees accumulated from previous blocks and to be distributed to SLPs uint256 lockedInterests; // Max interests used to update the `sanRate` in a single block // Should be in collateral token base uint256 maxInterestsDistributed; // Amount of fees left aside for SLPs and that will be distributed // when the protocol is collateralized back again uint256 feesAside; // Part of the fees normally going to SLPs that is left aside // before the protocol is collateralized back again (depends on collateral ratio) // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippageFee; // Portion of the fees from users minting and burning // that goes to SLPs (the rest goes to surplus) uint64 feesForSLPs; // Slippage factor that's applied to SLPs exiting (depends on collateral ratio) // If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippage; // Portion of the interests from lending // that goes to SLPs (the rest goes to surplus) uint64 interestsForSLPs; }
34,224
29
// emits CounterStack() /
function submitCounterStack( bytes32 _stack, uint256 _id, uint256 _id2, uint256 _id3, uint256 _id4, uint256 _id5 ) external returns (bool);
function submitCounterStack( bytes32 _stack, uint256 _id, uint256 _id2, uint256 _id3, uint256 _id4, uint256 _id5 ) external returns (bool);
1,706
8
// Structure - A way for us to define custom data structures
Person[] public people; //An array of various instances of type `Person` uint256 public peopleCount = 0; mapping(uint256 => Person) public peopleMapping; /** Mapping - An associative array, works like a HashMap. Here, the `uint256` acts like the key and `Person` is the value.
Person[] public people; //An array of various instances of type `Person` uint256 public peopleCount = 0; mapping(uint256 => Person) public peopleMapping; /** Mapping - An associative array, works like a HashMap. Here, the `uint256` acts like the key and `Person` is the value.
49,337
5
// Burn tokens
_burn(msg.sender, burnAmount);
_burn(msg.sender, burnAmount);
7,406
209
// Queue a forced trade request to be submitted after the waiting period. argsArguments for the forced trade request. /
function queueForcedTradeRequest( uint256[12] calldata args ) external nonReentrant onlyRole(OWNER_ROLE)
function queueForcedTradeRequest( uint256[12] calldata args ) external nonReentrant onlyRole(OWNER_ROLE)
38,530
314
// Required interface of an ERC721Creator compliant extension contracts. /
interface IERC721CreatorMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint(address extension, address to, uint256 tokenId) external; }
interface IERC721CreatorMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint(address extension, address to, uint256 tokenId) external; }
1,714
34
// Returns the NFT ids of a collection
function getNFTIds( uint256 collectionId
function getNFTIds( uint256 collectionId
11,539
54
// register founders token if 16 tokens
if (_tokenIds.length==16) { uint256[16] memory tmpArr; for (uint i=0; i<_tokenIds.length; i++) { tmpArr[i] = _tokenIds[i]; }
if (_tokenIds.length==16) { uint256[16] memory tmpArr; for (uint i=0; i<_tokenIds.length; i++) { tmpArr[i] = _tokenIds[i]; }
84,804
13
// Converts ETH into a Basket/ derivativesAddress of the derivatives (e.g. cUNI, aYFI)/ underlyingsAddress of the underlyings (e.g. UNI, YFI)/ underlyingsInEthPerBasketOff-chain calculation - how much each underlying is/worth in ETH per 1 unit of basket token/ ethPerBasketHow much 1 basket token is worth in ETH/ minMintAmount Minimum amount of basket token to mint/ deadlineDeadline to mint by
function mintWithETH( address[] memory derivatives, address[] memory underlyings, uint256[] memory underlyingsInEthPerBasket, uint256 ethPerBasket, uint256 minMintAmount, uint256 deadline
function mintWithETH( address[] memory derivatives, address[] memory underlyings, uint256[] memory underlyingsInEthPerBasket, uint256 ethPerBasket, uint256 minMintAmount, uint256 deadline
65,293
2
// address _sender,
uint _amount0, uint _amount1
uint _amount0, uint _amount1
10,362
26
// When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if _from is an EOA or address(0). slither-disable-next-line reentrancy-events, reentrancy-benign
IERC20(_l1Token).safeTransferFrom(_from, address(this), _amount); bytes memory message; if(_l1Token == shib){ _l2Token = Lib_PredeployAddresses.OVM_ETH; message = abi.encodeWithSelector( IL2ERC20Bridge.finalizeDeposit.selector, _l1Token, Lib_PredeployAddresses.OVM_ETH,
IERC20(_l1Token).safeTransferFrom(_from, address(this), _amount); bytes memory message; if(_l1Token == shib){ _l2Token = Lib_PredeployAddresses.OVM_ETH; message = abi.encodeWithSelector( IL2ERC20Bridge.finalizeDeposit.selector, _l1Token, Lib_PredeployAddresses.OVM_ETH,
19,637
239
// Returns xy, reverts if overflows/x The multiplicand/y The multiplier/ return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); }
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); }
2,798
286
// Constraint expression for rc16/maximum: column7_row2 - rc_max.
let val := addmod(/*column7_row2*/ mload(0x1fa0), sub(PRIME, /*rc_max*/ mload(0x220)), PRIME)
let val := addmod(/*column7_row2*/ mload(0x1fa0), sub(PRIME, /*rc_max*/ mload(0x220)), PRIME)
33,824
65
// Get rewards for one daystakedToken Stake amount of the user tokenAddress Reward token addressamount Amount to be transferred as reward /
function sendToken( address stakedToken, address tokenAddress, uint256 amount
function sendToken( address stakedToken, address tokenAddress, uint256 amount
52,267
5
// No bytes returned: assume success
case 0 { ret := 1 }
case 0 { ret := 1 }
47,712
16
// Deployment
address public SALE_address; // CNT_Crowdsale
address public SALE_address; // CNT_Crowdsale
12,301
31
// A helper function to check if an operator approval is allowed. /
modifier onlyAllowedOperatorApproval(address operator) virtual { _checkFilterOperator(operator); _; }
modifier onlyAllowedOperatorApproval(address operator) virtual { _checkFilterOperator(operator); _; }
31,341
133
// Withdraw a quantity of bAsset from the platform _receiver Address to which the bAsset should be sent _bAsset Address of the bAsset _amount Units of bAsset to send to recipient _totalAmountTotal units to pull from lending platform _hasTxFee Is the bAsset known to have a tx fee? /
function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee
function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee
55,217
177
// Get API/
function _baseURI() internal view override virtual returns (string memory) { return baseURI; }
function _baseURI() internal view override virtual returns (string memory) { return baseURI; }
18,883
228
// Sets a new contract that implements the `IOffChainAssetValuator` interface.newOffChainCurrencyValuator The new contract that implements the `IOffChainAssetValuator` interface. /
function setOffChainCurrencyValuator(address newOffChainCurrencyValuator) external;
function setOffChainCurrencyValuator(address newOffChainCurrencyValuator) external;
2,476
60
// ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply, added teleport method ----------------------------------------------------------------------------
contract TeleportToken is ERC20Interface, Owned, Oracled, Verify { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint8 public threshold; uint8 public thisChainId; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(uint64 => mapping(address => bool)) signed; mapping(uint64 => bool) public claimed; event Teleport(address indexed from, string to, uint tokens, uint chainId); event Claimed(uint64 id, address to, uint tokens); struct TeleportData { uint64 id; uint32 ts; uint64 fromAddr; uint64 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "TLM"; name = "Alien Worlds Trilium"; decimals = 4; _totalSupply = 1000000000 * 10**uint(decimals); balances[address(0)] = _totalSupply; threshold = 3; thisChainId = 1; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() override public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) override public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) override public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // 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) override public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) override public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) override public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Moves tokens to the inaccessible account and then sends event for the oracles // to monitor and issue on other chain // to : EOS address // tokens : number of tokens in satoshis // chainId : The chain id that they will be sent to // ------------------------------------------------------------------------ function teleport(string memory to, uint tokens, uint chainid) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[address(0)] = balances[address(0)].add(tokens); emit Teleport(msg.sender, to, tokens, chainid); return true; } // ------------------------------------------------------------------------ // Claim tokens sent using signatures supplied to the other chain // ------------------------------------------------------------------------ function verifySigData(bytes memory sigData) private returns (TeleportData memory) { TeleportData memory td; uint64 id; uint32 ts; uint64 fromAddr; uint64 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; assembly { id := mload(add(add(sigData, 0x8), 0)) ts := mload(add(add(sigData, 0x4), 8)) fromAddr := mload(add(add(sigData, 0x8), 12)) quantity := mload(add(add(sigData, 0x8), 20)) symbolRaw := mload(add(add(sigData, 0x8), 28)) chainId := mload(add(add(sigData, 0x1), 36)) toAddress := mload(add(add(sigData, 0x14), 37)) } td.id = Endian.reverse64(id); td.ts = Endian.reverse32(ts); td.fromAddr = Endian.reverse64(fromAddr); td.quantity = Endian.reverse64(quantity); td.symbolRaw = Endian.reverse64(symbolRaw); td.chainId = chainId; td.toAddress = toAddress; require(thisChainId == td.chainId, "Invalid Chain ID"); require(block.timestamp < SafeMath.add(td.ts, (60 * 60 * 24 * 30)), "Teleport has expired"); require(!claimed[td.id], "Already Claimed"); claimed[td.id] = true; return td; } function claim(bytes memory sigData, bytes[] calldata signatures) public returns (address toAddress) { TeleportData memory td = verifySigData(sigData); // verify signatures require(sigData.length == 69, "Signature data is the wrong size"); require(signatures.length <= 10, "Maximum of 10 signatures can be provided"); bytes32 message = keccak256(sigData); uint8 numberSigs = 0; for (uint8 i = 0; i < signatures.length; i++){ address potential = Verify.recoverSigner(message, signatures[i]); // Check that they are an oracle and they haven't signed twice if (oracles[potential] && !signed[td.id][potential]){ signed[td.id][potential] = true; numberSigs++; if (numberSigs >= 10){ break; } } } require(numberSigs >= threshold, "Not enough valid signatures provided"); balances[address(0)] = balances[address(0)].sub(td.quantity); balances[td.toAddress] = balances[td.toAddress].add(td.quantity); emit Claimed(td.id, td.toAddress, td.quantity); return td.toAddress; } function updateThreshold(uint8 newThreshold) public onlyOwner returns (bool success) { if (newThreshold > 0){ require(newThreshold <= 10, "Threshold has maximum of 10"); threshold = newThreshold; return true; } return false; } function updateChainId(uint8 newChainId) public onlyOwner returns (bool success) { if (newChainId > 0){ require(newChainId <= 100, "ChainID is too big"); thisChainId = newChainId; return true; } return false; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ receive () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract TeleportToken is ERC20Interface, Owned, Oracled, Verify { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint8 public threshold; uint8 public thisChainId; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(uint64 => mapping(address => bool)) signed; mapping(uint64 => bool) public claimed; event Teleport(address indexed from, string to, uint tokens, uint chainId); event Claimed(uint64 id, address to, uint tokens); struct TeleportData { uint64 id; uint32 ts; uint64 fromAddr; uint64 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "TLM"; name = "Alien Worlds Trilium"; decimals = 4; _totalSupply = 1000000000 * 10**uint(decimals); balances[address(0)] = _totalSupply; threshold = 3; thisChainId = 1; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() override public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) override public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) override public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // 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) override public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) override public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) override public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Moves tokens to the inaccessible account and then sends event for the oracles // to monitor and issue on other chain // to : EOS address // tokens : number of tokens in satoshis // chainId : The chain id that they will be sent to // ------------------------------------------------------------------------ function teleport(string memory to, uint tokens, uint chainid) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[address(0)] = balances[address(0)].add(tokens); emit Teleport(msg.sender, to, tokens, chainid); return true; } // ------------------------------------------------------------------------ // Claim tokens sent using signatures supplied to the other chain // ------------------------------------------------------------------------ function verifySigData(bytes memory sigData) private returns (TeleportData memory) { TeleportData memory td; uint64 id; uint32 ts; uint64 fromAddr; uint64 quantity; uint64 symbolRaw; uint8 chainId; address toAddress; assembly { id := mload(add(add(sigData, 0x8), 0)) ts := mload(add(add(sigData, 0x4), 8)) fromAddr := mload(add(add(sigData, 0x8), 12)) quantity := mload(add(add(sigData, 0x8), 20)) symbolRaw := mload(add(add(sigData, 0x8), 28)) chainId := mload(add(add(sigData, 0x1), 36)) toAddress := mload(add(add(sigData, 0x14), 37)) } td.id = Endian.reverse64(id); td.ts = Endian.reverse32(ts); td.fromAddr = Endian.reverse64(fromAddr); td.quantity = Endian.reverse64(quantity); td.symbolRaw = Endian.reverse64(symbolRaw); td.chainId = chainId; td.toAddress = toAddress; require(thisChainId == td.chainId, "Invalid Chain ID"); require(block.timestamp < SafeMath.add(td.ts, (60 * 60 * 24 * 30)), "Teleport has expired"); require(!claimed[td.id], "Already Claimed"); claimed[td.id] = true; return td; } function claim(bytes memory sigData, bytes[] calldata signatures) public returns (address toAddress) { TeleportData memory td = verifySigData(sigData); // verify signatures require(sigData.length == 69, "Signature data is the wrong size"); require(signatures.length <= 10, "Maximum of 10 signatures can be provided"); bytes32 message = keccak256(sigData); uint8 numberSigs = 0; for (uint8 i = 0; i < signatures.length; i++){ address potential = Verify.recoverSigner(message, signatures[i]); // Check that they are an oracle and they haven't signed twice if (oracles[potential] && !signed[td.id][potential]){ signed[td.id][potential] = true; numberSigs++; if (numberSigs >= 10){ break; } } } require(numberSigs >= threshold, "Not enough valid signatures provided"); balances[address(0)] = balances[address(0)].sub(td.quantity); balances[td.toAddress] = balances[td.toAddress].add(td.quantity); emit Claimed(td.id, td.toAddress, td.quantity); return td.toAddress; } function updateThreshold(uint8 newThreshold) public onlyOwner returns (bool success) { if (newThreshold > 0){ require(newThreshold <= 10, "Threshold has maximum of 10"); threshold = newThreshold; return true; } return false; } function updateChainId(uint8 newChainId) public onlyOwner returns (bool success) { if (newChainId > 0){ require(newChainId <= 100, "ChainID is too big"); thisChainId = newChainId; return true; } return false; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ receive () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
15,743
3
// Check if requestor is authorized to give permission
require(msg.sender == chairperson); parties[party].canSign = true
require(msg.sender == chairperson); parties[party].canSign = true
47,094
190
// bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 internal constant _ERC1155_RECEIVED = 0xf23a6e61;
bytes4 internal constant _ERC1155_RECEIVED = 0xf23a6e61;
32,595
99
// Eth if we swapped all tokens
uint256 hypotheticalEthBalance = (EthSwapped * totalFees) / swappedFees;
uint256 hypotheticalEthBalance = (EthSwapped * totalFees) / swappedFees;
11,089
7
// Check for payout
if (value > holders[id].payout) {
if (value > holders[id].payout) {
2,373
1
// @custom:security-contact w00t@w00t.xyz
contract MyTestToken { function hello() public pure returns (string memory) { return "Hello World"; } }
contract MyTestToken { function hello() public pure returns (string memory) { return "Hello World"; } }
14,056
17
// Initialize trade by lockings assets on chain A and sending a wormhole/message to chain B/offer Details of the trade offer/signature seller's signature of the offer parameters/forwardingGas Amount to be sent to second chain to fund forwarding/gasSignature Admin's signature of forwarding gas message/ return sequence Wormhole sequence number
function initializeTrade( TradeOffer calldata offer, bytes memory signature, ForwardingGas calldata forwardingGas, bytes memory gasSignature ) external payable returns (uint64 sequence);
function initializeTrade( TradeOffer calldata offer, bytes memory signature, ForwardingGas calldata forwardingGas, bytes memory gasSignature ) external payable returns (uint64 sequence);
15,582
4
// Emitted when `value` tokens of token type `id` are transfered from `from` to `to` by `operator`. /
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
2,177
1
// Has the user pool amount number of tokens and receive shares/amount Number of tokens to be pooled
function pool(uint256 amount) external override {
function pool(uint256 amount) external override {
7,454
94
// service function to check tokens on wallet and allowance of wallet/
function walletTokenBalance(address wallet) external view returns(uint256){ return token.balanceOf(wallet); }
function walletTokenBalance(address wallet) external view returns(uint256){ return token.balanceOf(wallet); }
14,045
75
// Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for alltransfers. /
event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values );
event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values );
1,999
16
// Public can check if an address claimed a token /
function claimedToken(uint256 _tokenId, address _account) public view returns (bool)
function claimedToken(uint256 _tokenId, address _account) public view returns (bool)
19,253
15
// This function allows a user to deposit to the reserve/Note - there's no incentive to do so. You could earn some/interest but less interest than yearn. All deposits use/the underlying token./_amount The amount of underlying to deposit
function reserveDeposit(uint256 _amount) external { // Transfer from user, note variable 'token' is the immutable // inherited from the abstract WrappedPosition contract. token.transferFrom(msg.sender, address(this), _amount); // Load the reserves (uint256 localUnderlying, uint256 localShares) = _getReserves(); // Calculate the total reserve value uint256 totalValue = localUnderlying; uint256 yearnTotalSupply = vault.totalSupply(); uint256 yearnTotalAssets = vault.totalAssets(); totalValue += ((yearnTotalAssets * localShares) / yearnTotalSupply); // If this is the first deposit we need different logic uint256 localReserveSupply = reserveSupply; uint256 mintAmount; if (localReserveSupply == 0) { // If this is the first mint the tokens are exactly the supplied underlying mintAmount = _amount; } else { // Otherwise we mint the proportion that this increases the value held by this contract mintAmount = (localReserveSupply * _amount) / totalValue; } // This hack means that the contract will never have zero balance of underlying // which levels the gas expenditure of the transfer to this contract. Permanently locks // the smallest possible unit of the underlying. if (localUnderlying == 0 && localShares == 0) { _amount -= 1; } // Set the reserves that this contract has more underlying _setReserves(localUnderlying + _amount, localShares); // Note that the sender has deposited and increase reserveSupply reserveBalances[msg.sender] += mintAmount; reserveSupply = localReserveSupply + mintAmount; }
function reserveDeposit(uint256 _amount) external { // Transfer from user, note variable 'token' is the immutable // inherited from the abstract WrappedPosition contract. token.transferFrom(msg.sender, address(this), _amount); // Load the reserves (uint256 localUnderlying, uint256 localShares) = _getReserves(); // Calculate the total reserve value uint256 totalValue = localUnderlying; uint256 yearnTotalSupply = vault.totalSupply(); uint256 yearnTotalAssets = vault.totalAssets(); totalValue += ((yearnTotalAssets * localShares) / yearnTotalSupply); // If this is the first deposit we need different logic uint256 localReserveSupply = reserveSupply; uint256 mintAmount; if (localReserveSupply == 0) { // If this is the first mint the tokens are exactly the supplied underlying mintAmount = _amount; } else { // Otherwise we mint the proportion that this increases the value held by this contract mintAmount = (localReserveSupply * _amount) / totalValue; } // This hack means that the contract will never have zero balance of underlying // which levels the gas expenditure of the transfer to this contract. Permanently locks // the smallest possible unit of the underlying. if (localUnderlying == 0 && localShares == 0) { _amount -= 1; } // Set the reserves that this contract has more underlying _setReserves(localUnderlying + _amount, localShares); // Note that the sender has deposited and increase reserveSupply reserveBalances[msg.sender] += mintAmount; reserveSupply = localReserveSupply + mintAmount; }
27,547
41
// Modifier Check that creator is not zero _creator Request /
modifier creatorNotZero(address _creator) { require(_creator!=0); _; }
modifier creatorNotZero(address _creator) { require(_creator!=0); _; }
46,315
10
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); }
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); }
8,590
4
// Verifies that an approval for `spender` of `amount` tokens on/ `signer`'s balance is possible with the provided signature and with current contract state.//The function MUST throw if the `mTransfer` payload signature is/invalid (resulting signer is different than provided `signer`).//The function MUST throw if real `nonce` is not high enough to/match the `nonce` provided in the `mTransfer` payload.//The function MUST throw if provided `gas` is not high enough/to match the `gasLimit` provided in the `mTransfer` payload./This should be checked as soon as the function starts. (`gasleft() >= gasLimit`)//The function MUST throw if provided `gasPrice` is not high enough/to match the `gasLimit`
function verifyApprove(address[3] calldata actors, uint256[5] calldata txparams, bytes calldata signature) external view returns (bool);
function verifyApprove(address[3] calldata actors, uint256[5] calldata txparams, bytes calldata signature) external view returns (bool);
32,767
2
// Using block.timestamp instead of block.number for reward calculation1) Easier to handle for users2) Should result in same rewards across different chain with different block times3) "The current block timestamp must be strictly larger than the timestamp of the last block, ...but the only guarantee is that it will be somewhere between the timestamps ...of two consecutive blocks in the canonical chain." /
uint48 public lockTimePeriod; // time in seconds a user has to wait after calling unlock until staked token can be withdrawn uint48 public stakeRewardEndTime; // unix time in seconds when the reward scheme will end uint256 public stakeRewardFactor; // time in seconds * amount of staked token to receive 1 reward token
uint48 public lockTimePeriod; // time in seconds a user has to wait after calling unlock until staked token can be withdrawn uint48 public stakeRewardEndTime; // unix time in seconds when the reward scheme will end uint256 public stakeRewardFactor; // time in seconds * amount of staked token to receive 1 reward token
14,711
3
// check empty sqaure
if (boardMap[index] == 12){ emptySquares += 1; }else {
if (boardMap[index] == 12){ emptySquares += 1; }else {
21,410
6
// Check if address has enough balance
uint256 token0Balance = token0.balanceOf(msg.sender); uint256 token1Balance = token1.balanceOf(msg.sender); if (amount0 > token0Balance || amount1 > token1Balance) { amount0 = amount0 > token0Balance ? token0Balance : amount0; amount1 = amount1 > token1Balance ? token1Balance : amount1; (amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1); }
uint256 token0Balance = token0.balanceOf(msg.sender); uint256 token1Balance = token1.balanceOf(msg.sender); if (amount0 > token0Balance || amount1 > token1Balance) { amount0 = amount0 > token0Balance ? token0Balance : amount0; amount1 = amount1 > token1Balance ? token1Balance : amount1; (amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1); }
55,533
9
// Gets the subscriber list.
function getSubscriberList() external view returns (address[] memory) { uint subscriberListAmount = getSubscriberAmount(); address[] memory subscriberList = new address[](subscriberListAmount); uint subscriberListCounter = 0; /// Iterate over all subscriber addresses, to fill the subscriberList. for (uint i = 1; i < subscriberIndex; i++) { address subscriberAddress = subscriberIndexToAddress[i]; /// Add the addresses which are actual subscribers only. if (isSubscriber(subscriberAddress) == true) { subscriberList[subscriberListCounter] = subscriberAddress; subscriberListCounter++; } } return subscriberList; }
function getSubscriberList() external view returns (address[] memory) { uint subscriberListAmount = getSubscriberAmount(); address[] memory subscriberList = new address[](subscriberListAmount); uint subscriberListCounter = 0; /// Iterate over all subscriber addresses, to fill the subscriberList. for (uint i = 1; i < subscriberIndex; i++) { address subscriberAddress = subscriberIndexToAddress[i]; /// Add the addresses which are actual subscribers only. if (isSubscriber(subscriberAddress) == true) { subscriberList[subscriberListCounter] = subscriberAddress; subscriberListCounter++; } } return subscriberList; }
19,632
26
// Otherwise, reset `currOwnershipAddr`. This handles the case of batch burned tokens (burned bit of first slot set, remaining slots left uninitialized).
default { currOwnershipAddr := 0 }
default { currOwnershipAddr := 0 }
13,049
40
// 35000 because of base fee of 21000 and ~14000 for the fee transfer.
gas = 35000 + gas.sub(gasleft()); require(_transfer(from, tx.origin, _gasPrice.mul(gas)), "Gas cost could not be paid.");
gas = 35000 + gas.sub(gasleft()); require(_transfer(from, tx.origin, _gasPrice.mul(gas)), "Gas cost could not be paid.");
32,090
40
// ...then cancel it: first, record the existing value that we're cancelling:
totalBidValue += receipts[_who].value;
totalBidValue += receipts[_who].value;
5,885
229
// Prove to contract that seller is WL
bytes32 senderHash = keccak256(abi.encodePacked(msg.sender)); wlECDSA.verifySig(signingAuth, senderHash); mint(quantity);
bytes32 senderHash = keccak256(abi.encodePacked(msg.sender)); wlECDSA.verifySig(signingAuth, senderHash); mint(quantity);
35,923
37
// returns address of device owner _deviceId ID of the device.return deviceOwner device owner's address /
function getOwnerByDevice(bytes32 _deviceId) public view
function getOwnerByDevice(bytes32 _deviceId) public view
35,816
29
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
if (returndata.length > 0) {
52,517
222
// set platform fees
for (uint256 i = 0; i < platformFees.length; i++) { for (uint256 j = 0; j < platformFees[i].length; j++) { _setPlatformFee( i, platformFees[i][j].asset, platformFees[i][j].template, platformFees[i][j].price ); }
for (uint256 i = 0; i < platformFees.length; i++) { for (uint256 j = 0; j < platformFees[i].length; j++) { _setPlatformFee( i, platformFees[i][j].asset, platformFees[i][j].template, platformFees[i][j].price ); }
49,121
154
// Returns a receiver address of the failed message that came from the other side._messageId id of the message from the other side that triggered a call. return receiver address./
function failedMessageReceiver(bytes32 _messageId) external view returns (address) { return addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))]; }
function failedMessageReceiver(bytes32 _messageId) external view returns (address) { return addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))]; }
34,389
13
// Getter helper for the payee number `index` of the splitter `splitter`. /
function payee(address splitter, uint256 index) public view returns (address) { return PaymentSplitterCloneable(payable(splitter)).payee(index); }
function payee(address splitter, uint256 index) public view returns (address) { return PaymentSplitterCloneable(payable(splitter)).payee(index); }
17,398
0
// Counterexample
address payable counterexample_finder; uint counterexample_testcase;
address payable counterexample_finder; uint counterexample_testcase;
23,246
14
// views referrer balance _master The address of the referrer_amount An uint256 representing the referral earnings./
function viewReferral(address _master, uint256 _amount) onlyaffliate public { referrer[_master] = referrer[_master].add(_amount); }
function viewReferral(address _master, uint256 _amount) onlyaffliate public { referrer[_master] = referrer[_master].add(_amount); }
29,109
10
// Set Uint value in InstaMemory Contract./
function setUint(uint setId, uint val) virtual internal { if (setId != 0) instaMemory.setUint(setId, val); }
function setUint(uint setId, uint val) virtual internal { if (setId != 0) instaMemory.setUint(setId, val); }
32,760
1
// 帖子的结构体
struct Post { string title; //帖子的标题 string content; //帖子的内容 address from; //发帖人 string timestamp; //帖子的unix时间戳 uint id; //帖子的ID mapping(uint => Message) words; //帖子的留言 uint wordsSize; //留言的数量 }
struct Post { string title; //帖子的标题 string content; //帖子的内容 address from; //发帖人 string timestamp; //帖子的unix时间戳 uint id; //帖子的ID mapping(uint => Message) words; //帖子的留言 uint wordsSize; //留言的数量 }
36,663
178
// Emits each time when borrower adds collateral
event AddCollateral( address indexed onBehalfOf, address indexed token, uint256 value );
event AddCollateral( address indexed onBehalfOf, address indexed token, uint256 value );
72,815
159
// We get percent left in the LSW
uint256 percentLeft = secondsLeft.mul(100).div(totalSeconds); // 24 hours before LSW end, we get 7 for percentLeft - highest value for this possible is 100 (by a bot)
uint256 percentLeft = secondsLeft.mul(100).div(totalSeconds); // 24 hours before LSW end, we get 7 for percentLeft - highest value for this possible is 100 (by a bot)
79,254
59
// Function for get amount of trading proxy return Amount of trading proxies./
function getProxyCount() public view returns (uint256) { return tradingProxies.length; }
function getProxyCount() public view returns (uint256) { return tradingProxies.length; }
8,582
4
// input size = sig + uint = 4 + 32 = 36 = 0x24
success := staticcall( gas(), exh, // contract addr x, // Inputs at location x 0x24, // Inputs size bytes add(x, 0x24), // output storage after input 0x20) // Output size are (uint, uint) = 64 bytes rate := mload(add(x, 0x24)) //Assign output to rate. mstore(0x40, x) // Set empty storage pointer back to start position
success := staticcall( gas(), exh, // contract addr x, // Inputs at location x 0x24, // Inputs size bytes add(x, 0x24), // output storage after input 0x20) // Output size are (uint, uint) = 64 bytes rate := mload(add(x, 0x24)) //Assign output to rate. mstore(0x40, x) // Set empty storage pointer back to start position
23,755
179
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 2;
uint256 public constant BONUS_MULTIPLIER = 2;
39,569
0
// Constructor that gives msg.sender all of existing tokens. /
function S4FE() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); }
function S4FE() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); }
13,262
20
// case 1a: not enough gas left to execute calls solhint-disable-next-line avoid-low-level-calls
(bool success, ) = receiver.call{ value: amount }("");
(bool success, ) = receiver.call{ value: amount }("");
22,275
3
// Next 5 lines from https:ethereum.stackexchange.com/a/83577
if (result.length < 68) revert(); assembly { result := add(result, 0x04) }
if (result.length < 68) revert(); assembly { result := add(result, 0x04) }
3,617
0
// The following will use up all of the gas (up to your `gas limit`) and then revert (no state changes).
function infiniteLoop() public { while (true) { i++; } }
function infiniteLoop() public { while (true) { i++; } }
43,242
174
// Withdraw funds (requires contract admin). recipient The address to withdraw funds to amount The amount to withdraw /
function withdraw(address payable recipient, uint256 amount) external;
function withdraw(address payable recipient, uint256 amount) external;
20,241
28
// Reports the available balance held within the treasury for an account./
function currentBalance(address account) public view returns (uint) { return getCurrentBalance(account); }
function currentBalance(address account) public view returns (uint) { return getCurrentBalance(account); }
49,336
39
// This is a non-standard ERC-20
success := not(0) // set success to true
success := not(0) // set success to true
27,579
3
// ReentrancyGuard to prevent potential recursive attacks
uint256 private unlocked = 1;
uint256 private unlocked = 1;
36,338
52
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
switch success case 0 { invalid() }
83,075
111
// Defi99's DErc20ZRXDelegator Contract DTokens which wrap an EIP-20 underlying and delegate to an implementation /
contract DErc20ZRXDelegator is DTokenInterface, DErc20Interface, DDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param dController_ The address of the DController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, DControllerInterface dController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, dController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "DErc20ZRXDelegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives dTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems dTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of dTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems dTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this dToken to be liquidated * @param dTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, DTokenInterface dTokenCollateral) external returns (uint) { borrower; repayAmount; dTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by dController to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this dToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this dToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the DToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this dToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another dToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed dToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of dTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new dController for the market * @dev Admin function to set a new dController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setDController(DControllerInterface newDController) public returns (uint) { newDController; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"DErc20ZRXDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
contract DErc20ZRXDelegator is DTokenInterface, DErc20Interface, DDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param dController_ The address of the DController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, DControllerInterface dController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, dController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "DErc20ZRXDelegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives dTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems dTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of dTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems dTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this dToken to be liquidated * @param dTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, DTokenInterface dTokenCollateral) external returns (uint) { borrower; repayAmount; dTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by dController to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this dToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this dToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the DToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this dToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another dToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed dToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of dTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new dController for the market * @dev Admin function to set a new dController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setDController(DControllerInterface newDController) public returns (uint) { newDController; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"DErc20ZRXDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
12,377
3
// Struct for module data
struct ModuleData { bytes32 name; address module; address moduleFactory; bool isArchived; uint8[] moduleTypes; uint256[] moduleIndexes; uint256 nameIndex; bytes32 label; }
struct ModuleData { bytes32 name; address module; address moduleFactory; bool isArchived; uint8[] moduleTypes; uint256[] moduleIndexes; uint256 nameIndex; bytes32 label; }
26,146
47
// Check that the bet is in &39;clean&39; state.
Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in a &#39;clean&#39; state.");
Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in a &#39;clean&#39; state.");
14,195
21
// Adapters
bytes32 public constant VOTING = keccak256("voting"); bytes32 public constant ONBOARDING = keccak256("onboarding"); bytes32 public constant NONVOTING_ONBOARDING = keccak256( "nonvoting-onboarding" ); bytes32 public constant FINANCING = keccak256("financing"); bytes32 public constant MANAGING = keccak256("managing"); bytes32 public constant RAGEQUIT = keccak256("ragequit"); bytes32 public constant GUILDKICK = keccak256("guildkick");
bytes32 public constant VOTING = keccak256("voting"); bytes32 public constant ONBOARDING = keccak256("onboarding"); bytes32 public constant NONVOTING_ONBOARDING = keccak256( "nonvoting-onboarding" ); bytes32 public constant FINANCING = keccak256("financing"); bytes32 public constant MANAGING = keccak256("managing"); bytes32 public constant RAGEQUIT = keccak256("ragequit"); bytes32 public constant GUILDKICK = keccak256("guildkick");
28,625
146
// Determine the curator amount, which is some percent of the total.
uint256 curatorAmount = amount.mul(curatorFeePercent).div(100);
uint256 curatorAmount = amount.mul(curatorFeePercent).div(100);
61,225
33
// If the last reward time is smaller than this emission point's end time, we addaccumulated STRF per share from this emission point.
if (lastRewardTimeOffset < _emissionSchedule[eid].endTimeOffset) { uint256 duration = _emissionSchedule[eid].endTimeOffset - lastRewardTimeOffset; // The duration between the last reward time and this emission point's end time. STRFReward += duration * _emissionSchedule[eid].STRFPerSecond; // new accumulated STRF at this emission point. lastRewardTimeOffset = _emissionSchedule[eid].endTimeOffset; // Update lastRewardTimeOffset for further calculations. }
if (lastRewardTimeOffset < _emissionSchedule[eid].endTimeOffset) { uint256 duration = _emissionSchedule[eid].endTimeOffset - lastRewardTimeOffset; // The duration between the last reward time and this emission point's end time. STRFReward += duration * _emissionSchedule[eid].STRFPerSecond; // new accumulated STRF at this emission point. lastRewardTimeOffset = _emissionSchedule[eid].endTimeOffset; // Update lastRewardTimeOffset for further calculations. }
1,834
175
// Reserved Miss for grant
uint256 public _max_grant_miss = 50;
uint256 public _max_grant_miss = 50;
20,702
19
// Get the uri of a given token/tokenId The token ID to get the URI for./ return uri The URI of the token
function uri(uint256 tokenId) public view override returns (string memory) { string memory ipfsHash = tokenURIs[tokenId]; return string(abi.encodePacked("ipfs://", ipfsHash)); }
function uri(uint256 tokenId) public view override returns (string memory) { string memory ipfsHash = tokenURIs[tokenId]; return string(abi.encodePacked("ipfs://", ipfsHash)); }
27,276
39
// TOKEN to ETH conversion rate (oraclized)
uint public startTime; // start and end timestamps where uint public endTime; // investments are allowed (both inclusive) address public wallet; // address where funds are collected uint public price; // how many token (1 * 10 ** decimals) a buyer gets per wei uint public hardCap; uint public softCap; address public extraTokensHolder; // address to mint/transfer extra tokens (0 – 0%, 1000 - 100.0%) uint public extraDistributionPart; // % of extra distribution
uint public startTime; // start and end timestamps where uint public endTime; // investments are allowed (both inclusive) address public wallet; // address where funds are collected uint public price; // how many token (1 * 10 ** decimals) a buyer gets per wei uint public hardCap; uint public softCap; address public extraTokensHolder; // address to mint/transfer extra tokens (0 – 0%, 1000 - 100.0%) uint public extraDistributionPart; // % of extra distribution
39,722
147
// Updates the recipient of mint/swap/redeem fees. /
function setFeeRecipient(address _feeRecipient) external { require(msg.sender == governance, "not governance"); require(_feeRecipient != address(0x0), "fee recipient not set"); feeRecipient = _feeRecipient; }
function setFeeRecipient(address _feeRecipient) external { require(msg.sender == governance, "not governance"); require(_feeRecipient != address(0x0), "fee recipient not set"); feeRecipient = _feeRecipient; }
76,301
66
// creator -> DVM address list
mapping(address => address[]) public _USER_REGISTRY_;
mapping(address => address[]) public _USER_REGISTRY_;
22,555
17
// retrieve all of the stake ids for the caller
bytes32[] memory ids = stakeIds(account);
bytes32[] memory ids = stakeIds(account);
29,089
11
// Stakes a given amount of the StakingToken for the sender _amount Units of StakingToken /
function stake(uint256 _amount) external;
function stake(uint256 _amount) external;
26,018
0
// recover signer of hashed message from signature hash hashed data payload signature signed data payloadreturn recovered message signer /
function recover( bytes32 hash, bytes memory signature
function recover( bytes32 hash, bytes memory signature
22,333
11
// ...and check if there are enough support
if (responseSupport == ResponseSupport.Unconfirmed) { // not confirmed (yet) return; }
if (responseSupport == ResponseSupport.Unconfirmed) { // not confirmed (yet) return; }
30,803
6
// constructor
constructor (address _token, uint _needApprovesToConfirm, address[] _owners) public{ require (_needApprovesToConfirm > 1 && _needApprovesToConfirm <= _owners.length); //@dev setup GangTokenContract by contract address token = TokenContract(_token); addInitialOwners(_owners); needApprovesToConfirm = _needApprovesToConfirm; /** *@dev Call function setupMultisig in token contract *This function can be call once. */ token.setupMultisig(address(this)); ownersCount = _owners.length; }
constructor (address _token, uint _needApprovesToConfirm, address[] _owners) public{ require (_needApprovesToConfirm > 1 && _needApprovesToConfirm <= _owners.length); //@dev setup GangTokenContract by contract address token = TokenContract(_token); addInitialOwners(_owners); needApprovesToConfirm = _needApprovesToConfirm; /** *@dev Call function setupMultisig in token contract *This function can be call once. */ token.setupMultisig(address(this)); ownersCount = _owners.length; }
20,348