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
41
// Airdrop tokens Remove `_value` tokens from the system irreversibly_value the amount with decimals(18)/
mapping (address => uint256) public airDropHistory; event AirDrop(address _receiver, uint256 _amount);
mapping (address => uint256) public airDropHistory; event AirDrop(address _receiver, uint256 _amount);
25,661
11
// Modifier is Owner address
modifier isOwner { assert(owner == msg.sender); _; }
modifier isOwner { assert(owner == msg.sender); _; }
47,366
6
// information that have to be added from the cryptonomica server: string signedStringFromServer;
string firstName; string lastName; string keyFingerprint; uint keyValidUntil; // unix time uint birthDateYear; uint birthDateMonth; uint birthDateDay;
string firstName; string lastName; string keyFingerprint; uint keyValidUntil; // unix time uint birthDateYear; uint birthDateMonth; uint birthDateDay;
3,870
45
// Private function to mint without any access checks.Called by the public edition minting functions. /
function _mintEditions(address[] memory recipients) internal returns (uint256) { require(uint64(mintable()) >= recipients.length, "Sold out"); for (uint i = 0; i < recipients.length; i++) { _mint(recipients[i], counter.current()); counter.increment(); } return counter.current(); }
function _mintEditions(address[] memory recipients) internal returns (uint256) { require(uint64(mintable()) >= recipients.length, "Sold out"); for (uint i = 0; i < recipients.length; i++) { _mint(recipients[i], counter.current()); counter.increment(); } return counter.current(); }
40,942
57
// Function to pause recieving of deposits.Available only to the owner. /
function pause() external onlyOwner { require(!paused); paused = true; }
function pause() external onlyOwner { require(!paused); paused = true; }
19,687
5
// The array to store the guesses submitted by each piece
Guess[MAX_NFT_SUPPLY] private guesses; bytes32 private secretMintCodeHash = 0x0aadf7eaabe5d56139de8e76813c132769e31f1738b8633e8376ae55330c9de3; event StakingFeeChanged(uint256 _stakeAmount);
Guess[MAX_NFT_SUPPLY] private guesses; bytes32 private secretMintCodeHash = 0x0aadf7eaabe5d56139de8e76813c132769e31f1738b8633e8376ae55330c9de3; event StakingFeeChanged(uint256 _stakeAmount);
82,761
56
// Returns an identifier for the bridge contract so that the latter could/ ensure it works with the BlockReward contract.
function blockRewardContractId() public pure returns(bytes4) { return 0x0d35a7ca; // bytes4(keccak256("blockReward")) }
function blockRewardContractId() public pure returns(bytes4) { return 0x0d35a7ca; // bytes4(keccak256("blockReward")) }
13,238
0
// Set BaseURL for the degens.
setBaseURI(_baseNFTURI);
setBaseURI(_baseNFTURI);
36,191
62
// Returns the id of the Aave market to which this contracts points toreturn The market id /
function getMarketId() external view override returns (string memory) { return _marketId; }
function getMarketId() external view override returns (string memory) { return _marketId; }
39,774
303
// Unlock as much collateral as possible while keeping the target ratio
amountToFree = Math.min(amountToFree, _maxWithdrawal()); _freeCollateralAndRepayDai(amountToFree, 0);
amountToFree = Math.min(amountToFree, _maxWithdrawal()); _freeCollateralAndRepayDai(amountToFree, 0);
76,984
77
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true;
require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true;
25,988
171
// Marble NFT Interface Defines Marbles unique extension of NFT....It contains methodes returning core properties what describe Marble NFTs and provides management options to create,burn NFT or change approvals of it. /
interface MarbleNFTInterface { /** * @dev Mints Marble NFT. * @notice This is a external function which should be called just by the owner of contract or any other user who has priviladge of being resposible * of creating valid Marble NFT. Valid token contains all neccessary information to be able recreate marble card image. * @param _tokenId The ID of new NFT. * @param _owner Address of the NFT owner. * @param _uri Unique URI proccessed by Marble services to be sure it is valid NFTs DNA. Most likely it is URL pointing to some website address. * @param _metadataUri URI pointing to "ERC721 Metadata JSON Schema" * @param _tokenId ID of the NFT to be burned. */ function mint( uint256 _tokenId, address _owner, address _creator, string _uri, string _metadataUri, uint256 _created ) external; /** * @dev Burns Marble NFT. Should be fired only by address with proper authority as contract owner or etc. * @param _tokenId ID of the NFT to be burned. */ function burn( uint256 _tokenId ) external; /** * @dev Allowes to change approval for change of ownership even when sender is not NFT holder. Sender has to have special role granted by contract to use this tool. * @notice Careful with this!!!! :)) * @param _tokenId ID of the NFT to be updated. * @param _approved ETH address what supposed to gain approval to take ownership of NFT. */ function forceApproval( uint256 _tokenId, address _approved ) external; /** * @dev Returns properties used for generating NFT metadata image (a.k.a. card). * @param _tokenId ID of the NFT. */ function tokenSource(uint256 _tokenId) external view returns ( string uri, address creator, uint256 created ); /** * @dev Returns ID of NFT what matches provided source URI. * @param _uri URI of source website. */ function tokenBySourceUri(string _uri) external view returns (uint256 tokenId); /** * @dev Returns all properties of Marble NFT. Lets call it Marble NFT Model with properties described below: * @param _tokenId ID of NFT * Returned model: * uint256 id ID of NFT * string uri URI of source website. Website is used to mine data to crate NFT metadata image. * string metadataUri URI to NFT metadata assets. In our case to our websevice providing JSON with additional information based on "ERC721 Metadata JSON Schema". * address owner NFT owner address. * address creator Address of creator of this NFT. It means that this addres placed sourceURI to candidate contract. * uint256 created Date and time of creation of NFT candidate. * * (id, uri, metadataUri, owner, creator, created) */ function getNFT(uint256 _tokenId) external view returns( uint256 id, string uri, string metadataUri, address owner, address creator, uint256 created ); /** * @dev Transforms URI to hash. * @param _uri URI to be transformed to hash. */ function getSourceUriHash(string _uri) external view returns(uint256 hash); }
interface MarbleNFTInterface { /** * @dev Mints Marble NFT. * @notice This is a external function which should be called just by the owner of contract or any other user who has priviladge of being resposible * of creating valid Marble NFT. Valid token contains all neccessary information to be able recreate marble card image. * @param _tokenId The ID of new NFT. * @param _owner Address of the NFT owner. * @param _uri Unique URI proccessed by Marble services to be sure it is valid NFTs DNA. Most likely it is URL pointing to some website address. * @param _metadataUri URI pointing to "ERC721 Metadata JSON Schema" * @param _tokenId ID of the NFT to be burned. */ function mint( uint256 _tokenId, address _owner, address _creator, string _uri, string _metadataUri, uint256 _created ) external; /** * @dev Burns Marble NFT. Should be fired only by address with proper authority as contract owner or etc. * @param _tokenId ID of the NFT to be burned. */ function burn( uint256 _tokenId ) external; /** * @dev Allowes to change approval for change of ownership even when sender is not NFT holder. Sender has to have special role granted by contract to use this tool. * @notice Careful with this!!!! :)) * @param _tokenId ID of the NFT to be updated. * @param _approved ETH address what supposed to gain approval to take ownership of NFT. */ function forceApproval( uint256 _tokenId, address _approved ) external; /** * @dev Returns properties used for generating NFT metadata image (a.k.a. card). * @param _tokenId ID of the NFT. */ function tokenSource(uint256 _tokenId) external view returns ( string uri, address creator, uint256 created ); /** * @dev Returns ID of NFT what matches provided source URI. * @param _uri URI of source website. */ function tokenBySourceUri(string _uri) external view returns (uint256 tokenId); /** * @dev Returns all properties of Marble NFT. Lets call it Marble NFT Model with properties described below: * @param _tokenId ID of NFT * Returned model: * uint256 id ID of NFT * string uri URI of source website. Website is used to mine data to crate NFT metadata image. * string metadataUri URI to NFT metadata assets. In our case to our websevice providing JSON with additional information based on "ERC721 Metadata JSON Schema". * address owner NFT owner address. * address creator Address of creator of this NFT. It means that this addres placed sourceURI to candidate contract. * uint256 created Date and time of creation of NFT candidate. * * (id, uri, metadataUri, owner, creator, created) */ function getNFT(uint256 _tokenId) external view returns( uint256 id, string uri, string metadataUri, address owner, address creator, uint256 created ); /** * @dev Transforms URI to hash. * @param _uri URI to be transformed to hash. */ function getSourceUriHash(string _uri) external view returns(uint256 hash); }
12,941
32
// the proposal quorum is the lowest of minProposalPower and the proposal quorum because it is awkward for the proposal to require more voting power than the execution
uint256 minPower = quorum <= minProposalPower ? quorum : minProposalPower;
uint256 minPower = quorum <= minProposalPower ? quorum : minProposalPower;
1,320
1
// queried by others ({ERC165Checker}).For an implementation, see {ERC165}./ Returns true if this contract implements the interface defined by`interfaceId`. See the correspondingto learn more about how these ids are created. This function call must use less than 30 000 gas. /
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
945
26
// all okay!
UserStatus("User has withdrawn funds", msg.sender, amount);
UserStatus("User has withdrawn funds", msg.sender, amount);
39,893
136
// Add a new token to registry _token ERC20 Token address _decimals Token's decimals _isTransferFeeEnabled Is token changes transfer fee _isSupportedOnCompound Is token supported on Compound _cToken cToken contract address _chainLinkOracle Chain Link Aggregator address to get TOKEN/ETH rate /
function addToken( address _token, uint8 _decimals, bool _isTransferFeeEnabled, bool _isSupportedOnCompound, address _cToken, address _chainLinkOracle ) public onlyOwner
function addToken( address _token, uint8 _decimals, bool _isTransferFeeEnabled, bool _isSupportedOnCompound, address _cToken, address _chainLinkOracle ) public onlyOwner
32,968
36
// uniswap tokenB pair address --> USDC
address pairB = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address pairB = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
31,803
7
// Sets reveal state/_state New reveal state
function setRevealed(bool _state) public onlyOwner { revealed = _state; emit RevealStateChanged(_state); }
function setRevealed(bool _state) public onlyOwner { revealed = _state; emit RevealStateChanged(_state); }
27,070
11
// iterate through oracle list and check if enough oracles(minimum quorum)have voted the same answer has the current one
for(uint i = 0; i < totalOracleCount; i++){ bytes memory a = bytes(currRequest.anwers[i]); bytes memory b = bytes(_valueRetrieved); if(keccak256(a) == keccak256(b)){ currentQuorum++; if(currentQuorum >= minQuorum){ currRequest.agreedValue = _valueRetrieved; emit UpdatedRequest ( currRequest.id,
for(uint i = 0; i < totalOracleCount; i++){ bytes memory a = bytes(currRequest.anwers[i]); bytes memory b = bytes(_valueRetrieved); if(keccak256(a) == keccak256(b)){ currentQuorum++; if(currentQuorum >= minQuorum){ currRequest.agreedValue = _valueRetrieved; emit UpdatedRequest ( currRequest.id,
39,454
6
// fee are either zero, or being paid in the collateral token
feeAmount = MathLib.multiply( qtyToMint, marketContract.COLLATERAL_TOKEN_FEE_PER_UNIT() ); totalCollateralTokenTransferAmount = neededCollateral.add(feeAmount); feeToken = collateralTokenAddress;
feeAmount = MathLib.multiply( qtyToMint, marketContract.COLLATERAL_TOKEN_FEE_PER_UNIT() ); totalCollateralTokenTransferAmount = neededCollateral.add(feeAmount); feeToken = collateralTokenAddress;
10,156
57
// Views
function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256);
8,896
3
// Tell if a Witnet.Result is errored./_result An instance of Witnet.Result./ return `true` if errored, `false` if successful.
function isError(Witnet.Result memory _result) external pure returns (bool);
function isError(Witnet.Result memory _result) external pure returns (bool);
14,041
184
// returns the delta between the current stable rate and the user stable rate atwhich the borrow position of the user will be rebalanced (scaled down)/
function getRebalanceDownRateDelta() external pure returns (uint256) { return REBALANCE_DOWN_RATE_DELTA; }
function getRebalanceDownRateDelta() external pure returns (uint256) { return REBALANCE_DOWN_RATE_DELTA; }
34,828
21
// start = startTime;end = endTime;
prices = etherCostOfEachToken * 0.0000001 ether;
prices = etherCostOfEachToken * 0.0000001 ether;
33,437
9
// If a decimal, we need to left-pad if the numTens isn't enough
if (decimal) { while (numTens < 3) { bstr[k--] = bytes1("0"); numTens++; }
if (decimal) { while (numTens < 3) { bstr[k--] = bytes1("0"); numTens++; }
38,795
225
// discount vesting amounts for vesting time
uint256 multiplier = vestedBalanceForAmount( 1e36, 0, block.timestamp ); bzrxRewardsVesting = bzrxRewardsVesting .sub(bzrxRewardsVesting .mul(multiplier) .div(1e36) );
uint256 multiplier = vestedBalanceForAmount( 1e36, 0, block.timestamp ); bzrxRewardsVesting = bzrxRewardsVesting .sub(bzrxRewardsVesting .mul(multiplier) .div(1e36) );
40,217
96
// it must implement {IPollenCallee}/
function execute(uint256 proposalId, bytes calldata data) external;
function execute(uint256 proposalId, bytes calldata data) external;
47,822
45
// claim before invalidating if there is something to claim
claimHodlRewardFor(_account);
claimHodlRewardFor(_account);
17,751
17
// get past rounds answers _roundId the answer number to retrieve the answer for[deprecated] Use getRoundData instead. This does not error if noanswer has been reached, it will simply return 0. Either wait to point toan already answered Aggregator or use the recommended getRoundDatainstead which includes better verification information. /
function getAnswer(uint256 _roundId) external view virtual override returns (int256)
function getAnswer(uint256 _roundId) external view virtual override returns (int256)
26,744
2
// Helper functions
function getEthBalance(address addr) public view returns (uint256 balance) { balance = addr.balance; }
function getEthBalance(address addr) public view returns (uint256 balance) { balance = addr.balance; }
27,650
83
// change address of Olympus Treasury_olympusTreasury uint /
function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; }
function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; }
35,522
10
// Only the director is permitted
require(msg.sender == director); _;
require(msg.sender == director); _;
16,664
2
// - Token 小数位
uint8 public decimals;
uint8 public decimals;
38,806
13
// allows owner to change tournament parameters (for next tournament)
function update(uint _players, uint _rounds, uint _time, uint _fee) public authority { nPlayers = _players; nRounds = _rounds; nTime = _time; nFee = _fee; }
function update(uint _players, uint _rounds, uint _time, uint _fee) public authority { nPlayers = _players; nRounds = _rounds; nTime = _time; nFee = _fee; }
50,983
52
// Library computes the startBlock, computes startWeights as the current denormalized weights of the core pool tokens.
SmartPoolManager.updateWeightsGradually( bPool, gradualUpdate, newWeights, startBlock, endBlock, minimumWeightChangeBlockPeriod );
SmartPoolManager.updateWeightsGradually( bPool, gradualUpdate, newWeights, startBlock, endBlock, minimumWeightChangeBlockPeriod );
21,687
56
//
if(shouldSwapBack()){ swapBack(); }
if(shouldSwapBack()){ swapBack(); }
2,570
0
// config
bool public EnableSystem; uint256 public DelayBlockOutGame; mapping(uint256 => uint256) public PriceUpgrate; mapping(uint256 => uint256) public BlockUpgrate; uint256 public MaxLevel; uint256 public DelayBlockLearn; uint256 public TotalBlockLearn; mapping(uint256 => uint256) public RewardPerBlockOfLevel;
bool public EnableSystem; uint256 public DelayBlockOutGame; mapping(uint256 => uint256) public PriceUpgrate; mapping(uint256 => uint256) public BlockUpgrate; uint256 public MaxLevel; uint256 public DelayBlockLearn; uint256 public TotalBlockLearn; mapping(uint256 => uint256) public RewardPerBlockOfLevel;
21,033
6
// Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` cash The amount of cash in the market borrows The amount of borrows in the market reserves The amount of reserves in the market (currently unused)return The utilization rate as a mantissa between [0, 1e18] /
function utilizationRate( uint256 cash, uint256 borrows, uint256 reserves
function utilizationRate( uint256 cash, uint256 borrows, uint256 reserves
32,484
64
// ERC721, ERC1155 imports // WalletSimple============ Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction. The first signature is created on the operation hash (see Data Formats) and passed to sendMultiSig/sendMultiSigTokenThe signer is determined by verifyMultiSig(). The second signature is created by the submitter of the transaction and determined by msg.signer. Data Formats============ The signature is created with ethereumjs-util.ecsign(operationHash).Like the eth_sign RPC call, it packs the values as a 65-byte array of [r, s, v].Unlike
contract WalletSimple is IERC721Receiver, ERC1155Receiver { // Events event Deposited(address from, uint256 value, bytes data); event SafeModeActivated(address msgSender); event Transacted( address msgSender, // Address of the sender of the message initiating the transaction address otherSigner, // Address of the signer (second signature) used to initiate the transaction bytes32 operation, // Operation hash (see Data Formats) address toAddress, // The address the transaction was sent to uint256 value, // Amount of Wei sent to the address bytes data // Data sent when invoking the transaction ); event BatchTransfer(address sender, address recipient, uint256 value); // this event shows the other signer and the operation hash that they signed // specific batch transfer events are emitted in Batcher event BatchTransacted( address msgSender, // Address of the sender of the message initiating the transaction address otherSigner, // Address of the signer (second signature) used to initiate the transaction bytes32 operation // Operation hash (see Data Formats) ); // Public fields mapping(address => bool) public signers; // The addresses that can co-sign transactions on the wallet bool public safeMode = false; // When active, wallet may only send to signer addresses bool public initialized = false; // True if the contract has been initialized // Internal fields uint256 private constant MAX_SEQUENCE_ID_INCREASE = 10000; uint256 constant SEQUENCE_ID_WINDOW_SIZE = 10; uint256[SEQUENCE_ID_WINDOW_SIZE] recentSequenceIds; /** * Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet. * 2 signers will be required to send a transaction from this wallet. * Note: The sender is NOT automatically added to the list of signers. * Signers CANNOT be changed once they are set * * @param allowedSigners An array of signers on the wallet */ function init(address[] calldata allowedSigners) external onlyUninitialized { require(allowedSigners.length == 3, 'Invalid number of signers'); for (uint8 i = 0; i < allowedSigners.length; i++) { require(allowedSigners[i] != address(0), 'Invalid signer'); signers[allowedSigners[i]] = true; } initialized = true; } /** * Get the network identifier that signers must sign over * This provides protection signatures being replayed on other chains * This must be a virtual function because chain-specific contracts will need * to override with their own network ids. It also can't be a field * to allow this contract to be used by proxy with delegatecall, which will * not pick up on state variables */ function getNetworkId() internal virtual pure returns (string memory) { return 'ETHER'; } /** * Get the network identifier that signers must sign over for token transfers * This provides protection signatures being replayed on other chains * This must be a virtual function because chain-specific contracts will need * to override with their own network ids. It also can't be a field * to allow this contract to be used by proxy with delegatecall, which will * not pick up on state variables */ function getTokenNetworkId() internal virtual pure returns (string memory) { return 'ERC20'; } /** * Get the network identifier that signers must sign over for batch transfers * This provides protection signatures being replayed on other chains * This must be a virtual function because chain-specific contracts will need * to override with their own network ids. It also can't be a field * to allow this contract to be used by proxy with delegatecall, which will * not pick up on state variables */ function getBatchNetworkId() internal virtual pure returns (string memory) { return 'ETHER-Batch'; } /** * Determine if an address is a signer on this wallet * @param signer address to check * returns boolean indicating whether address is signer or not */ function isSigner(address signer) public view returns (bool) { return signers[signer]; } /** * Modifier that will execute internal code block only if the sender is an authorized signer on this wallet */ modifier onlySigner { require(isSigner(msg.sender), 'Non-signer in onlySigner method'); _; } /** * Modifier that will execute internal code block only if the contract has not been initialized yet */ modifier onlyUninitialized { require(!initialized, 'Contract already initialized'); _; } /** * Gets called when a transaction is received with data that does not match any other method */ fallback() external payable { if (msg.value > 0) { // Fire deposited event if we are receiving funds emit Deposited(msg.sender, msg.value, msg.data); } } /** * Gets called when a transaction is received with ether and no data */ receive() external payable { if (msg.value > 0) { // Fire deposited event if we are receiving funds // message data is always empty for receive. If there is data it is sent to fallback function. emit Deposited(msg.sender, msg.value, ''); } } /** * Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover. * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated. * * @param toAddress the destination address to send an outgoing transaction * @param value the amount in Wei to be sent * @param data the data to send to the toAddress when invoking the transaction * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * @param signature see Data Formats */ function sendMultiSig( address toAddress, uint256 value, bytes calldata data, uint256 expireTime, uint256 sequenceId, bytes calldata signature ) external onlySigner { // Verify the other signer bytes32 operationHash = keccak256( abi.encodePacked( getNetworkId(), toAddress, value, data, expireTime, sequenceId ) ); address otherSigner = verifyMultiSig( toAddress, operationHash, signature, expireTime, sequenceId ); // Success, send the transaction (bool success, ) = toAddress.call{ value: value }(data); require(success, 'Call execution failed'); emit Transacted( msg.sender, otherSigner, operationHash, toAddress, value, data ); } /** * Execute a batched multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover. * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated. * The recipients and values to send are encoded in two arrays, where for index i, recipients[i] will be sent values[i]. * * @param recipients The list of recipients to send to * @param values The list of values to send to * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * @param signature see Data Formats */ function sendMultiSigBatch( address[] calldata recipients, uint256[] calldata values, uint256 expireTime, uint256 sequenceId, bytes calldata signature ) external onlySigner { require(recipients.length != 0, 'Not enough recipients'); require( recipients.length == values.length, 'Unequal recipients and values' ); require(recipients.length < 256, 'Too many recipients, max 255'); // Verify the other signer bytes32 operationHash = keccak256( abi.encodePacked( getBatchNetworkId(), recipients, values, expireTime, sequenceId ) ); // the first parameter (toAddress) is used to ensure transactions in safe mode only go to a signer // if in safe mode, we should use normal sendMultiSig to recover, so this check will always fail if in safe mode require(!safeMode, 'Batch in safe mode'); address otherSigner = verifyMultiSig( address(0x0), operationHash, signature, expireTime, sequenceId ); batchTransfer(recipients, values); emit BatchTransacted(msg.sender, otherSigner, operationHash); } /** * Transfer funds in a batch to each of recipients * @param recipients The list of recipients to send to * @param values The list of values to send to recipients. * The recipient with index i in recipients array will be sent values[i]. * Thus, recipients and values must be the same length */ function batchTransfer( address[] calldata recipients, uint256[] calldata values ) internal { for (uint256 i = 0; i < recipients.length; i++) { require(address(this).balance >= values[i], 'Insufficient funds'); (bool success, ) = recipients[i].call{ value: values[i] }(''); require(success, 'Call failed'); emit BatchTransfer(msg.sender, recipients[i], values[i]); } } /** * Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover. * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated. * * @param toAddress the destination address to send an outgoing transaction * @param value the amount in tokens to be sent * @param tokenContractAddress the address of the erc20 token contract * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * @param signature see Data Formats */ function sendMultiSigToken( address toAddress, uint256 value, address tokenContractAddress, uint256 expireTime, uint256 sequenceId, bytes calldata signature ) external onlySigner { // Verify the other signer bytes32 operationHash = keccak256( abi.encodePacked( getTokenNetworkId(), toAddress, value, tokenContractAddress, expireTime, sequenceId ) ); verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId); TransferHelper.safeTransfer(tokenContractAddress, toAddress, value); } /** * Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc20 token contract */ function flushForwarderTokens( address payable forwarderAddress, address tokenContractAddress ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.flushTokens(tokenContractAddress); } /** * Execute a ERC721 token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc20 token contract */ function flushERC721ForwarderTokens( address payable forwarderAddress, address tokenContractAddress, uint256 tokenId ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.flushERC721Token(tokenContractAddress, tokenId); } /** * Execute a ERC1155 batch token flush from one of the forwarder addresses. * This transfer needs only a single signature and can be done by any signer. * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc1155 token contract */ function batchFlushERC1155ForwarderTokens( address payable forwarderAddress, address tokenContractAddress, uint256[] calldata tokenIds ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.batchFlushERC1155Tokens(tokenContractAddress, tokenIds); } /** * Execute a ERC1155 token flush from one of the forwarder addresses. * This transfer needs only a single signature and can be done by any signer. * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc1155 token contract * @param tokenId the token id associated with the ERC1155 */ function flushERC1155ForwarderTokens( address payable forwarderAddress, address tokenContractAddress, uint256 tokenId ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.flushERC1155Tokens(tokenContractAddress, tokenId); } /** * Sets the autoflush 721 parameter on the forwarder. * * @param forwarderAddress the address of the forwarder to toggle. * @param autoFlush whether to autoflush erc721 tokens */ function setAutoFlush721(address forwarderAddress, bool autoFlush) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.setAutoFlush721(autoFlush); } /** * Sets the autoflush 721 parameter on the forwarder. * * @param forwarderAddress the address of the forwarder to toggle. * @param autoFlush whether to autoflush erc1155 tokens */ function setAutoFlush1155(address forwarderAddress, bool autoFlush) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.setAutoFlush1155(autoFlush); } /** * Do common multisig verification for both eth sends and erc20token transfers * * @param toAddress the destination address to send an outgoing transaction * @param operationHash see Data Formats * @param signature see Data Formats * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * returns address that has created the signature */ function verifyMultiSig( address toAddress, bytes32 operationHash, bytes calldata signature, uint256 expireTime, uint256 sequenceId ) private returns (address) { address otherSigner = recoverAddressFromSignature(operationHash, signature); // Verify if we are in safe mode. In safe mode, the wallet can only send to signers require(!safeMode || isSigner(toAddress), 'External transfer in safe mode'); // Verify that the transaction has not expired require(expireTime >= block.timestamp, 'Transaction expired'); // Try to insert the sequence ID. Will revert if the sequence id was invalid tryInsertSequenceId(sequenceId); require(isSigner(otherSigner), 'Invalid signer'); require(otherSigner != msg.sender, 'Signers cannot be equal'); return otherSigner; } /** * ERC721 standard callback function for when a ERC721 is transfered. * * @param _operator The address of the nft contract * @param _from The address of the sender * @param _tokenId The token id of the nft * @param _data Additional data with no specified format, sent in call to `_to` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data ) external virtual override returns (bytes4) { return this.onERC721Received.selector; } /** * @inheritdoc IERC1155Receiver */ function onERC1155Received( address _operator, address _from, uint256 id, uint256 value, bytes calldata data ) external virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @inheritdoc IERC1155Receiver */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } /** * Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses. */ function activateSafeMode() external onlySigner { safeMode = true; emit SafeModeActivated(msg.sender); } /** * Gets signer's address using ecrecover * @param operationHash see Data Formats * @param signature see Data Formats * returns address recovered from the signature */ function recoverAddressFromSignature( bytes32 operationHash, bytes memory signature ) private pure returns (address) { require(signature.length == 65, 'Invalid signature - wrong length'); // We need to unpack the signature, which is given as an array of 65 bytes (like eth.sign) bytes32 r; bytes32 s; uint8 v; // solhint-disable-next-line assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := and(mload(add(signature, 65)), 255) } if (v < 27) { v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs } // protect against signature malleability // S value must be in the lower half orader // reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/051d340171a93a3d401aaaea46b4b62fa81e5d7c/contracts/cryptography/ECDSA.sol#L53 require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); // note that this returns 0 if the signature is invalid // Since 0x0 can never be a signer, when the recovered signer address // is checked against our signer list, that 0x0 will cause an invalid signer failure return ecrecover(operationHash, v, r, s); } /** * Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted. * We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and * greater than the minimum element in the window. * @param sequenceId to insert into array of stored ids */ function tryInsertSequenceId(uint256 sequenceId) private onlySigner { // Keep a pointer to the lowest value element in the window uint256 lowestValueIndex = 0; // fetch recentSequenceIds into memory for function context to avoid unnecessary sloads uint256[SEQUENCE_ID_WINDOW_SIZE] memory _recentSequenceIds = recentSequenceIds; for (uint256 i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { require(_recentSequenceIds[i] != sequenceId, 'Sequence ID already used'); if (_recentSequenceIds[i] < _recentSequenceIds[lowestValueIndex]) { lowestValueIndex = i; } } // The sequence ID being used is lower than the lowest value in the window // so we cannot accept it as it may have been used before require( sequenceId > _recentSequenceIds[lowestValueIndex], 'Sequence ID below window' ); // Block sequence IDs which are much higher than the lowest value // This prevents people blocking the contract by using very large sequence IDs quickly require( sequenceId <= (_recentSequenceIds[lowestValueIndex] + MAX_SEQUENCE_ID_INCREASE), 'Sequence ID above maximum' ); recentSequenceIds[lowestValueIndex] = sequenceId; } /** * Gets the next available sequence ID for signing when using executeAndConfirm * returns the sequenceId one higher than the highest currently stored */ function getNextSequenceId() external view returns (uint256) { uint256 highestSequenceId = 0; for (uint256 i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { if (recentSequenceIds[i] > highestSequenceId) { highestSequenceId = recentSequenceIds[i]; } } return highestSequenceId + 1; } }
contract WalletSimple is IERC721Receiver, ERC1155Receiver { // Events event Deposited(address from, uint256 value, bytes data); event SafeModeActivated(address msgSender); event Transacted( address msgSender, // Address of the sender of the message initiating the transaction address otherSigner, // Address of the signer (second signature) used to initiate the transaction bytes32 operation, // Operation hash (see Data Formats) address toAddress, // The address the transaction was sent to uint256 value, // Amount of Wei sent to the address bytes data // Data sent when invoking the transaction ); event BatchTransfer(address sender, address recipient, uint256 value); // this event shows the other signer and the operation hash that they signed // specific batch transfer events are emitted in Batcher event BatchTransacted( address msgSender, // Address of the sender of the message initiating the transaction address otherSigner, // Address of the signer (second signature) used to initiate the transaction bytes32 operation // Operation hash (see Data Formats) ); // Public fields mapping(address => bool) public signers; // The addresses that can co-sign transactions on the wallet bool public safeMode = false; // When active, wallet may only send to signer addresses bool public initialized = false; // True if the contract has been initialized // Internal fields uint256 private constant MAX_SEQUENCE_ID_INCREASE = 10000; uint256 constant SEQUENCE_ID_WINDOW_SIZE = 10; uint256[SEQUENCE_ID_WINDOW_SIZE] recentSequenceIds; /** * Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet. * 2 signers will be required to send a transaction from this wallet. * Note: The sender is NOT automatically added to the list of signers. * Signers CANNOT be changed once they are set * * @param allowedSigners An array of signers on the wallet */ function init(address[] calldata allowedSigners) external onlyUninitialized { require(allowedSigners.length == 3, 'Invalid number of signers'); for (uint8 i = 0; i < allowedSigners.length; i++) { require(allowedSigners[i] != address(0), 'Invalid signer'); signers[allowedSigners[i]] = true; } initialized = true; } /** * Get the network identifier that signers must sign over * This provides protection signatures being replayed on other chains * This must be a virtual function because chain-specific contracts will need * to override with their own network ids. It also can't be a field * to allow this contract to be used by proxy with delegatecall, which will * not pick up on state variables */ function getNetworkId() internal virtual pure returns (string memory) { return 'ETHER'; } /** * Get the network identifier that signers must sign over for token transfers * This provides protection signatures being replayed on other chains * This must be a virtual function because chain-specific contracts will need * to override with their own network ids. It also can't be a field * to allow this contract to be used by proxy with delegatecall, which will * not pick up on state variables */ function getTokenNetworkId() internal virtual pure returns (string memory) { return 'ERC20'; } /** * Get the network identifier that signers must sign over for batch transfers * This provides protection signatures being replayed on other chains * This must be a virtual function because chain-specific contracts will need * to override with their own network ids. It also can't be a field * to allow this contract to be used by proxy with delegatecall, which will * not pick up on state variables */ function getBatchNetworkId() internal virtual pure returns (string memory) { return 'ETHER-Batch'; } /** * Determine if an address is a signer on this wallet * @param signer address to check * returns boolean indicating whether address is signer or not */ function isSigner(address signer) public view returns (bool) { return signers[signer]; } /** * Modifier that will execute internal code block only if the sender is an authorized signer on this wallet */ modifier onlySigner { require(isSigner(msg.sender), 'Non-signer in onlySigner method'); _; } /** * Modifier that will execute internal code block only if the contract has not been initialized yet */ modifier onlyUninitialized { require(!initialized, 'Contract already initialized'); _; } /** * Gets called when a transaction is received with data that does not match any other method */ fallback() external payable { if (msg.value > 0) { // Fire deposited event if we are receiving funds emit Deposited(msg.sender, msg.value, msg.data); } } /** * Gets called when a transaction is received with ether and no data */ receive() external payable { if (msg.value > 0) { // Fire deposited event if we are receiving funds // message data is always empty for receive. If there is data it is sent to fallback function. emit Deposited(msg.sender, msg.value, ''); } } /** * Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover. * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated. * * @param toAddress the destination address to send an outgoing transaction * @param value the amount in Wei to be sent * @param data the data to send to the toAddress when invoking the transaction * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * @param signature see Data Formats */ function sendMultiSig( address toAddress, uint256 value, bytes calldata data, uint256 expireTime, uint256 sequenceId, bytes calldata signature ) external onlySigner { // Verify the other signer bytes32 operationHash = keccak256( abi.encodePacked( getNetworkId(), toAddress, value, data, expireTime, sequenceId ) ); address otherSigner = verifyMultiSig( toAddress, operationHash, signature, expireTime, sequenceId ); // Success, send the transaction (bool success, ) = toAddress.call{ value: value }(data); require(success, 'Call execution failed'); emit Transacted( msg.sender, otherSigner, operationHash, toAddress, value, data ); } /** * Execute a batched multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover. * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated. * The recipients and values to send are encoded in two arrays, where for index i, recipients[i] will be sent values[i]. * * @param recipients The list of recipients to send to * @param values The list of values to send to * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * @param signature see Data Formats */ function sendMultiSigBatch( address[] calldata recipients, uint256[] calldata values, uint256 expireTime, uint256 sequenceId, bytes calldata signature ) external onlySigner { require(recipients.length != 0, 'Not enough recipients'); require( recipients.length == values.length, 'Unequal recipients and values' ); require(recipients.length < 256, 'Too many recipients, max 255'); // Verify the other signer bytes32 operationHash = keccak256( abi.encodePacked( getBatchNetworkId(), recipients, values, expireTime, sequenceId ) ); // the first parameter (toAddress) is used to ensure transactions in safe mode only go to a signer // if in safe mode, we should use normal sendMultiSig to recover, so this check will always fail if in safe mode require(!safeMode, 'Batch in safe mode'); address otherSigner = verifyMultiSig( address(0x0), operationHash, signature, expireTime, sequenceId ); batchTransfer(recipients, values); emit BatchTransacted(msg.sender, otherSigner, operationHash); } /** * Transfer funds in a batch to each of recipients * @param recipients The list of recipients to send to * @param values The list of values to send to recipients. * The recipient with index i in recipients array will be sent values[i]. * Thus, recipients and values must be the same length */ function batchTransfer( address[] calldata recipients, uint256[] calldata values ) internal { for (uint256 i = 0; i < recipients.length; i++) { require(address(this).balance >= values[i], 'Insufficient funds'); (bool success, ) = recipients[i].call{ value: values[i] }(''); require(success, 'Call failed'); emit BatchTransfer(msg.sender, recipients[i], values[i]); } } /** * Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover. * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated. * * @param toAddress the destination address to send an outgoing transaction * @param value the amount in tokens to be sent * @param tokenContractAddress the address of the erc20 token contract * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * @param signature see Data Formats */ function sendMultiSigToken( address toAddress, uint256 value, address tokenContractAddress, uint256 expireTime, uint256 sequenceId, bytes calldata signature ) external onlySigner { // Verify the other signer bytes32 operationHash = keccak256( abi.encodePacked( getTokenNetworkId(), toAddress, value, tokenContractAddress, expireTime, sequenceId ) ); verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId); TransferHelper.safeTransfer(tokenContractAddress, toAddress, value); } /** * Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc20 token contract */ function flushForwarderTokens( address payable forwarderAddress, address tokenContractAddress ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.flushTokens(tokenContractAddress); } /** * Execute a ERC721 token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc20 token contract */ function flushERC721ForwarderTokens( address payable forwarderAddress, address tokenContractAddress, uint256 tokenId ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.flushERC721Token(tokenContractAddress, tokenId); } /** * Execute a ERC1155 batch token flush from one of the forwarder addresses. * This transfer needs only a single signature and can be done by any signer. * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc1155 token contract */ function batchFlushERC1155ForwarderTokens( address payable forwarderAddress, address tokenContractAddress, uint256[] calldata tokenIds ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.batchFlushERC1155Tokens(tokenContractAddress, tokenIds); } /** * Execute a ERC1155 token flush from one of the forwarder addresses. * This transfer needs only a single signature and can be done by any signer. * * @param forwarderAddress the address of the forwarder address to flush the tokens from * @param tokenContractAddress the address of the erc1155 token contract * @param tokenId the token id associated with the ERC1155 */ function flushERC1155ForwarderTokens( address payable forwarderAddress, address tokenContractAddress, uint256 tokenId ) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.flushERC1155Tokens(tokenContractAddress, tokenId); } /** * Sets the autoflush 721 parameter on the forwarder. * * @param forwarderAddress the address of the forwarder to toggle. * @param autoFlush whether to autoflush erc721 tokens */ function setAutoFlush721(address forwarderAddress, bool autoFlush) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.setAutoFlush721(autoFlush); } /** * Sets the autoflush 721 parameter on the forwarder. * * @param forwarderAddress the address of the forwarder to toggle. * @param autoFlush whether to autoflush erc1155 tokens */ function setAutoFlush1155(address forwarderAddress, bool autoFlush) external onlySigner { IForwarder forwarder = IForwarder(forwarderAddress); forwarder.setAutoFlush1155(autoFlush); } /** * Do common multisig verification for both eth sends and erc20token transfers * * @param toAddress the destination address to send an outgoing transaction * @param operationHash see Data Formats * @param signature see Data Formats * @param expireTime the number of seconds since 1970 for which this transaction is valid * @param sequenceId the unique sequence id obtainable from getNextSequenceId * returns address that has created the signature */ function verifyMultiSig( address toAddress, bytes32 operationHash, bytes calldata signature, uint256 expireTime, uint256 sequenceId ) private returns (address) { address otherSigner = recoverAddressFromSignature(operationHash, signature); // Verify if we are in safe mode. In safe mode, the wallet can only send to signers require(!safeMode || isSigner(toAddress), 'External transfer in safe mode'); // Verify that the transaction has not expired require(expireTime >= block.timestamp, 'Transaction expired'); // Try to insert the sequence ID. Will revert if the sequence id was invalid tryInsertSequenceId(sequenceId); require(isSigner(otherSigner), 'Invalid signer'); require(otherSigner != msg.sender, 'Signers cannot be equal'); return otherSigner; } /** * ERC721 standard callback function for when a ERC721 is transfered. * * @param _operator The address of the nft contract * @param _from The address of the sender * @param _tokenId The token id of the nft * @param _data Additional data with no specified format, sent in call to `_to` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data ) external virtual override returns (bytes4) { return this.onERC721Received.selector; } /** * @inheritdoc IERC1155Receiver */ function onERC1155Received( address _operator, address _from, uint256 id, uint256 value, bytes calldata data ) external virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @inheritdoc IERC1155Receiver */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } /** * Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses. */ function activateSafeMode() external onlySigner { safeMode = true; emit SafeModeActivated(msg.sender); } /** * Gets signer's address using ecrecover * @param operationHash see Data Formats * @param signature see Data Formats * returns address recovered from the signature */ function recoverAddressFromSignature( bytes32 operationHash, bytes memory signature ) private pure returns (address) { require(signature.length == 65, 'Invalid signature - wrong length'); // We need to unpack the signature, which is given as an array of 65 bytes (like eth.sign) bytes32 r; bytes32 s; uint8 v; // solhint-disable-next-line assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := and(mload(add(signature, 65)), 255) } if (v < 27) { v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs } // protect against signature malleability // S value must be in the lower half orader // reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/051d340171a93a3d401aaaea46b4b62fa81e5d7c/contracts/cryptography/ECDSA.sol#L53 require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); // note that this returns 0 if the signature is invalid // Since 0x0 can never be a signer, when the recovered signer address // is checked against our signer list, that 0x0 will cause an invalid signer failure return ecrecover(operationHash, v, r, s); } /** * Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted. * We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and * greater than the minimum element in the window. * @param sequenceId to insert into array of stored ids */ function tryInsertSequenceId(uint256 sequenceId) private onlySigner { // Keep a pointer to the lowest value element in the window uint256 lowestValueIndex = 0; // fetch recentSequenceIds into memory for function context to avoid unnecessary sloads uint256[SEQUENCE_ID_WINDOW_SIZE] memory _recentSequenceIds = recentSequenceIds; for (uint256 i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { require(_recentSequenceIds[i] != sequenceId, 'Sequence ID already used'); if (_recentSequenceIds[i] < _recentSequenceIds[lowestValueIndex]) { lowestValueIndex = i; } } // The sequence ID being used is lower than the lowest value in the window // so we cannot accept it as it may have been used before require( sequenceId > _recentSequenceIds[lowestValueIndex], 'Sequence ID below window' ); // Block sequence IDs which are much higher than the lowest value // This prevents people blocking the contract by using very large sequence IDs quickly require( sequenceId <= (_recentSequenceIds[lowestValueIndex] + MAX_SEQUENCE_ID_INCREASE), 'Sequence ID above maximum' ); recentSequenceIds[lowestValueIndex] = sequenceId; } /** * Gets the next available sequence ID for signing when using executeAndConfirm * returns the sequenceId one higher than the highest currently stored */ function getNextSequenceId() external view returns (uint256) { uint256 highestSequenceId = 0; for (uint256 i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { if (recentSequenceIds[i] > highestSequenceId) { highestSequenceId = recentSequenceIds[i]; } } return highestSequenceId + 1; } }
16,886
28
// return - the number of hours wait time for any critical update/
function speedBumpHours() public view returns (uint16){ TreasuryBase t = TreasuryBase(treasuryAddress()); return t.speedBumpHours(); }
function speedBumpHours() public view returns (uint16){ TreasuryBase t = TreasuryBase(treasuryAddress()); return t.speedBumpHours(); }
17,450
1,302
// 653
entry "sundrily" : ENG_ADVERB
entry "sundrily" : ENG_ADVERB
21,489
19
// instead of reverting, return 0 if nothing is due so multiple schedules can be checked
if (vested == 0) { return 0; }
if (vested == 0) { return 0; }
35,130
57
// set parent references in child proposals
if (i > 0) { Proposal storage p = proposals[id]; p.parentProposalId = ids[0]; }
if (i > 0) { Proposal storage p = proposals[id]; p.parentProposalId = ids[0]; }
47,394
64
// @_amount: wbtc amount
function deposit_wbtc(uint256 _amount) internal { IERC20(wbtc).transferFrom(msg.sender, address(this), _amount); IERC20(wbtc).approve(address(pool_deposit), 0); IERC20(wbtc).approve(address(pool_deposit), _amount); uint256[2] memory uamounts = [uint256(0), _amount]; pool_deposit.add_liquidity(uamounts, 0); }
function deposit_wbtc(uint256 _amount) internal { IERC20(wbtc).transferFrom(msg.sender, address(this), _amount); IERC20(wbtc).approve(address(pool_deposit), 0); IERC20(wbtc).approve(address(pool_deposit), _amount); uint256[2] memory uamounts = [uint256(0), _amount]; pool_deposit.add_liquidity(uamounts, 0); }
35,703
27
// Transfer a tile owned by another address, for which the calling address/has previously been granted transfer approval by the owner./_from The address that owns the tile to be transfered./_to The address that should take ownership of the tile. Can be any address,/including the caller./_tokenId The ID of the tile to be transferred./Required for ERC-721 compliance.
function transferFrom( address _from, address _to, uint256 _tokenId ) external
function transferFrom( address _from, address _to, uint256 _tokenId ) external
18,726
85
// Determine Runner PortionsNote, torch has already been passed, so torchRunners[0]is the current torch runner
if (_previousLast != address(0)) { runnerPortions[2] = _forPayout.mul(10).div(100); }
if (_previousLast != address(0)) { runnerPortions[2] = _forPayout.mul(10).div(100); }
64,503
50
// -------------------------- Trait Rarity functions--------------------------/ Clears the trait rarity for a given trait (Ex. hair which is 0). traitIndex The index we want to clear. /
function clearTraitRarity(uint256 traitIndex) external onlyOwner { delete traitRarity[traitIndex]; }
function clearTraitRarity(uint256 traitIndex) external onlyOwner { delete traitRarity[traitIndex]; }
70,620
46
// The contract can be initialized with a number of tokensAll the tokens are deposited to the owner address_balance Initial supply of the contract_name Token Name_symbol Token symbol_decimals Token decimals
function TetherToken1(uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; }
function TetherToken1(uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; }
5,297
1
// Emits on updating the virtual price bounds
event NewLimiterParams(uint256 lowerBound, uint256 upperBound);
event NewLimiterParams(uint256 lowerBound, uint256 upperBound);
34,805
20
// ------------------------------------------------------------------------ Transfer tokens from the from account to the to accountThe 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) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
28,479
490
// Decompress the data here so we can extract the data directly from calldata
bytes4 selector = IDecompressor(0x0).decompress.selector; bytes memory decompressed; assembly {
bytes4 selector = IDecompressor(0x0).decompress.selector; bytes memory decompressed; assembly {
28,766
1
// Can't access this vars using id, name, pickCount Must us position in function ex team[1] will return id team[0].toNumber will return int/
struct Team { uint id; string name; uint pickCount; }
struct Team { uint id; string name; uint pickCount; }
35,498
44
// Destroys `tokenId`. The approval is cleared when the token is burned.
function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); delete _owners[tokenId_]; totalSupply--; _balanceOf[owner]--; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); }
function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); delete _owners[tokenId_]; totalSupply--; _balanceOf[owner]--; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); }
11,338
50
// repeat while the mask is not empty
while (mask != 0) {
while (mask != 0) {
2,486
7
// Sets or unsets the approval of a given operatorAn operator is allowed to transfer all tokens of the sender on their behalf operator address to set the approval approved representing the status of the approval to be set /
function setApprovalForAll(address operator, bool approved) external override
function setApprovalForAll(address operator, bool approved) external override
8,793
14
// Performs a swap before bridging via Across/_lifiData data used purely for tracking and analytics/_swapData an array of swap related data for performing swaps before bridging/_acrossData data specific to Across
function swapAndStartBridgeTokensViaAcross( LiFiData calldata _lifiData, LibSwap.SwapData[] calldata _swapData, AcrossData memory _acrossData
function swapAndStartBridgeTokensViaAcross( LiFiData calldata _lifiData, LibSwap.SwapData[] calldata _swapData, AcrossData memory _acrossData
25,406
131
// Need to use proxy-wide FRAX balance if applicable, to prevent exploiting
veFXS_needed_for_max_boost = (the_proxy == address(0)) ? minVeFXSForMaxBoost(account) : minVeFXSForMaxBoostProxy(the_proxy); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (vefxs_bal_to_use * MULTIPLIER_PRECISION) / veFXS_needed_for_max_boost; mult_optn_2 = (user_vefxs_fraction * vefxs_max_multiplier) / MULTIPLIER_PRECISION; }
veFXS_needed_for_max_boost = (the_proxy == address(0)) ? minVeFXSForMaxBoost(account) : minVeFXSForMaxBoostProxy(the_proxy); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (vefxs_bal_to_use * MULTIPLIER_PRECISION) / veFXS_needed_for_max_boost; mult_optn_2 = (user_vefxs_fraction * vefxs_max_multiplier) / MULTIPLIER_PRECISION; }
4,439
3
// return eip-1167 code to write it to spawned contract runtime.
assembly { return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length }
assembly { return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length }
45,099
35
// Decode a `CBOR.Value` structure into a native `int128[]` value. _cborValue An instance of `CBOR.Value`.return The value represented by the input, as an `int128[]` value. /
function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; }
function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; }
11,859
0
// uint256 EGGS_PER_MINERS_PER_SECOND=1;
uint256 public EGGS_TO_HATCH_1MINERS = 2592000; //for final version should be seconds in a day uint256 PSN = 10000; uint256 PSNH = 5000; bool public initialized = false; address payable public ceoAddress; address payable public ceoAddress2; mapping(address => uint256) public hatcheryMiners; mapping(address => uint256) public claimedEggs; mapping(address => uint256) public lastHatch; mapping(address => address) public referrals;
uint256 public EGGS_TO_HATCH_1MINERS = 2592000; //for final version should be seconds in a day uint256 PSN = 10000; uint256 PSNH = 5000; bool public initialized = false; address payable public ceoAddress; address payable public ceoAddress2; mapping(address => uint256) public hatcheryMiners; mapping(address => uint256) public claimedEggs; mapping(address => uint256) public lastHatch; mapping(address => address) public referrals;
13,194
29
// Cast a with a reason
* Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public returns (uint256) { address voter = address(msg.sender); return LibGovernor.castVote(proposalId, voter, support, reason); }
* Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public returns (uint256) { address voter = address(msg.sender); return LibGovernor.castVote(proposalId, voter, support, reason); }
24,862
30
// Verify that the given transfer state is included in the "finalized" channel state
bytes32 transferStateHash = hashTransferState(cts); verifyMerkleProof( merkleProofData, channelDispute.merkleRoot, transferStateHash );
bytes32 transferStateHash = hashTransferState(cts); verifyMerkleProof( merkleProofData, channelDispute.merkleRoot, transferStateHash );
42,291
18
// Event emitted when user unstaked in emergency mode. user Address of the user. tokenId unstaked tokenId. /
event EmergencyUnstake(address indexed user, uint256 tokenId);
event EmergencyUnstake(address indexed user, uint256 tokenId);
59,585
145
// require(account == msg.sender,"you are not authorized on this account!");
require(stakers[account].amount >= amount, "Insufficient amount!"); require(_token.transfer(account, amount), "Transfer error!"); consolidate(account); stakers[account].amount = stakers[account].amount.sub(amount); total = total.sub(amount);
require(stakers[account].amount >= amount, "Insufficient amount!"); require(_token.transfer(account, amount), "Transfer error!"); consolidate(account); stakers[account].amount = stakers[account].amount.sub(amount); total = total.sub(amount);
67,068
79
// There are additional minimum reserve init and token supply restrictions enforced by `RedeemableERC20` and `RedeemableERC20Pool`. This ensures that the weightings and valuations will be in a sensible range according to the internal assumptions made by Balancer etc.
require( trustRedeemableERC20Config_.totalSupply >= trustRedeemableERC20PoolConfig_.reserveInit, "MIN_TOKEN_SUPPLY" ); uint256 successBalance_ = trustRedeemableERC20PoolConfig_.reserveInit .add(config_.seederFee) .add(config_.redeemInit) .add(config_.minimumCreatorRaise);
require( trustRedeemableERC20Config_.totalSupply >= trustRedeemableERC20PoolConfig_.reserveInit, "MIN_TOKEN_SUPPLY" ); uint256 successBalance_ = trustRedeemableERC20PoolConfig_.reserveInit .add(config_.seederFee) .add(config_.redeemInit) .add(config_.minimumCreatorRaise);
33,440
187
// Now point_history is filled until t=now
if (_tokenId != 0) {
if (_tokenId != 0) {
72,169
194
// Max. ceiling possible [wad]
uint256 maxDebtCeiling;
uint256 maxDebtCeiling;
40,967
1,390
// 696
entry "monoinfected" : ENG_ADJECTIVE
entry "monoinfected" : ENG_ADJECTIVE
17,308
24
// withdraw
function withdraw(address _to, uint256 _value) public
function withdraw(address _to, uint256 _value) public
45,536
0
// ETH/USD
PRICE_FEEDERS[ address(0) ] = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e;
PRICE_FEEDERS[ address(0) ] = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e;
9,540
72
// Set the number of selectors in the array
assembly { mstore(_facetFunctionSelectors, numSelectors) }
assembly { mstore(_facetFunctionSelectors, numSelectors) }
53,657
0
// @inheritdoc IOperatorFiltererFacet
function registerOperatorFilterer(address subscriptionOrRegistrantToCopy, bool subscribe) external onlyAccessControlAdmin { OperatorFiltererLib._register(subscriptionOrRegistrantToCopy, subscribe); }
function registerOperatorFilterer(address subscriptionOrRegistrantToCopy, bool subscribe) external onlyAccessControlAdmin { OperatorFiltererLib._register(subscriptionOrRegistrantToCopy, subscribe); }
15,176
2
// Immutable variables/ solhint-disable-next-line func-name-mixedcase
function CONSTANT_OUTFLOW_NFT() external view returns (IConstantOutflowNFT);
function CONSTANT_OUTFLOW_NFT() external view returns (IConstantOutflowNFT);
32,002
89
// --Add participant address Manager only--
function Addparticipant(address[] memory _ParticipantAddrs) public onlyManager returns (bool) { uint _addressAmount = _ParticipantAddrs.length; for (uint i = 0; i < _addressAmount; i++){ if(!isWhitelist(_ParticipantAddrs[i])){ participantList.push(_ParticipantAddrs[i]); addWhitelist(_ParticipantAddrs[i]); }else{ participantList.push(_ParticipantAddrs[i]); } } return true; }
function Addparticipant(address[] memory _ParticipantAddrs) public onlyManager returns (bool) { uint _addressAmount = _ParticipantAddrs.length; for (uint i = 0; i < _addressAmount; i++){ if(!isWhitelist(_ParticipantAddrs[i])){ participantList.push(_ParticipantAddrs[i]); addWhitelist(_ParticipantAddrs[i]); }else{ participantList.push(_ParticipantAddrs[i]); } } return true; }
19,665
126
// Get balance of a payee _requestId Request id _payeeIndex payee index (0 = main payee)return balance /
function getPayeeBalance(bytes32 _requestId, uint8 _payeeIndex) public constant returns(int256)
function getPayeeBalance(bytes32 _requestId, uint8 _payeeIndex) public constant returns(int256)
68,683
2
// Emitted when someone withdraws asset from this contract./See https:eips.ethereum.org/EIPS/eip-4626/sender The address who call the function./receiver The address who will receive the assets./owner The address who owns the assets./assets The amount of asset withdrawn./shares The amounf of pool shares to withdraw.
event Withdraw( address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares );
event Withdraw( address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares );
9,107
53
// Safe BSW transfer function, just in case if rounding error causes pool to not have enough BSWs.
function safeBSWTransfer(address _to, uint256 _amount) internal { uint256 BSWBal = BSW.balanceOf(address(this)); if (_amount > BSWBal) { BSW.transfer(_to, BSWBal); } else { BSW.transfer(_to, _amount); } }
function safeBSWTransfer(address _to, uint256 _amount) internal { uint256 BSWBal = BSW.balanceOf(address(this)); if (_amount > BSWBal) { BSW.transfer(_to, BSWBal); } else { BSW.transfer(_to, _amount); } }
11,483
141
// A checkpoint for marking number of votes from a given block
struct Checkpoint { uint32 fromBlock; uint256 votes; }
struct Checkpoint { uint32 fromBlock; uint256 votes; }
1,852
22
// market maker fee will never be more than 1%
uint256 oldFee = makerFee; if (_makerFee > 10 finney) { _makerFee = 10 finney; }
uint256 oldFee = makerFee; if (_makerFee > 10 finney) { _makerFee = 10 finney; }
12,266
5
// Allows owner to change ownership _owner new owner address to set /
function setOwner(address payable _owner) external { require(msg.sender == owner, "owner: !owner"); pendingOwner = _owner; }
function setOwner(address payable _owner) external { require(msg.sender == owner, "owner: !owner"); pendingOwner = _owner; }
41,688
282
// enables trading in a given pool, by providing the funding rate as two virtual balances, and updates itstrading liquidity please note that the virtual balances should be derived from token prices, normalized to the smallest unit oftokens. For example: - if the price of one (1018 wei) BNT is $X and the price of one (1018 wei) TKN is $Y, then the virtual balancesshould represent a ratio of X to Y- if the price of one (1018 wei) BNT is $X and the price of one (106 wei) USDC is $Y, then the virtual balancesshould represent a ratio of X
function enableTrading( Token pool, uint256 bntVirtualBalance, uint256 baseTokenVirtualBalance
function enableTrading( Token pool, uint256 bntVirtualBalance, uint256 baseTokenVirtualBalance
75,546
292
// Right Lendroid Foundation A smart contract for NFT Rights /
abstract contract Right is ERC721, Ownable { using ExtendedStrings for string; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; function _mintTo(address to) internal { uint256 newTokenId = _getNextTokenId(); _mint(to, newTokenId); _incrementTokenId(); } /** * @notice Allows owner to mint a a token to a given address * dev Mints a new token to the given address, increments currentTokenId * @param to address of the future owner of the token */ function mintTo(address to) public onlyOwner { _mintTo(to); } /** * @notice Displays the id of the latest token that was minted * @return uint256 : latest minted token id */ function currentTokenId() public view returns (uint256) { return _tokenIdTracker.current(); } /** * @notice Displays the id of the next token that will be minted * @dev Calculates the next token ID based on value of _currentTokenId * @return uint256 : id of the next token */ function _getNextTokenId() private view returns (uint256) { return _tokenIdTracker.current().add(1); } /** * @notice Increments the value of _currentTokenId * @dev Internal function that increases the value of _currentTokenId by 1 */ function _incrementTokenId() private { _tokenIdTracker.increment(); } /** * @notice set the base api url of the Right token * @param url : string representing the api url */ function setApiBaseUrl(string memory url) external onlyOwner { _setBaseURI(url); } }
abstract contract Right is ERC721, Ownable { using ExtendedStrings for string; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; function _mintTo(address to) internal { uint256 newTokenId = _getNextTokenId(); _mint(to, newTokenId); _incrementTokenId(); } /** * @notice Allows owner to mint a a token to a given address * dev Mints a new token to the given address, increments currentTokenId * @param to address of the future owner of the token */ function mintTo(address to) public onlyOwner { _mintTo(to); } /** * @notice Displays the id of the latest token that was minted * @return uint256 : latest minted token id */ function currentTokenId() public view returns (uint256) { return _tokenIdTracker.current(); } /** * @notice Displays the id of the next token that will be minted * @dev Calculates the next token ID based on value of _currentTokenId * @return uint256 : id of the next token */ function _getNextTokenId() private view returns (uint256) { return _tokenIdTracker.current().add(1); } /** * @notice Increments the value of _currentTokenId * @dev Internal function that increases the value of _currentTokenId by 1 */ function _incrementTokenId() private { _tokenIdTracker.increment(); } /** * @notice set the base api url of the Right token * @param url : string representing the api url */ function setApiBaseUrl(string memory url) external onlyOwner { _setBaseURI(url); } }
8,160
54
// Computes the token0 and token1 value for a given amount of liquidity, the current/ pool prices and the prices at the tick boundaries/sqrtRatioX96 A sqrt price representing the current pool prices/sqrtRatioAX96 A sqrt price representing the first tick boundary/sqrtRatioBX96 A sqrt price representing the second tick boundary/liquidity The liquidity being valued/ return amount0 The amount of token0/ return amount1 The amount of token1
function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity
function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity
5,208
179
// Anyone can checkpoint another user
function checkpointOtherUser(address user_addr) external { _checkpointUser(user_addr); }
function checkpointOtherUser(address user_addr) external { _checkpointUser(user_addr); }
64,254
9
// Check if the ballot can be voted
uint256 ballotType = checkVotable(ballotIdx);
uint256 ballotType = checkVotable(ballotIdx);
49,398
308
// Invert denominator mod 2256 Now that denominator is an odd number, it has an inverse modulo 2256 such that denominatorinv = 1 mod 2256. Compute the inverse by starting with a seed that is correct correct for four bits. That is, denominatorinv = 1 mod 24
uint256 inv = (3 * denominator) ^ 2;
uint256 inv = (3 * denominator) ^ 2;
35,003
11
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
7,783
17
// - the token address. /
function addPriceFeed(bytes4 _erc2362id, address _token) internal { IERC165 _newPriceFeed = witnetPriceRouter.getPriceFeed( bytes4(_erc2362id) ); require( address(_newPriceFeed) != address(0), "Failed to add price feed. Price feed address is invalid!" );
function addPriceFeed(bytes4 _erc2362id, address _token) internal { IERC165 _newPriceFeed = witnetPriceRouter.getPriceFeed( bytes4(_erc2362id) ); require( address(_newPriceFeed) != address(0), "Failed to add price feed. Price feed address is invalid!" );
22,955
95
// In forking mode, explicitly grant the given address cheatcode access
function allowCheatcodes(address account) external;
function allowCheatcodes(address account) external;
27,680
47
// Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address.- `account` must have at least `amount` tokens. /
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount;
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount;
35,840
44
// Lottery generator numbers by given hash./
function randomizerLottery(bytes32 hash, address sender) private returns(bool, uint256[] memory) { uint256[] memory lotteryNumbers = new uint256[](7); bytes32 userHash = keccak256(abi.encodePacked( hash, sender, random(999) )); bool win = true; for (uint i = 0; i < 7; i++) { uint position = i + random(1); bytes1 charAtPos = charAt(userHash, position); uint8 firstNums = getLastN(charAtPos, 4); uint firstNumInt = uint(firstNums); if (firstNumInt > 9) { firstNumInt = 16 - firstNumInt; } lotteryNumbers[i] = firstNumInt; if (firstNums != 7) { win = false; } } return (win, lotteryNumbers); }
function randomizerLottery(bytes32 hash, address sender) private returns(bool, uint256[] memory) { uint256[] memory lotteryNumbers = new uint256[](7); bytes32 userHash = keccak256(abi.encodePacked( hash, sender, random(999) )); bool win = true; for (uint i = 0; i < 7; i++) { uint position = i + random(1); bytes1 charAtPos = charAt(userHash, position); uint8 firstNums = getLastN(charAtPos, 4); uint firstNumInt = uint(firstNums); if (firstNumInt > 9) { firstNumInt = 16 - firstNumInt; } lotteryNumbers[i] = firstNumInt; if (firstNums != 7) { win = false; } } return (win, lotteryNumbers); }
25,256
63
// transfer a token and remove the ask for it. /
function _transfer( address from, address to, uint256 tokenId
function _transfer( address from, address to, uint256 tokenId
21,730
171
// enable
_autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify();
_autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify();
13,024
87
// Decode an array of natural numeric values from a Result as a `uint64[]` value. _result An instance of Result.return The `uint64[]` decoded from the Result. /
function asUint64Array(Result memory _result) public pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); }
function asUint64Array(Result memory _result) public pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); }
6,719
35
// Set the treasury vault for this vault /
function setTreasury(uint256 treasury_) external onlyRole(TREASURY_ROLE) { require(vaultExistence[treasury_], 'Vault does not exist'); treasury = treasury_; }
function setTreasury(uint256 treasury_) external onlyRole(TREASURY_ROLE) { require(vaultExistence[treasury_], 'Vault does not exist'); treasury = treasury_; }
26,945
26
// those are the public addresses on etherscan
address private uniswapRouterV2 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address private WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address private uniswapFactory = address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); address sidepotAddress = 0x000000000000000000000000000000000000dEaD; event Survivor(address indexed who);
address private uniswapRouterV2 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address private WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address private uniswapFactory = address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); address sidepotAddress = 0x000000000000000000000000000000000000dEaD; event Survivor(address indexed who);
8,158
6
// Required methods
function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external;
function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external;
14,505
11
// _ItemsID= Total n. of items of Nfts on this market place.
Counters.Counter private _ItemsId;
Counters.Counter private _ItemsId;
28,083
0
// Set the deposit verifier contract. This can be only called by the operator. _contract address of the verifier contract. /
function setDepositVerifier(address _contract) public onlyOperator { _depositVerifier = IEthDepositVerifier(_contract); }
function setDepositVerifier(address _contract) public onlyOperator { _depositVerifier = IEthDepositVerifier(_contract); }
36,251
17
// Permissioned Sorbetto variables/Contains Sorbetto variables that may only be called by the governance
contract SorbettoStrategy is ISorbettoStrategy { // Address of the Sorbetto's strategy owner address public governance; // Pending to claim ownership address address public pendingGovernance; /// @inheritdoc ISorbettoStrategy uint32 public override twapDuration; /// @inheritdoc ISorbettoStrategy int24 public override maxTwapDeviation; /// @inheritdoc ISorbettoStrategy int24 public override tickRangeMultiplier; /// @inheritdoc ISorbettoStrategy uint24 public override protocolFee; /// @inheritdoc ISorbettoStrategy uint24 public override priceImpactPercentage; /** * @param _twapDuration TWAP duration in seconds for rebalance check * @param _maxTwapDeviation Max deviation from TWAP during rebalance * @param _tickRangeMultiplier Used to determine base order range * @param _protocolFee The protocol's fee in hundredths of a bip, i.e. 1e-6 * @param _priceImpactPercentage The price impact percentage during swap in hundredths of a bip, i.e. 1e-6 */ constructor( uint32 _twapDuration, int24 _maxTwapDeviation, int24 _tickRangeMultiplier, uint24 _protocolFee, uint24 _priceImpactPercentage ) { twapDuration = _twapDuration; maxTwapDeviation = _maxTwapDeviation; tickRangeMultiplier = _tickRangeMultiplier; protocolFee = _protocolFee; priceImpactPercentage = _priceImpactPercentage; governance = msg.sender; require(_maxTwapDeviation >= 0, "maxTwapDeviation"); require(_twapDuration > 0, "twapDuration"); require(_protocolFee < 1e6 && _protocolFee > 0, "PF"); require(_priceImpactPercentage < 1e6 && _priceImpactPercentage > 0, "PIP"); } modifier onlyGovernance { require(msg.sender == governance, "NOT ALLOWED"); _; } function setTwapDuration(uint32 _twapDuration) external onlyGovernance { require(_twapDuration > 0, "twapDuration"); twapDuration = _twapDuration; } function setMaxTwapDeviation(int24 _maxTwapDeviation) external onlyGovernance { require(_maxTwapDeviation > 0, "PF"); maxTwapDeviation = _maxTwapDeviation; } function setTickRange(int24 _tickRangeMultiplier) external onlyGovernance { tickRangeMultiplier = _tickRangeMultiplier; } function setProtocolFee(uint16 _protocolFee) external onlyGovernance { require(_protocolFee < 1e6 && _protocolFee > 0, "PF"); protocolFee = _protocolFee; } function setPriceImpact(uint16 _priceImpactPercentage) external onlyGovernance { require(_priceImpactPercentage < 1e6 && _priceImpactPercentage > 0, "PIP"); priceImpactPercentage = _priceImpactPercentage; } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "PG"); governance = msg.sender; } }
contract SorbettoStrategy is ISorbettoStrategy { // Address of the Sorbetto's strategy owner address public governance; // Pending to claim ownership address address public pendingGovernance; /// @inheritdoc ISorbettoStrategy uint32 public override twapDuration; /// @inheritdoc ISorbettoStrategy int24 public override maxTwapDeviation; /// @inheritdoc ISorbettoStrategy int24 public override tickRangeMultiplier; /// @inheritdoc ISorbettoStrategy uint24 public override protocolFee; /// @inheritdoc ISorbettoStrategy uint24 public override priceImpactPercentage; /** * @param _twapDuration TWAP duration in seconds for rebalance check * @param _maxTwapDeviation Max deviation from TWAP during rebalance * @param _tickRangeMultiplier Used to determine base order range * @param _protocolFee The protocol's fee in hundredths of a bip, i.e. 1e-6 * @param _priceImpactPercentage The price impact percentage during swap in hundredths of a bip, i.e. 1e-6 */ constructor( uint32 _twapDuration, int24 _maxTwapDeviation, int24 _tickRangeMultiplier, uint24 _protocolFee, uint24 _priceImpactPercentage ) { twapDuration = _twapDuration; maxTwapDeviation = _maxTwapDeviation; tickRangeMultiplier = _tickRangeMultiplier; protocolFee = _protocolFee; priceImpactPercentage = _priceImpactPercentage; governance = msg.sender; require(_maxTwapDeviation >= 0, "maxTwapDeviation"); require(_twapDuration > 0, "twapDuration"); require(_protocolFee < 1e6 && _protocolFee > 0, "PF"); require(_priceImpactPercentage < 1e6 && _priceImpactPercentage > 0, "PIP"); } modifier onlyGovernance { require(msg.sender == governance, "NOT ALLOWED"); _; } function setTwapDuration(uint32 _twapDuration) external onlyGovernance { require(_twapDuration > 0, "twapDuration"); twapDuration = _twapDuration; } function setMaxTwapDeviation(int24 _maxTwapDeviation) external onlyGovernance { require(_maxTwapDeviation > 0, "PF"); maxTwapDeviation = _maxTwapDeviation; } function setTickRange(int24 _tickRangeMultiplier) external onlyGovernance { tickRangeMultiplier = _tickRangeMultiplier; } function setProtocolFee(uint16 _protocolFee) external onlyGovernance { require(_protocolFee < 1e6 && _protocolFee > 0, "PF"); protocolFee = _protocolFee; } function setPriceImpact(uint16 _priceImpactPercentage) external onlyGovernance { require(_priceImpactPercentage < 1e6 && _priceImpactPercentage > 0, "PIP"); priceImpactPercentage = _priceImpactPercentage; } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "PG"); governance = msg.sender; } }
38,362