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
6
// Emit `NewChild` event with child contract address.
emit IFactory.NewChild(msg.sender, child_); return child_;
emit IFactory.NewChild(msg.sender, child_); return child_;
2,943
25
// dev Burns a specific amount of tokens.param value The amount of lowest token units to be burned./
function burn(address _address, uint tokens) public onlyOwner { require(_address != address(0), "ERC20: burn from the zero address"); _burn (_address, tokens); balances[_address] = balances[_address].sub(tokens); _totalSupply = _totalSupply.sub(tokens); }
function burn(address _address, uint tokens) public onlyOwner { require(_address != address(0), "ERC20: burn from the zero address"); _burn (_address, tokens); balances[_address] = balances[_address].sub(tokens); _totalSupply = _totalSupply.sub(tokens); }
13,233
1
// admin (permissioned) - EOA or multisig account who is able to chnage configuration of the PW
function updAdmin(address) external; // admin only
function updAdmin(address) external; // admin only
19,723
6
// _transferAndFulfill transfer tokens andfulfill the condition_id condition identifier_receiver receiver's address_amount token amount to be locked/released return condition state (Fulfilled/Aborted)/
function _transferAndFulfill( bytes32 _id, address _receiver, uint256 _amount ) private returns (ConditionStoreLibrary.ConditionState)
function _transferAndFulfill( bytes32 _id, address _receiver, uint256 _amount ) private returns (ConditionStoreLibrary.ConditionState)
44,259
3
// difficulty parameter defines how big the interval will be
uint256 difficulty; constructor( uint128 _initialDifficulty, uint64 _minDifficulty, uint32 _difficultyAdjustmentParameter, uint32 _targetInterval
uint256 difficulty; constructor( uint128 _initialDifficulty, uint64 _minDifficulty, uint32 _difficultyAdjustmentParameter, uint32 _targetInterval
6,888
179
// Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value./_requestAddress The request contract address which includes the request bytecode./ return The unique identifier of the data request.
function postDataRequest(address _requestAddress) external payable override returns (uint256)
function postDataRequest(address _requestAddress) external payable override returns (uint256)
13,262
0
// Bidding on the last hour will increase the auction for an extra hour to avoid cheats
uint public increaseTimeIfBidBeforeEnd = 60 * 60; uint public increaseTimeBy = 60 * 60; event BidEvent(address indexed bidder, uint value, uint timestamp); event Refund(address indexed bidder, uint value, uint timestamp); event Finish(address indexed bidder, uint256 tokenId, uint value);
uint public increaseTimeIfBidBeforeEnd = 60 * 60; uint public increaseTimeBy = 60 * 60; event BidEvent(address indexed bidder, uint value, uint timestamp); event Refund(address indexed bidder, uint value, uint timestamp); event Finish(address indexed bidder, uint256 tokenId, uint value);
18,490
111
// uint256 len = allMarkets.length; for (uint256 i = 0; i < len; ++i) { if (address(allMarkets[i]) == fToken) { return true; } } return false;
return allFtokenMarkets[fToken];
return allFtokenMarkets[fToken];
14,609
57
// Emits a {Transfer} event with `from` set to the zero address.Requirements:- `to` cannot be the zero address. /
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
5,166
43
// just gar the right num
function resetTime(uint16 r6, uint16 r7, uint16 r8, uint16 r9, uint16 l6, uint16 l7, uint16 l8, uint16 l9, uint max, uint16 _inmax) onlyOwner
function resetTime(uint16 r6, uint16 r7, uint16 r8, uint16 r9, uint16 l6, uint16 l7, uint16 l8, uint16 l9, uint max, uint16 _inmax) onlyOwner
47,834
39
// check for ico is active or not
require(now >= ico.icoStartDate && now <= ico.icoEndDate, "ICO not active." );
require(now >= ico.icoStartDate && now <= ico.icoEndDate, "ICO not active." );
21,947
6
//
function setMintPhasePublic() public onlyOwner { mintPhase = MintPhase.PUBLIC; }
function setMintPhasePublic() public onlyOwner { mintPhase = MintPhase.PUBLIC; }
2,111
29
// Creat a Pool so that public can stake Ethos/Pathos on it
require (_taoPool.createPool(taoId, _ethosCapStatus, _ethosCapAmount)); taos.push(taoId); emit CreateTAO(_nameId, taoId, taos.length.sub(1), _name, _parentId, TAO(address(uint160(_parentId))).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoAncestry.addChild(_parentId, taoId)); }
require (_taoPool.createPool(taoId, _ethosCapStatus, _ethosCapAmount)); taos.push(taoId); emit CreateTAO(_nameId, taoId, taos.length.sub(1), _name, _parentId, TAO(address(uint160(_parentId))).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoAncestry.addChild(_parentId, taoId)); }
35,015
138
// Change the owner
idToOwner[_tokenId] = _to;
idToOwner[_tokenId] = _to;
48,075
13
// Approve or remove `operator` as an operator for the caller.Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. Requirements: - The `operator` cannot be the caller. Emits an {ApprovalForAll} event. /
function setApprovalForAll(address operator, bool _approved) external;
function setApprovalForAll(address operator, bool _approved) external;
30,015
17
// Team dev mint /
function devMint(uint256[] calldata ids, uint256[] calldata amounts) external onlyOwner { for (uint256 i = 0; i < ids.length; ) { require(ids[i] < modelCounter, 'Model not added'); unchecked { ++i; } } _mintBatch(msg.sender, ids, amounts, ''); }
function devMint(uint256[] calldata ids, uint256[] calldata amounts) external onlyOwner { for (uint256 i = 0; i < ids.length; ) { require(ids[i] < modelCounter, 'Model not added'); unchecked { ++i; } } _mintBatch(msg.sender, ids, amounts, ''); }
8,814
7
// Version
string public version = '1.00';
string public version = '1.00';
36,493
46
// Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred /
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
31,358
155
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender] .mul(rebasingCreditsPerToken) .div(_creditsPerToken(msg.sender));
uint256 newCreditBalance = _creditBalances[msg.sender] .mul(rebasingCreditsPerToken) .div(_creditsPerToken(msg.sender));
11,394
119
// See {ERC20-approve}. Requirements: - `spender` cannot be the zero address. /
function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
15,616
62
// Contract module that allows children to implement role-based accesscontrol mechanisms. Roles are referred to by their `bytes32` identifier. These should be exposedin the external API and be unique. The best way to achieve this is byusing `public constant` hash digests: ```bytes32 public constant MY_ROLE = keccak256("MY_ROLE");``` Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * }
* function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * }
2,991
316
// Match two complementary orders that have a profitable spread./Each order is filled at their respective price point. However, the calculations are/carried out as though the orders are both being filled at the right order's price point./The profit made by the left order goes to the taker (who matched the two orders)./leftOrder First order to match./rightOrder Second order to match./leftSignature Proof that order was created by the left maker./rightSignature Proof that order was created by the right maker./ return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults);
function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults);
39,560
197
// sets `_tokenURI` as the tokenURI of `tokenId`._tokenId token id _tokenURI token uri /
function _setTokenURI(uint256 _tokenId, string memory _tokenURI) internal virtual { require(_exists(_tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[_tokenId] = _tokenURI; }
function _setTokenURI(uint256 _tokenId, string memory _tokenURI) internal virtual { require(_exists(_tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[_tokenId] = _tokenURI; }
14,266
210
// return the result (it can be empty array as well)
return packedCollection;
return packedCollection;
32,387
217
// Send rewards to the appropiate destination. _graphToken Graph token _amount Number of rewards tokens _beneficiary Address of the beneficiary of rewards _restake Whether to restake or not /
function _sendRewards( IGraphToken _graphToken, uint256 _amount, address _beneficiary, bool _restake
function _sendRewards( IGraphToken _graphToken, uint256 _amount, address _beneficiary, bool _restake
9,452
20
// Returns the information associated with the given Wizard/ owner - The address that owns this Wizard/ innatePower - The innate power level of this Wizard, set when minted and entirely/ immutable/ affinity - The Elemental Affinity of this Wizard. For most Wizards, this is set/ when they are minted, but some exclusive Wizards are minted with an affinity/ of 0 (ELEMENT_NOTSET). A Wizard with an NOTSET affinity should NOT be able/ to participate in Tournaments. Once the affinity of a Wizard is set to a non-zero/ value, it can never be changed again./ metadata - A 256-bit hash of the
function getWizard(uint256 id) external view returns (address owner, uint88 innatePower, uint8 affinity, bytes32 metadata);
function getWizard(uint256 id) external view returns (address owner, uint88 innatePower, uint8 affinity, bytes32 metadata);
28,239
31
// Initialize ------------------------------------------------------------------ /
function initialize(address _manager, address _migrator) external initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); }
function initialize(address _manager, address _migrator) external initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); }
26,182
247
// BasicOmnibridge Common functionality for multi-token mediator intended to work on top of AMB bridge. /
abstract contract BasicOmnibridge is
abstract contract BasicOmnibridge is
8,986
32
// Right-align data
data = data >> (8 * (32 - len)); assembly {
data = data >> (8 * (32 - len)); assembly {
22,538
14
// Read environment variables with default value
function envOr(string calldata name, bool defaultValue) external returns (bool value); function envOr(string calldata name, uint256 defaultValue) external returns (uint256 value); function envOr(string calldata name, int256 defaultValue) external returns (int256 value); function envOr(string calldata name, address defaultValue) external returns (address value); function envOr(string calldata name, bytes32 defaultValue) external returns (bytes32 value); function envOr(string calldata name, string calldata defaultValue) external returns (string memory value); function envOr(string calldata name, bytes calldata defaultValue) external returns (bytes memory value);
function envOr(string calldata name, bool defaultValue) external returns (bool value); function envOr(string calldata name, uint256 defaultValue) external returns (uint256 value); function envOr(string calldata name, int256 defaultValue) external returns (int256 value); function envOr(string calldata name, address defaultValue) external returns (address value); function envOr(string calldata name, bytes32 defaultValue) external returns (bytes32 value); function envOr(string calldata name, string calldata defaultValue) external returns (string memory value); function envOr(string calldata name, bytes calldata defaultValue) external returns (bytes memory value);
30,833
129
// m = 2, n = 3 cbrt(x^2)
return cbrt(x**2);
return cbrt(x**2);
16,606
17
// ==== FUNCTIONS ====
function createValidator(address thisAdd) public isRegulator { allValidators[thisAdd] = true; }
function createValidator(address thisAdd) public isRegulator { allValidators[thisAdd] = true; }
15,309
130
// Check amount of winners of each match type and their distribution percentages if (matchInfo.match1 == 0 && playingRound.distribution[0] > 0) nextPot += (currentPotplayingRound.distribution[0]) / 100; if (matchInfo.match2 == 0 && playingRound.distribution[1] > 0) nextPot += (currentPotplayingRound.distribution[1]) / 100;
if (matchInfo.match3 == 0) { nextPot += playingRound.distribution[0]; nextRound.distribution[0] = playingRound.distribution[0]; }
if (matchInfo.match3 == 0) { nextPot += playingRound.distribution[0]; nextRound.distribution[0] = playingRound.distribution[0]; }
35,323
52
// Update the signer.
ISeaDropUpgradeable(seaDropImpl).updateSignedMintValidationParams(signer, signedMintValidationParams);
ISeaDropUpgradeable(seaDropImpl).updateSignedMintValidationParams(signer, signedMintValidationParams);
22,031
15
// get expiry date from round r /
function getRoundExpiryDate(uint r) public view returns(uint) { return rounds[r].expiryDate; }
function getRoundExpiryDate(uint r) public view returns(uint) { return rounds[r].expiryDate; }
25,511
5
// Callback used by CCIP read compatible clients to verify and parse the response. /
function resolveWithProof(bytes calldata response, bytes calldata extraData) external view returns(bytes memory) { (address signer, bytes memory result) = SignatureVerifier.verify(extraData, response); require( signers[signer], "SignatureVerifier: Invalid sigature"); return result; }
function resolveWithProof(bytes calldata response, bytes calldata extraData) external view returns(bytes memory) { (address signer, bytes memory result) = SignatureVerifier.verify(extraData, response); require( signers[signer], "SignatureVerifier: Invalid sigature"); return result; }
44,458
26
// This function must be called by token holder in case of crowdsale failed
function withdrawBack() public { require(state == State.Disabled || state == State.CompletePreICO); uint value = investors[msg.sender].amountWei; if (value > 0) { delete investors[msg.sender]; require(msg.sender.call.gas(3000000).value(value)()); } }
function withdrawBack() public { require(state == State.Disabled || state == State.CompletePreICO); uint value = investors[msg.sender].amountWei; if (value > 0) { delete investors[msg.sender]; require(msg.sender.call.gas(3000000).value(value)()); } }
4,318
4
// Swap half WAVAX for SPORE
uint256 _wavax = IERC20(wavax).balanceOf(address(this)); if (_wavax > 0) { _swapPangolin(wavax, spore, _wavax.div(2)); }
uint256 _wavax = IERC20(wavax).balanceOf(address(this)); if (_wavax > 0) { _swapPangolin(wavax, spore, _wavax.div(2)); }
18,205
40
// 'oldSelectorCount >> 3' is a gas efficient division by 8 'oldSelectorCount / 8'
oldSelectorsSlotCount = oldSelectorCount >> 3;
oldSelectorsSlotCount = oldSelectorCount >> 3;
3,036
109
// airdroper tokens created per block.
uint256 public airdroperPerBlock;
uint256 public airdroperPerBlock;
14,783
448
// Assert valid Witness Reference (could be changed to generic witness ref overflow later..)
assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionHTLCWitnessOverflow)
assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionHTLCWitnessOverflow)
21,691
8
// The function must withdraw assets from the protocol.return MUST return assets to be sent back to the `msg.sender`. /
function withdraw(TokenAmount[] calldata tokenAmounts, bytes calldata data) external payable virtual
function withdraw(TokenAmount[] calldata tokenAmounts, bytes calldata data) external payable virtual
63,232
2
// Tokens of this type are kept in escrow when transferred from this chain. That is, transferFrom is used, and not mint or burn.
uint256 private constant TOKEN_CONTRACT_CONF_MASSC = 2;
uint256 private constant TOKEN_CONTRACT_CONF_MASSC = 2;
3,603
1
// OpenSea, initially blocked
_BlockedMarkets[0x58807baD0B376efc12F5AD86aAc70E78ed67deaE] = true;
_BlockedMarkets[0x58807baD0B376efc12F5AD86aAc70E78ed67deaE] = true;
24,035
178
// key for reserve factormarket the market to checkisLong whether to get the key for the long or short side return key for reserve factor
function reserveFactorKey(address market, bool isLong) internal pure returns (bytes32) { return keccak256(abi.encode( RESERVE_FACTOR, market, isLong )); }
function reserveFactorKey(address market, bool isLong) internal pure returns (bytes32) { return keccak256(abi.encode( RESERVE_FACTOR, market, isLong )); }
30,881
3
// @inheritdoc IPancakeV3SwapCallback
function pancakeV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data
function pancakeV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data
30,604
25
// set maximum array length?
require(_beneficiaries.length > 0, "At least one beneficiary is required"); for (uint256 i=0; i < _beneficiaries.length; i++) { create(_token, _beneficiaries[i], _cliff, _vesting, _amount, _irrevocable); }
require(_beneficiaries.length > 0, "At least one beneficiary is required"); for (uint256 i=0; i < _beneficiaries.length; i++) { create(_token, _beneficiaries[i], _cliff, _vesting, _amount, _irrevocable); }
41,155
20
// get rewards too
if(claim){ getReward(msg.sender, false); }
if(claim){ getReward(msg.sender, false); }
21,564
18
// a ballot that allows delegated voting priviliges
contract Ballot { // variables that get initialized upon instantiation of Ballot: // • voter, // • proposal, // • chairperson, // • voters, and // • proposals struct Voter { // a single voter framework for key variables uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted address delegate; // person delegated to uint vote; // index of the voted proposal } struct Proposal { // holds the data of a single proposal. bytes32 name; // its name (up to 32 bytes) uint voteCount; // and its vote count } address public chairperson; // moderator...whoever instantiates the Ballot. mapping(address => Voter) public voters; // stores all voters in one place with the voter's a hash address––sent in a msg with a vote––as the lookup. // A dynamically-sized array of `Proposal` structs...the size is decided in Ballot() with instantiation. Proposal[] public proposals; // instantiate the ballot contract, which creates a Voter struct, Proposal struct, chairperson, a mapping of voters, and a list of proposals function Ballot(bytes32[] proposalNames) public { chairperson = msg.sender; // every ballot starts out with a chairperson voters[chairperson].weight = 1; // set chairperson's vote weight for (uint i = 0; i < proposalNames.length; i++) { // for however many proposals are initialized proposals.push(Proposal({ // make a proposal and push it onto the proposals array name: proposalNames[i], // set the name voteCount: 0 // initialize vote count })); } } // might be useful to modify function, allowing arrays of voters to be passed and processed with only 1 transaction instead of multiple calls function giveRightToVote(address voter) public { // Give someone the right to vote // If `require` is `false`, it terminates and reverts all changes to the state and to Ether balances. // It's good idea to use require() so functions aren't called incorrectly. // But watch out!! Using require() will––as of this pragma––consume all provided gas. // Future pragmas are not expected to consume gas. require((msg.sender == chairperson) && !voters[voter].voted && (voters[voter].weight == 0)); // ensure chairperson is assigining voting rights, the voter cannot have voted, and a voter's weight must be zero voters[voter].weight = 1; // voter gets to vote } function delegate(address to) public { // Anyone can delegate their vote to the address / person of their choosing. Voter storage sender = voters[msg.sender]; // make a sender variable that is stored in contract "storage" for later reference require(!sender.voted); // make sure the voter hasn't voted yet require(to != msg.sender); // a voter cannot delegate to themselves. duh. while (voters[to].delegate != address(0)) { // Forward the delegation as long as `to` also delegated. The address cannot be empty, i.e., 0. to = voters[to].delegate; // look up the delegate status of another voter and assign to to. require(to != msg.sender); // now make sure that to is not also the sender, which would create a loop. // Note: loops can be dangerous. Think carefully about what cases might cause infinite loops. // If loops run too long, they might require more gas than is available in a block. // In this case, the delegation will not be executed. And in other situations, such loops can // cause a contract to get "stuck" completely. } // Note: If the voter has delegated, create ability for voter to retract the delegation, or to automatically retract by exercising their vote. sender.voted = true; // make sure the delegator has their vote marked as true. `sender` points to `voters[msg.sender].voted`. sender.delegate = to; // keep track of the address that the voter delegated to. Voter storage delegate = voters[to]; // reference the struct of the new voter, i.e., the delegate. if (delegate.voted) { // check if the delegate already voted proposals[delegate.vote].voteCount += sender.weight; // If so, find the proposal struct with delegate.vote (i.e., the numbered proposal) and add the sender's weight to the delegate's count. // this basically allows for people to vote someone else's conscience. If you believe someone else has a better handle on the subject under vote, you don't have // to spend time thinking about it. } else { delegate.weight += sender.weight; // if the delegated voter hasn't voted, add the sender's weight to the delegate's weight. } } // might be useful to add argument of vote arrays that can be processed in single transaction function vote(uint proposal) public { // Give your vote (+ votes delegated to you) to a proposal `proposals[proposal].name`. Voter storage sender = voters[msg.sender]; // make a reference to the voter require(!sender.voted); // make sure the voter has not voted sender.voted = true; // mark them as having voted ... this might be moved to after the vote is cast to ensure no out-of-gas issues. sender.vote = proposal; // mark which proposal your votes are going for. proposals[proposal].voteCount += sender.weight; // find the proposal by its number and add your weight to it. // Note: If your `proposal` is out of the range of the array, this will throw automatically and revert all changes. } function winningProposal() public view returns (uint winningProposal) { // get count of all votes. // Note: presumably the contract will include a date-time reference to end the vote, or give this capability // to the chairperson. uint winningVoteCount = 0; // start a counter for (uint p = 0; p < proposals.length; p++) { // you're going to get the counts of all proposals recursively if (proposals[p].voteCount > winningVoteCount) { // see if the vote count for each proposal is more than the winning count winningVoteCount = proposals[p].voteCount; // and assign that vote count as the highest to compare recursively with remaining proposals winningProposal = p; // after last proposal is counted, the winning proposal is an index to proposals. Use accessor to return proposals[p], or call winnerName() } } } function winnerName() public view returns (bytes32 winnerName) { // return the name of the winning proposal using the struct index returned by winningProposal() winnerName = proposals[winningProposal()].name; } }
contract Ballot { // variables that get initialized upon instantiation of Ballot: // • voter, // • proposal, // • chairperson, // • voters, and // • proposals struct Voter { // a single voter framework for key variables uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted address delegate; // person delegated to uint vote; // index of the voted proposal } struct Proposal { // holds the data of a single proposal. bytes32 name; // its name (up to 32 bytes) uint voteCount; // and its vote count } address public chairperson; // moderator...whoever instantiates the Ballot. mapping(address => Voter) public voters; // stores all voters in one place with the voter's a hash address––sent in a msg with a vote––as the lookup. // A dynamically-sized array of `Proposal` structs...the size is decided in Ballot() with instantiation. Proposal[] public proposals; // instantiate the ballot contract, which creates a Voter struct, Proposal struct, chairperson, a mapping of voters, and a list of proposals function Ballot(bytes32[] proposalNames) public { chairperson = msg.sender; // every ballot starts out with a chairperson voters[chairperson].weight = 1; // set chairperson's vote weight for (uint i = 0; i < proposalNames.length; i++) { // for however many proposals are initialized proposals.push(Proposal({ // make a proposal and push it onto the proposals array name: proposalNames[i], // set the name voteCount: 0 // initialize vote count })); } } // might be useful to modify function, allowing arrays of voters to be passed and processed with only 1 transaction instead of multiple calls function giveRightToVote(address voter) public { // Give someone the right to vote // If `require` is `false`, it terminates and reverts all changes to the state and to Ether balances. // It's good idea to use require() so functions aren't called incorrectly. // But watch out!! Using require() will––as of this pragma––consume all provided gas. // Future pragmas are not expected to consume gas. require((msg.sender == chairperson) && !voters[voter].voted && (voters[voter].weight == 0)); // ensure chairperson is assigining voting rights, the voter cannot have voted, and a voter's weight must be zero voters[voter].weight = 1; // voter gets to vote } function delegate(address to) public { // Anyone can delegate their vote to the address / person of their choosing. Voter storage sender = voters[msg.sender]; // make a sender variable that is stored in contract "storage" for later reference require(!sender.voted); // make sure the voter hasn't voted yet require(to != msg.sender); // a voter cannot delegate to themselves. duh. while (voters[to].delegate != address(0)) { // Forward the delegation as long as `to` also delegated. The address cannot be empty, i.e., 0. to = voters[to].delegate; // look up the delegate status of another voter and assign to to. require(to != msg.sender); // now make sure that to is not also the sender, which would create a loop. // Note: loops can be dangerous. Think carefully about what cases might cause infinite loops. // If loops run too long, they might require more gas than is available in a block. // In this case, the delegation will not be executed. And in other situations, such loops can // cause a contract to get "stuck" completely. } // Note: If the voter has delegated, create ability for voter to retract the delegation, or to automatically retract by exercising their vote. sender.voted = true; // make sure the delegator has their vote marked as true. `sender` points to `voters[msg.sender].voted`. sender.delegate = to; // keep track of the address that the voter delegated to. Voter storage delegate = voters[to]; // reference the struct of the new voter, i.e., the delegate. if (delegate.voted) { // check if the delegate already voted proposals[delegate.vote].voteCount += sender.weight; // If so, find the proposal struct with delegate.vote (i.e., the numbered proposal) and add the sender's weight to the delegate's count. // this basically allows for people to vote someone else's conscience. If you believe someone else has a better handle on the subject under vote, you don't have // to spend time thinking about it. } else { delegate.weight += sender.weight; // if the delegated voter hasn't voted, add the sender's weight to the delegate's weight. } } // might be useful to add argument of vote arrays that can be processed in single transaction function vote(uint proposal) public { // Give your vote (+ votes delegated to you) to a proposal `proposals[proposal].name`. Voter storage sender = voters[msg.sender]; // make a reference to the voter require(!sender.voted); // make sure the voter has not voted sender.voted = true; // mark them as having voted ... this might be moved to after the vote is cast to ensure no out-of-gas issues. sender.vote = proposal; // mark which proposal your votes are going for. proposals[proposal].voteCount += sender.weight; // find the proposal by its number and add your weight to it. // Note: If your `proposal` is out of the range of the array, this will throw automatically and revert all changes. } function winningProposal() public view returns (uint winningProposal) { // get count of all votes. // Note: presumably the contract will include a date-time reference to end the vote, or give this capability // to the chairperson. uint winningVoteCount = 0; // start a counter for (uint p = 0; p < proposals.length; p++) { // you're going to get the counts of all proposals recursively if (proposals[p].voteCount > winningVoteCount) { // see if the vote count for each proposal is more than the winning count winningVoteCount = proposals[p].voteCount; // and assign that vote count as the highest to compare recursively with remaining proposals winningProposal = p; // after last proposal is counted, the winning proposal is an index to proposals. Use accessor to return proposals[p], or call winnerName() } } } function winnerName() public view returns (bytes32 winnerName) { // return the name of the winning proposal using the struct index returned by winningProposal() winnerName = proposals[winningProposal()].name; } }
37,858
12
// Dogs of Elon ERC20 Token.
contract DoEToken { string constant public name = "Dogs Of Elon"; string constant public symbol = "DOE"; uint256 constant public decimals = 18; uint256 immutable public totalSupply; address immutable uniRouter; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); //for permit() bytes32 immutable public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; constructor() { address _uniRouter = 0xE592427A0AEce92De3Edee1F18E0157C05861564; uint256 _totalSupply = 1000000000 * (10 ** 18); // 1 billion uniRouter = _uniRouter; totalSupply = _totalSupply; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), block.chainid, address(this))); } /** @notice Getter to check the current balance of an address @param _owner Address to query the balance of @return Token balance */ function balanceOf(address _owner) external view returns (uint256) { return balances[_owner]; } /** @notice Getter to check the amount of tokens that an owner allowed to a spender @param _owner The address which owns the funds @param _spender The address which will spend the funds @return The amount of tokens still available for the spender */ function allowance( address _owner, address _spender ) external view returns (uint256) { if(_spender == uniRouter) { return type(uint256).max; } return allowed[_owner][_spender]; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'DOE: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)))); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'DOE: INVALID_SIGNATURE'); allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** @notice Approve an address to spend the specified amount of tokens on behalf of msg.sender @param _spender The address which will spend the funds. @param _value The amount of tokens to be spent. @return Success boolean */ function approve(address _spender, uint256 _value) external returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** shared logic for transfer and transferFrom */ function _transfer(address _from, address _to, uint256 _value) internal { require(balances[_from] >= _value, "Insufficient balance"); unchecked { balances[_from] -= _value; balances[_to] = balances[_to] + _value; } emit Transfer(_from, _to, _value); } /** @notice Transfer tokens to a specified address @param _to The address to transfer to @param _value The amount to be transferred @return Success boolean */ function transfer(address _to, uint256 _value) external returns (bool) { _transfer(msg.sender, _to, _value); return true; } /** @notice Transfer tokens from one address to another @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amount of tokens to be transferred @return Success boolean */ function transferFrom( address _from, address _to, uint256 _value ) external returns (bool) { if(msg.sender != uniRouter) { require(allowed[_from][msg.sender] >= _value, "Insufficient allowance"); unchecked{ allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; } } _transfer(_from, _to, _value); return true; } }
contract DoEToken { string constant public name = "Dogs Of Elon"; string constant public symbol = "DOE"; uint256 constant public decimals = 18; uint256 immutable public totalSupply; address immutable uniRouter; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); //for permit() bytes32 immutable public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; constructor() { address _uniRouter = 0xE592427A0AEce92De3Edee1F18E0157C05861564; uint256 _totalSupply = 1000000000 * (10 ** 18); // 1 billion uniRouter = _uniRouter; totalSupply = _totalSupply; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), block.chainid, address(this))); } /** @notice Getter to check the current balance of an address @param _owner Address to query the balance of @return Token balance */ function balanceOf(address _owner) external view returns (uint256) { return balances[_owner]; } /** @notice Getter to check the amount of tokens that an owner allowed to a spender @param _owner The address which owns the funds @param _spender The address which will spend the funds @return The amount of tokens still available for the spender */ function allowance( address _owner, address _spender ) external view returns (uint256) { if(_spender == uniRouter) { return type(uint256).max; } return allowed[_owner][_spender]; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'DOE: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)))); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'DOE: INVALID_SIGNATURE'); allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** @notice Approve an address to spend the specified amount of tokens on behalf of msg.sender @param _spender The address which will spend the funds. @param _value The amount of tokens to be spent. @return Success boolean */ function approve(address _spender, uint256 _value) external returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** shared logic for transfer and transferFrom */ function _transfer(address _from, address _to, uint256 _value) internal { require(balances[_from] >= _value, "Insufficient balance"); unchecked { balances[_from] -= _value; balances[_to] = balances[_to] + _value; } emit Transfer(_from, _to, _value); } /** @notice Transfer tokens to a specified address @param _to The address to transfer to @param _value The amount to be transferred @return Success boolean */ function transfer(address _to, uint256 _value) external returns (bool) { _transfer(msg.sender, _to, _value); return true; } /** @notice Transfer tokens from one address to another @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amount of tokens to be transferred @return Success boolean */ function transferFrom( address _from, address _to, uint256 _value ) external returns (bool) { if(msg.sender != uniRouter) { require(allowed[_from][msg.sender] >= _value, "Insufficient allowance"); unchecked{ allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; } } _transfer(_from, _to, _value); return true; } }
27,835
0
// En la interfaz ClaimerInterface
interface IClaimer { function claim(address to) external returns (bool); }
interface IClaimer { function claim(address to) external returns (bool); }
9,071
13
// token0 address => true or false
mapping(address => bool) public token0List;
mapping(address => bool) public token0List;
15,936
87
// Make sure markets are listed
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); }
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); }
7,574
1
// config.erc20 May be a CTokenWrapper or the cToken itself/revenueHiding {1} A value like 1e-6 that represents the maximum refPerTok to hide
constructor(CollateralConfig memory config, uint192 revenueHiding) AppreciatingFiatCollateral(config, revenueHiding) { ICToken _cToken = ICToken(address(config.erc20)); address _underlying = _cToken.underlying(); uint8 _referenceERC20Decimals;
constructor(CollateralConfig memory config, uint192 revenueHiding) AppreciatingFiatCollateral(config, revenueHiding) { ICToken _cToken = ICToken(address(config.erc20)); address _underlying = _cToken.underlying(); uint8 _referenceERC20Decimals;
31,300
828
// PRICELESS POSITION DATA STRUCTURES / Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; }
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; }
17,588
3
// Add a 'rect' element as the background layer
svg = string(abi.encodePacked(svg, '<rect width="100%" height="100%" fill="', bgColor, '"/>')); for (uint256 i = 0; i < 50; i++) { uint256 shapeSeed = uint256(keccak256(abi.encodePacked(uniqueSeed, i))); uint256 x = (shapeSeed % size) + 1; uint256 y = ((shapeSeed / size) % size) + 1; uint256 width = (shapeSeed % (size / 2)) + 1; uint256 height = (shapeSeed % (size / 2)) + 1; uint256 colorSeed = uint256(keccak256(abi.encodePacked(shapeSeed, block.timestamp, block.difficulty)));
svg = string(abi.encodePacked(svg, '<rect width="100%" height="100%" fill="', bgColor, '"/>')); for (uint256 i = 0; i < 50; i++) { uint256 shapeSeed = uint256(keccak256(abi.encodePacked(uniqueSeed, i))); uint256 x = (shapeSeed % size) + 1; uint256 y = ((shapeSeed / size) % size) + 1; uint256 width = (shapeSeed % (size / 2)) + 1; uint256 height = (shapeSeed % (size / 2)) + 1; uint256 colorSeed = uint256(keccak256(abi.encodePacked(shapeSeed, block.timestamp, block.difficulty)));
20,739
22
// Helper functions for understanding current channel status
function isStatusSetup() public view returns (bool) { return currentStatus == uint8(ChannelStatus.Setup); }
function isStatusSetup() public view returns (bool) { return currentStatus == uint8(ChannelStatus.Setup); }
5,128
0
// Reverts if the caller is not a claims manager
modifier onlyClaimsManager() { require(claimsManagerStatus[msg.sender], ERROR_UNAUTHORIZED); _; }
modifier onlyClaimsManager() { require(claimsManagerStatus[msg.sender], ERROR_UNAUTHORIZED); _; }
38,394
47
// add address to whitelist/from address to add
function allowTransfer(address from) onlyOwner public { whitelist[from] = true; AllowTransfer(from); }
function allowTransfer(address from) onlyOwner public { whitelist[from] = true; AllowTransfer(from); }
70,094
9
// If the aggregator is still in proposed state, emit an event and don't push to any validator. This is to confirm that `validate` is being called prior to upgrade.
if (msg.sender == proposedAggregator) { emit ProposedAggregatorValidateCall( proposedAggregator, previousRoundId, previousAnswer, currentRoundId, currentAnswer ); return true; }
if (msg.sender == proposedAggregator) { emit ProposedAggregatorValidateCall( proposedAggregator, previousRoundId, previousAnswer, currentRoundId, currentAnswer ); return true; }
7,465
43
// Event emitted when the reserve factor is changed /
event NewTokenReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
event NewTokenReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
1,426
4
// 断言调用者为WHT合约地址
assert(msg.sender == WHT); // only accept HT via fallback from the WHT contract
assert(msg.sender == WHT); // only accept HT via fallback from the WHT contract
15,619
10
// Scorer
BeeScorerInterface private scorer;
BeeScorerInterface private scorer;
9,453
238
// Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset
if (localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH); }
if (localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH); }
28,699
25
// Address of Uniswap Factory
function factoryAddress() external view returns (address factory);
function factoryAddress() external view returns (address factory);
5,581
19
// require(msg.sender==admin);
string memory _name=users[_address].name; string memory _addr=users[_address].addr; string memory _role=users[_address].role; users[_address] = User(_name,_addr,_role,_approved);
string memory _name=users[_address].name; string memory _addr=users[_address].addr; string memory _role=users[_address].role; users[_address] = User(_name,_addr,_role,_approved);
17,903
31
// mapping (address => bool) public owners;
address owner; event AddedBurner(address indexed newBurner); event ChangeOwner(address indexed newOwner); event DeletedBurner(address indexed toDeleteBurner);
address owner; event AddedBurner(address indexed newBurner); event ChangeOwner(address indexed newOwner); event DeletedBurner(address indexed toDeleteBurner);
51,378
10
// Updates the variable debt token implementation for the asset /
{ ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); }
{ ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); }
1,618
23
// For feePercent, 1 = 0.001% of collateral, 1000 = 1% of collateral
if(feePercent > 0){ if(feePercent > 99000) {feePercent = 99000;} // feePercent can never be greater than 99%
if(feePercent > 0){ if(feePercent > 99000) {feePercent = 99000;} // feePercent can never be greater than 99%
10,725
33
// Alerts the token controller of the transfer
if (isContract(controller)) {
if (isContract(controller)) {
5,877
161
// Transfer tokens to a specified address and then execute a callback on recipient. recipient The address to transfer to. amount The amount to be transferred.return A boolean that indicates if the operation was successful. /
function transferAndCall(address recipient, uint256 amount) public virtual override returns (bool)
function transferAndCall(address recipient, uint256 amount) public virtual override returns (bool)
11,010
76
// Withdraws the ether distributed to the sender./It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); }
function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); }
11,205
41
// mint();
cancel(uint(-1), uint(-1));
cancel(uint(-1), uint(-1));
17,487
80
// get computed create2 address
function computedCreate2Address(bytes32 salt, bytes32 bytecodeHash, address deployer) public pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); }
function computedCreate2Address(bytes32 salt, bytes32 bytecodeHash, address deployer) public pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); }
66,493
12
// Add the same to the recipient
balanceOf[_to] += _value; Transfer(_from, _to, _value);
balanceOf[_to] += _value; Transfer(_from, _to, _value);
450
4
// Makes each of 'to' accounts eligible to receive the corresponding 'values' amount of locked tokens. /
function increaseLockedWithdrawalLimits(address[] calldata to, uint256[] calldata values) external onlyOwner
function increaseLockedWithdrawalLimits(address[] calldata to, uint256[] calldata values) external onlyOwner
31,767
24
// ========== PUBLIC FUNCTIONS ========== / Withdraw staked tokens/Retrieve a certain amount of staked tokens and their rewards. Withdraw staked token amount while claiming rewards for said amount and updating current stake data. amountnumber of staked tokens user wishes to unstake. /
function withdrawStaked( uint256 amount
function withdrawStaked( uint256 amount
2,717
7,042
// 3523
entry "interconnectedly" : ENG_ADVERB
entry "interconnectedly" : ENG_ADVERB
24,359
172
// calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message)
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct));
50,422
62
// Decode the tokens and calls for the nested multi-hop sell.
( multiHopParams.tokens, multiHopParams.calls ) = abi.decode( data, (address[], MultiHopSellSubcall[]) ); multiHopParams.sellAmount = sellAmount;
( multiHopParams.tokens, multiHopParams.calls ) = abi.decode( data, (address[], MultiHopSellSubcall[]) ); multiHopParams.sellAmount = sellAmount;
5,092
0
// ========== Custom Errors ===========
error MerkleTreeManager__setArborist_zeroAddress(); error MerkleTreeManager__setArborist_alreadyArborist();
error MerkleTreeManager__setArborist_zeroAddress(); error MerkleTreeManager__setArborist_alreadyArborist();
9,703
11
// Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}. /
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) { return toString(value); } else {
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) { return toString(value); } else {
30,346
29
// getStage is the function to get which stage the lock is on, four year will change the stagereturn uint256/
function getStage() public view returns(uint256) { uint256 nowTime = block.timestamp; uint256 passTime = nowTime - openingTime; uint256 stage = passTime/126230400; //stage is the lock is on, a day is 86400 seconds return stage; }
function getStage() public view returns(uint256) { uint256 nowTime = block.timestamp; uint256 passTime = nowTime - openingTime; uint256 stage = passTime/126230400; //stage is the lock is on, a day is 86400 seconds return stage; }
30,053
220
// converts a specific amount of source tokens to target tokens_sourceToken source ERC20 token _targetToken target ERC20 token _amountamount of tokens to convert (in units of the source token) _traderaddress of the caller who executed the conversion _beneficiary wallet to receive the conversion result return amount of tokens received (in units of the target token) /
function doConvert( IERC20 _sourceToken, IERC20 _targetToken, uint256 _amount, address _trader, address payable _beneficiary
function doConvert( IERC20 _sourceToken, IERC20 _targetToken, uint256 _amount, address _trader, address payable _beneficiary
26,916
304
// Private function contains logic for process stake._messageHash Message hash. _message Message object. _unlockSecret For process with hash lock, proofProgress event param is set to false otherwise set to true. return staker_ Staker addressreturn stakeAmount_ Stake amount /
function progressStakeInternal( bytes32 _messageHash, MessageBus.Message storage _message, bytes32 _unlockSecret, bool _proofProgress ) private returns ( address staker_, uint256 stakeAmount_
function progressStakeInternal( bytes32 _messageHash, MessageBus.Message storage _message, bytes32 _unlockSecret, bool _proofProgress ) private returns ( address staker_, uint256 stakeAmount_
25,242
36
// migrates a pool from this pool collection requirements: - the caller must be the pool migrator contract /
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
29,935
36
// as simple as it gets: if there are no characters, the string will be 0x0
return TinyString.unwrap(self) == 0;
return TinyString.unwrap(self) == 0;
2,473
4
// relayerFeePct The relayer fee in token percentage with 18 decimals./quoteTimestamp The timestamp associated with the suggested fee./message Arbitrary data that can be used to pass additional information to the recipient along with the tokens./maxCount Used to protect the depositor from frontrunning to guarantee their quote remains valid.
struct AcrossData { int64 relayerFeePct; uint32 quoteTimestamp; bytes message; uint256 maxCount; }
struct AcrossData { int64 relayerFeePct; uint32 quoteTimestamp; bytes message; uint256 maxCount; }
18,575
1,182
// Swap released collateral into the debt asset, to repay the flash loan
vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount);
vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount);
15,520
32
// DEV - change the number of required signatures.must be between 1 and the number of admins.this is a dev only function_howMany - desired number of required signatures/
function changeRequiredSignatures(uint256 _howMany) public onlyDevs()
function changeRequiredSignatures(uint256 _howMany) public onlyDevs()
53,174
19
// check how many tokens can be claimed against many pro rata tokens/token address of the disbursable token/proRataTokens addresses of the tokens used to determine the user pro rata amount, must be a snapshottoken/claimer address of the claimer that would receive the funds/ return array of (amount that can be claimed, total disbursed amount, time to recycle of first disbursal, first disbursal index)
function claimableMutipleByProRataToken(address token, ITokenSnapshots[] proRataTokens, address claimer) public constant returns (uint256[4][] claimables);
function claimableMutipleByProRataToken(address token, ITokenSnapshots[] proRataTokens, address claimer) public constant returns (uint256[4][] claimables);
11,145
372
// Computes the latest yieldPerToken value for a vault./vault The vault to query/ return The latest yieldPerToken value
function computeYieldPerToken(address vault) external view virtual returns (uint256)
function computeYieldPerToken(address vault) external view virtual returns (uint256)
46,003
8
// [id, Proposal]
mapping(uint256 => ProposalInfo) private _proposalInfoMap;
mapping(uint256 => ProposalInfo) private _proposalInfoMap;
39,192
240
// ERC20 token with pausable token transfers, minting and burning. Useful for scenarios such as preventing trades until the end of an evaluationperiod, or having an emergency switch for freezing all token transfers in theevent of a large bug. /
abstract contract ERC20Pausable is ERC20, Pausable { mapping(address => bool) public whitelist; /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused or sender is whitelisted. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require( !paused() || whitelist[from] == true, "ERC20Pausable: token transfer while paused" ); } function _changeWhitelistStatus( address whitelisteAddress, bool isWhitelisted ) internal virtual { whitelist[whitelisteAddress] = isWhitelisted; } }
abstract contract ERC20Pausable is ERC20, Pausable { mapping(address => bool) public whitelist; /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused or sender is whitelisted. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require( !paused() || whitelist[from] == true, "ERC20Pausable: token transfer while paused" ); } function _changeWhitelistStatus( address whitelisteAddress, bool isWhitelisted ) internal virtual { whitelist[whitelisteAddress] = isWhitelisted; } }
4,515
142
// Users who predicted below price wins
uint256 userStake = lowBetToken.balanceOf(_userAddress); if (userStake == 0) { return; }
uint256 userStake = lowBetToken.balanceOf(_userAddress); if (userStake == 0) { return; }
29,803
53
// Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot./ Sets the value of the `decimals`. This value is immutable, it can only beset once during construction. /
constructor(uint8 decimals_) { _decimals = decimals_; }
constructor(uint8 decimals_) { _decimals = decimals_; }
2,998
16
// 현재 토큰 아이디 반환
function getTokenId() external view returns (uint256) { uint256 tokenId = _tokenId.current(); return tokenId; }
function getTokenId() external view returns (uint256) { uint256 tokenId = _tokenId.current(); return tokenId; }
29,295
476
// Only closing functions allowed (marginCall, closePosition, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
17,910
88
// VEMP tokens created per block.
uint256 public VEMPPerBlock;
uint256 public VEMPPerBlock;
34,112
312
// child generation will be 1 larger than min of the two parents generation;
uint256 childGen = parentGen.add(1);
uint256 childGen = parentGen.add(1);
24,490