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
7
// return pid by address
mapping(address => uint256) public address2PID_;
mapping(address => uint256) public address2PID_;
15,509
31
// Set allowance for other address Allows `_spender` to spend no more than `_value` tokens on your behalf_spender The address authorized to spend _value the max amount they can spend /
function approve(address _spender, uint256 _value) public whenNotPaused
function approve(address _spender, uint256 _value) public whenNotPaused
65,485
28
// Checks if the pool is still open or not /
modifier isPoolOpen() { require(totalInvestors < size && now < (startDate + duration) && now >= startDate); _; }
modifier isPoolOpen() { require(totalInvestors < size && now < (startDate + duration) && now >= startDate); _; }
24,623
32
// MultiHolderVault This contract distribute ether to multiple address. /
contract MultiHolderVault is HolderBase, RefundVault { using SafeMath for uint256; function MultiHolderVault(address _wallet, uint256 _ratioCoeff) public HolderBase(_ratioCoeff) RefundVault(_wallet) {} function close() public onlyOwner { require(state == State.Active); require(initialized); super.distribute(); // distribute ether to holders super.close(); // transfer remaining ether to wallet } }
contract MultiHolderVault is HolderBase, RefundVault { using SafeMath for uint256; function MultiHolderVault(address _wallet, uint256 _ratioCoeff) public HolderBase(_ratioCoeff) RefundVault(_wallet) {} function close() public onlyOwner { require(state == State.Active); require(initialized); super.distribute(); // distribute ether to holders super.close(); // transfer remaining ether to wallet } }
55,981
195
// repay flash loan
IERC20(loanToken).safeTransfer(iToken, maxLiquidatable); return abi.encode( loanToken, uint256(_realLiquidatedLoanAmount - _liquidatedLoanAmount) );
IERC20(loanToken).safeTransfer(iToken, maxLiquidatable); return abi.encode( loanToken, uint256(_realLiquidatedLoanAmount - _liquidatedLoanAmount) );
45,417
260
// Virtual value of liquid assets in the poolreturn Virtual liquid value of pool assets /
function liquidValue() public view returns (uint256) { return currencyBalance().add(yTokenValue()); }
function liquidValue() public view returns (uint256) { return currencyBalance().add(yTokenValue()); }
22,096
100
// Update the land
lands[_landId].ownerAddress = msg.sender; lands[_landId].landForSale = false;
lands[_landId].ownerAddress = msg.sender; lands[_landId].landForSale = false;
15,813
19
// Distribute(mint) sale tokens. Executable by contract owner only./ Contract owner only. Cant withdraw more than _sale_tokens./ _receiverAddress - Address which recieves sale tokens
function distributeSale(address _receiverAddress) external onlyOwner { require(_sale_tokens > 0, "Cant distribute more than cap"); _transfer(address(this), _receiverAddress, _sale_tokens); _sale_tokens = 0; }
function distributeSale(address _receiverAddress) external onlyOwner { require(_sale_tokens > 0, "Cant distribute more than cap"); _transfer(address(this), _receiverAddress, _sale_tokens); _sale_tokens = 0; }
46,826
46
// A mapping from EtherDog IDs to the address that owns them. All EtherDogs have/some valid owner address, even gen0 EtherDogs are created with a non-zero owner.
mapping (uint256 => address) public EtherDogIndexToOwner;
mapping (uint256 => address) public EtherDogIndexToOwner;
20,762
63
// Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.The call is not executed if the target address is not a contract.from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the callreturn bool whether the call correctly returned the expected magic value /
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(),
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(),
1,589
75
// 32 is the length in bytes of hash, enforced by the type signature above
return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash) );
return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash) );
6,760
106
// Returns the data of an user on a distribution user Address of the user asset The address of the reference asset of the distributionreturn The new index /
function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; }
function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; }
70,265
25
// Strategic Growth Forum Implementation of ERC20 with added control for contract owner /
contract SGFC is ISGFC, ERC20, Pausable, AccessControl { // State Variables // mapping(address => bool) private _whitelist; // bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant ATTENDEE_ROLE = keccak256("ATTENDEE_ROLE"); address public immutable i_admin; // address public immutable i_poapContract; // event Clawback(address indexed account); constructor( string memory tokenName, string memory tokenSymbol, uint256 initialAmount, address admin ) ERC20(tokenName, tokenSymbol) { i_admin = admin; _grantRole(DEFAULT_ADMIN_ROLE, admin); // _grantRole(PAUSER_ROLE, msg.sender); // _grantRole(MINTER_ROLE, msg.sender); _mint(msg.sender, initialAmount); } // Modifiers // modifier onlyWhitelist(address _account) { // require(_whitelist[_account] == true, "Address is not whitelisted."); // _; // } // Pause function function pause() public onlyRole(OWNER_ROLE) { _pause(); } function unpause() public onlyRole(OWNER_ROLE) { _unpause(); } // 1. get current admin role for role // 2. check if msg.sender has admin role // 3. update admin role for role function setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 currentAdmin = getRoleAdmin(role); require( hasRole(currentAdmin, msg.sender), "Only the role administrator for this role can set a new admin" ); _setRoleAdmin(role, adminRole); } // function setContract(address contractAddress) // public // onlyRole(DEFAULT_ADMIN_ROLE) // { // i_poapContract = contractAddress; // } // function getWhitelist(address account) public view override returns (bool) { // return _whitelist[account]; // } /** * @notice Adds account to whitelist */ // function addToWhitelist(address account) public override onlyOwner { // _whitelist[account] = true; // emit Whitelisted(account); // } /** * @notice adds a list of accounts to the whitelist */ // function batchAddToWhitelist(address[] memory accounts) // public // override // onlyOwner // { // address[] memory addresses = accounts; // uint64 i; // uint256 length = accounts.length; // for (i = 0; i < length; i++) { // addToWhitelist(addresses[i]); // } // } /** * @param account the address to remove from the whitelist */ // function removeFromWhitelist(address account) public override onlyOwner { // _whitelist[account] = false; // } /** * @notice removes a list of accounts from the whitelist */ // function batchRemoveFromWhitelist(address[] memory accounts) // public // override // onlyOwner // { // address[] memory addresses = accounts; // uint64 i; // uint256 length = accounts.length; // for (i = 0; i < length; i++) { // removeFromWhitelist(addresses[i]); // } // } // function _beforeTokenTransfer( // address from, // address to, // uint256 amount // ) internal override whenNotPaused { // super._beforeTokenTransfer(from, to, amount); // } /** * @dev override of the standard implementation of the transfer function * @param to the account receiving tokens * @param amount the number of tokens to transfer * @notice only whitelisted addresses can receive tokens */ function transfer(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { require( hasRole(ATTENDEE_ROLE, to), "Address is not approved to transact SGFC" ); super.transfer(to, amount); } function transferFrom( address from, address to, uint256 amount ) public virtual override whenNotPaused returns (bool) { require( hasRole(ATTENDEE_ROLE, to), "Address is not approved to transact SGFC" ); super.transferFrom(from, to, amount); } /** * @dev mints tokens to user address * @param to the address that tokens are minted to * @param amount the number of tokens to mint * @notice increases the allowance of owner when called, enabling clawbacks of tokens if necessary */ function airdrop(address to, uint256 amount) external virtual override onlyRole(MINTER_ROLE) whenNotPaused { // require(hasRole(MINTER_ROLE, msg.sender)); // require( // msg.sender == i_poapContract, // "Only approved addresses can call the mint function" // ); _mint(to, amount); _approve(to, i_admin, amount); } /** * @param spender the address receiving permission to spend tokens * @param owner the owner of the tokens * @param addedValue the amount to increase the current allowance by */ // function increaseAllowance( // address spender, // address owner, // uint256 addedValue // ) public virtual onlyWhitelist(spender) returns (bool) { // _approve(owner, spender, allowance(owner, spender) + addedValue); // return true; // } /** * @param account the address to be removed from the whitelist and stripped of tokens * @notice clawbacks are enabled to maintain the restriction that only SGF attendees can transact the token */ function clawback(address account) public onlyRole(DEFAULT_ADMIN_ROLE) { uint256 accountBalance = balanceOf(account); transferFrom(account, i_admin, accountBalance); revokeRole(ATTENDEE_ROLE, account); emit Clawback(account); } /** * @notice destroys the contract and transfers all funds to the contract owner */ function destroy() public onlyRole(DEFAULT_ADMIN_ROLE) { selfdestruct(payable(i_admin)); } }
contract SGFC is ISGFC, ERC20, Pausable, AccessControl { // State Variables // mapping(address => bool) private _whitelist; // bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant ATTENDEE_ROLE = keccak256("ATTENDEE_ROLE"); address public immutable i_admin; // address public immutable i_poapContract; // event Clawback(address indexed account); constructor( string memory tokenName, string memory tokenSymbol, uint256 initialAmount, address admin ) ERC20(tokenName, tokenSymbol) { i_admin = admin; _grantRole(DEFAULT_ADMIN_ROLE, admin); // _grantRole(PAUSER_ROLE, msg.sender); // _grantRole(MINTER_ROLE, msg.sender); _mint(msg.sender, initialAmount); } // Modifiers // modifier onlyWhitelist(address _account) { // require(_whitelist[_account] == true, "Address is not whitelisted."); // _; // } // Pause function function pause() public onlyRole(OWNER_ROLE) { _pause(); } function unpause() public onlyRole(OWNER_ROLE) { _unpause(); } // 1. get current admin role for role // 2. check if msg.sender has admin role // 3. update admin role for role function setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 currentAdmin = getRoleAdmin(role); require( hasRole(currentAdmin, msg.sender), "Only the role administrator for this role can set a new admin" ); _setRoleAdmin(role, adminRole); } // function setContract(address contractAddress) // public // onlyRole(DEFAULT_ADMIN_ROLE) // { // i_poapContract = contractAddress; // } // function getWhitelist(address account) public view override returns (bool) { // return _whitelist[account]; // } /** * @notice Adds account to whitelist */ // function addToWhitelist(address account) public override onlyOwner { // _whitelist[account] = true; // emit Whitelisted(account); // } /** * @notice adds a list of accounts to the whitelist */ // function batchAddToWhitelist(address[] memory accounts) // public // override // onlyOwner // { // address[] memory addresses = accounts; // uint64 i; // uint256 length = accounts.length; // for (i = 0; i < length; i++) { // addToWhitelist(addresses[i]); // } // } /** * @param account the address to remove from the whitelist */ // function removeFromWhitelist(address account) public override onlyOwner { // _whitelist[account] = false; // } /** * @notice removes a list of accounts from the whitelist */ // function batchRemoveFromWhitelist(address[] memory accounts) // public // override // onlyOwner // { // address[] memory addresses = accounts; // uint64 i; // uint256 length = accounts.length; // for (i = 0; i < length; i++) { // removeFromWhitelist(addresses[i]); // } // } // function _beforeTokenTransfer( // address from, // address to, // uint256 amount // ) internal override whenNotPaused { // super._beforeTokenTransfer(from, to, amount); // } /** * @dev override of the standard implementation of the transfer function * @param to the account receiving tokens * @param amount the number of tokens to transfer * @notice only whitelisted addresses can receive tokens */ function transfer(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { require( hasRole(ATTENDEE_ROLE, to), "Address is not approved to transact SGFC" ); super.transfer(to, amount); } function transferFrom( address from, address to, uint256 amount ) public virtual override whenNotPaused returns (bool) { require( hasRole(ATTENDEE_ROLE, to), "Address is not approved to transact SGFC" ); super.transferFrom(from, to, amount); } /** * @dev mints tokens to user address * @param to the address that tokens are minted to * @param amount the number of tokens to mint * @notice increases the allowance of owner when called, enabling clawbacks of tokens if necessary */ function airdrop(address to, uint256 amount) external virtual override onlyRole(MINTER_ROLE) whenNotPaused { // require(hasRole(MINTER_ROLE, msg.sender)); // require( // msg.sender == i_poapContract, // "Only approved addresses can call the mint function" // ); _mint(to, amount); _approve(to, i_admin, amount); } /** * @param spender the address receiving permission to spend tokens * @param owner the owner of the tokens * @param addedValue the amount to increase the current allowance by */ // function increaseAllowance( // address spender, // address owner, // uint256 addedValue // ) public virtual onlyWhitelist(spender) returns (bool) { // _approve(owner, spender, allowance(owner, spender) + addedValue); // return true; // } /** * @param account the address to be removed from the whitelist and stripped of tokens * @notice clawbacks are enabled to maintain the restriction that only SGF attendees can transact the token */ function clawback(address account) public onlyRole(DEFAULT_ADMIN_ROLE) { uint256 accountBalance = balanceOf(account); transferFrom(account, i_admin, accountBalance); revokeRole(ATTENDEE_ROLE, account); emit Clawback(account); } /** * @notice destroys the contract and transfers all funds to the contract owner */ function destroy() public onlyRole(DEFAULT_ADMIN_ROLE) { selfdestruct(payable(i_admin)); } }
1,159
22
// Modifier to check if vester.
modifier onlyVester() { require( hasRole(VESTER_ROLE, _msgSender()), "AccessDenied : Only Vester Call This Function" ); _; }
modifier onlyVester() { require( hasRole(VESTER_ROLE, _msgSender()), "AccessDenied : Only Vester Call This Function" ); _; }
3,648
1
// It deadlocks your tokens and emit an event with amount and EOS public key. /
function teleport(string hivePublicKey) public { require(isValidKey(hivePublicKey), "not valid HIVE public key"); super.teleport(hivePublicKey); }
function teleport(string hivePublicKey) public { require(isValidKey(hivePublicKey), "not valid HIVE public key"); super.teleport(hivePublicKey); }
25,341
70
// Allows the owner to finalize the sale and allow tokens to be traded.
function finalize() external onlyOwner returns (bool) { require(!finalized); finalized = true; TokenFinalized(); return true; }
function finalize() external onlyOwner returns (bool) { require(!finalized); finalized = true; TokenFinalized(); return true; }
3,901
0
// for minters
mapping(address => bool) public _minters;
mapping(address => bool) public _minters;
43,270
70
// Require that a status code belongs to a particular category, otherwise `revert` with messagestatus Binary ERC-1066 status code category Required category nibble message Revert message /
function requireCategory(byte status, byte category, string memory message) public view
function requireCategory(byte status, byte category, string memory message) public view
10,708
7
// check the balance of caller/ return wei balance of the account
function vaultBalance() external view returns (uint256) { return vault[msg.sender]; }
function vaultBalance() external view returns (uint256) { return vault[msg.sender]; }
43,063
23
// EVENTS// DATA STRUCTURES/
struct Config { string placeholder; string base; uint64 supply; bool permanent; }
struct Config { string placeholder; string base; uint64 supply; bool permanent; }
23,293
90
// seriesId => NonGenSeries
mapping ( uint256 => NonGenSeries) public nonGenSeries; mapping ( uint256 => uint256[]) _allowedCurrencies; mapping ( uint256 => address) public bankAddress; mapping ( uint256 => uint256) public nonGenseriesRoyalty; mapping ( uint256 => uint256) public baseCurrency;
mapping ( uint256 => NonGenSeries) public nonGenSeries; mapping ( uint256 => uint256[]) _allowedCurrencies; mapping ( uint256 => address) public bankAddress; mapping ( uint256 => uint256) public nonGenseriesRoyalty; mapping ( uint256 => uint256) public baseCurrency;
39,214
151
// 221 -> Emeeji221.json
return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json"));
return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json"));
38,661
37
// crowdsale
uint256 public constant CROWDSALE_AMOUNT = 80 * MILLION_GML; // Should not include vested amount uint256 public constant START_DATE = 1505736000; // (epoch timestamp) uint256 public constant END_DATE = 1508500800; // TODO (epoch timestamp) uint256 public constant CROWDSALE_PRICE = 700; // 700 GML / ETH uint256 public constant VESTING_1_AMOUNT = 10 * MILLION_GML; // GIM reserve fund uint256 public constant VESTING_1_DATE = 1537272000; // TODO (epoch timestamp) uint256 public constant VESTING_2_AMOUNT = 30 * MILLION_GML; // Team uint256 public constant VESTING_2_DATE = 1568808000; // TODO (epoch timestamp) bool public vesting1Withdrawn = false; bool public vesting2Withdrawn = false;
uint256 public constant CROWDSALE_AMOUNT = 80 * MILLION_GML; // Should not include vested amount uint256 public constant START_DATE = 1505736000; // (epoch timestamp) uint256 public constant END_DATE = 1508500800; // TODO (epoch timestamp) uint256 public constant CROWDSALE_PRICE = 700; // 700 GML / ETH uint256 public constant VESTING_1_AMOUNT = 10 * MILLION_GML; // GIM reserve fund uint256 public constant VESTING_1_DATE = 1537272000; // TODO (epoch timestamp) uint256 public constant VESTING_2_AMOUNT = 30 * MILLION_GML; // Team uint256 public constant VESTING_2_DATE = 1568808000; // TODO (epoch timestamp) bool public vesting1Withdrawn = false; bool public vesting2Withdrawn = false;
23,391
144
// get getDepositDetails/
{ return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount, lockedToken[_id].unlockTime,lockedToken[_id].withdrawn); }
{ return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount, lockedToken[_id].unlockTime,lockedToken[_id].withdrawn); }
8,911
100
// Calculate EIP712 constants
DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,address verifyingContract)"), keccak256(bytes("ERC721o")), keccak256(bytes("1")), address(this) )); PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,address verifyingContract)"), keccak256(bytes("ERC721o")), keccak256(bytes("1")), address(this) )); PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
29,778
20
// ===== Run Migration =====
controller.setStrategy(params.want, params.afterStrategy); uint256 afterBalance = sett.balance(); uint256 afterPpfs = sett.getPricePerFullShare();
controller.setStrategy(params.want, params.afterStrategy); uint256 afterBalance = sett.balance(); uint256 afterPpfs = sett.getPricePerFullShare();
31,173
28
// ========== MUTATIVE FUNCTIONS ========== //Stops the controller. /
function pause() onlyPauser external { _pause(); }
function pause() onlyPauser external { _pause(); }
24,346
11
// если есть незачисленный airdrop на балансе, переводим на основной счет.
sumBalanceAndAirdrop(msg.sender); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true;
sumBalanceAndAirdrop(msg.sender); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true;
10,611
84
// investors count
uint public investorCount;
uint public investorCount;
16,994
5
// payout ether
uint256 payout = address(this).balance / div;
uint256 payout = address(this).balance / div;
35,228
33
// Fetch the candidate's details from the voters mapping
Voter memory candidateInfo = voters[registeredVoters[voterId - 1]]; partyCandidates[candidateIndex].voterId = voterId; partyCandidates[candidateIndex].fullName = candidateInfo.fullName; partyCandidates[candidateIndex].faceImageIpfsUrl = candidateInfo.faceImageIpfsUrl;
Voter memory candidateInfo = voters[registeredVoters[voterId - 1]]; partyCandidates[candidateIndex].voterId = voterId; partyCandidates[candidateIndex].fullName = candidateInfo.fullName; partyCandidates[candidateIndex].faceImageIpfsUrl = candidateInfo.faceImageIpfsUrl;
27,601
19
// Returns the current total borrows plus accrued interestreturn The total borrows with interest /
function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; }
function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; }
22,816
4
// Returns the data of an user on a distribution user Address of the user asset The address of the reference asset of the distributionreturn The new index /
function getUserAssetData(address user, address asset) external view returns (uint256);
function getUserAssetData(address user, address asset) external view returns (uint256);
5,955
139
// capture the contract's current ETH balance. this is so that we can capture exactly the amount of ETH that the swap creates, and not make the liquidity event include any ETH that has been manually sent to the contract
uint256 initialBalance = twa.balanceOf(address(this));
uint256 initialBalance = twa.balanceOf(address(this));
3,597
27
// Unlock account /
function unlockAccount(address _address) public onlyOwner{ _blacklist[_address] = false; }
function unlockAccount(address _address) public onlyOwner{ _blacklist[_address] = false; }
10,829
110
// decrease fee after selling /
function decreaseFee() private { _totalFee = _totalFee.sub(sellExtraFee); }
function decreaseFee() private { _totalFee = _totalFee.sub(sellExtraFee); }
13,605
6
// Require the function call went through EntryPoint or owner /
function _requireFromEntryPointOrOwner() internal view { if (msg.sender != address(entryPoint()) && msg.sender != owner()) { revert NotOwnerOrEntrypoint(); } }
function _requireFromEntryPointOrOwner() internal view { if (msg.sender != address(entryPoint()) && msg.sender != owner()) { revert NotOwnerOrEntrypoint(); } }
15,988
243
// indicates if transfer is enabled
bool private _transferEnabled = false;
bool private _transferEnabled = false;
20,904
7
// Changes a uint for a specific target indexNote: this function is only callable by the Governance contract. _target is the index of the uint to change _amount is the amount to change the given uint to /
function changeUint(bytes32 _target, uint256 _amount) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT], "Only the Governance contract can change the uint" ); uints[_target] = _amount; }
function changeUint(bytes32 _target, uint256 _amount) external { require( msg.sender == addresses[_GOVERNANCE_CONTRACT], "Only the Governance contract can change the uint" ); uints[_target] = _amount; }
29,246
208
// update discount factor for token./_token The address of token./_discount The discount factor. multipled by 1e18
function updateDiscount(address _token, uint256 _discount) external onlyGovernor { discount[_token] = _discount; emit UpdateDiscount(_token, _discount); }
function updateDiscount(address _token, uint256 _discount) external onlyGovernor { discount[_token] = _discount; emit UpdateDiscount(_token, _discount); }
24,893
363
// Digest describing the data the user signs according EIP 712. Needs to match what is passed to Metamask.
bytes32 public constant DELEGATION_HASH_EIP712 = keccak256(abi.encodePacked("address GenesisProtocolAddress","bytes32 ProposalId", "uint Vote","uint AmountToStake","uint Nonce"));
bytes32 public constant DELEGATION_HASH_EIP712 = keccak256(abi.encodePacked("address GenesisProtocolAddress","bytes32 ProposalId", "uint Vote","uint AmountToStake","uint Nonce"));
37,175
34
// Apply losses to current stKSM shares on this contract_losses user address for claiming/
function ditributeLosses(uint256 _losses) external onlyLido { totalVirtualXcKSMAmount -= _losses; emit LossesDistributed(_losses); }
function ditributeLosses(uint256 _losses) external onlyLido { totalVirtualXcKSMAmount -= _losses; emit LossesDistributed(_losses); }
43,269
56
// MintableToken ERC20Standard modified with mintable token creation. /
contract MintableToken is ERC20Standard, Ownable { /** * @dev Hardcap - maximum allowed amount of tokens to be minted */ uint104 public constant MINTING_HARDCAP = 1e30; /** * @dev Auto-generated function to check whether the minting has finished. * @return True if the minting has finished, or false. */ bool public mintingFinished = false; event Mint(address indexed _to, uint256 _amount); event MintFinished(); modifier canMint() { require(!mintingFinished, 'Uninished minting required.'); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. */ function mint(address _to, uint256 _amount) public onlyOwners canMint() { uint256 totalSupply = dataStorage.totalSupply(); totalSupply = totalSupply.add(_amount); require(totalSupply <= MINTING_HARDCAP, 'Total supply of token in circulation must be below hardcap.'); dataStorage.setTotalSupply(totalSupply); uint256 toBalance = dataStorage.balances(_to); toBalance = toBalance.add(_amount); dataStorage.setBalance(_to, toBalance); ledger.addTransaction(address(0), _to, _amount); emit Transfer(address(0), _to, _amount); emit Mint(_to, _amount); } /** * @dev Function to permanently stop minting new tokens. */ function finishMinting() public onlyOwners { mintingFinished = true; emit MintFinished(); } }
contract MintableToken is ERC20Standard, Ownable { /** * @dev Hardcap - maximum allowed amount of tokens to be minted */ uint104 public constant MINTING_HARDCAP = 1e30; /** * @dev Auto-generated function to check whether the minting has finished. * @return True if the minting has finished, or false. */ bool public mintingFinished = false; event Mint(address indexed _to, uint256 _amount); event MintFinished(); modifier canMint() { require(!mintingFinished, 'Uninished minting required.'); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. */ function mint(address _to, uint256 _amount) public onlyOwners canMint() { uint256 totalSupply = dataStorage.totalSupply(); totalSupply = totalSupply.add(_amount); require(totalSupply <= MINTING_HARDCAP, 'Total supply of token in circulation must be below hardcap.'); dataStorage.setTotalSupply(totalSupply); uint256 toBalance = dataStorage.balances(_to); toBalance = toBalance.add(_amount); dataStorage.setBalance(_to, toBalance); ledger.addTransaction(address(0), _to, _amount); emit Transfer(address(0), _to, _amount); emit Mint(_to, _amount); } /** * @dev Function to permanently stop minting new tokens. */ function finishMinting() public onlyOwners { mintingFinished = true; emit MintFinished(); } }
6,630
0
// Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length./Credit to Open Zeppelin under MIT license https:github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.solL55
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = ALPHABET[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); }
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = ALPHABET[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); }
1,586
52
// create a long term order to swap from token1/ amount1In total amount of token1 to swap/ numberOfTimeIntervals number of time intervals over which to execute long term order
function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external lock isNotPaused execVirtualOrders returns (uint256 orderId) { uint amount1 = transferAmount1In(amount1In); twammReserve1 += uint112(amount1); require(uint256(reserve1) + twammReserve1 <= type(uint112).max); // OVERFLOW orderId = longTermOrders.longTermSwapFrom1To0(amount1, numberOfTimeIntervals); orderIDsForUser[msg.sender].push(orderId); emit LongTermSwap1To0(msg.sender, orderId, amount1, numberOfTimeIntervals); }
function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external lock isNotPaused execVirtualOrders returns (uint256 orderId) { uint amount1 = transferAmount1In(amount1In); twammReserve1 += uint112(amount1); require(uint256(reserve1) + twammReserve1 <= type(uint112).max); // OVERFLOW orderId = longTermOrders.longTermSwapFrom1To0(amount1, numberOfTimeIntervals); orderIDsForUser[msg.sender].push(orderId); emit LongTermSwap1To0(msg.sender, orderId, amount1, numberOfTimeIntervals); }
15,182
138
// We are in the first quarter to update, we add the proportional pending part
newCheckpoint.quarterPower = newCheckpoint.quarterPower.add( data[4].mul(slotEnding.sub(data[1])).div(data[2]) );
newCheckpoint.quarterPower = newCheckpoint.quarterPower.add( data[4].mul(slotEnding.sub(data[1])).div(data[2]) );
31,752
26
// Checks availability of `_name` and returns bool accordingly. /
function checkNameAvailability(string memory _name) public view override returns (bool)
function checkNameAvailability(string memory _name) public view override returns (bool)
34,944
31
// This function probably deserves some explanation.The DNSSEC keytag function is a checksum that relies on summing up individual bytesfrom the input string, with some mild bitshifting. Here's a Naive solidity implementation: function computeKeytag(bytes memory data) internal pure returns (uint16) {uint ac;for (uint i = 0; i < data.length; i++) {ac += i & 1 == 0 ? uint16(data.readUint8(i)) << 8 : data.readUint8(i);}return uint16(ac + (ac >> 16));} The EVM, with its 256 bit words, is exceedingly inefficient at doing byte-by-byte operations;the code above, on reasonable length inputs, consumes over 100k gas. But we can make the EVM'slarge words work in
unchecked { require(data.length <= 8192, "Long keys not permitted"); uint256 ac1; uint256 ac2; for (uint256 i = 0; i < data.length + 31; i += 32) { uint256 word; assembly { word := mload(add(add(data, 32), i)) }
unchecked { require(data.length <= 8192, "Long keys not permitted"); uint256 ac1; uint256 ac2; for (uint256 i = 0; i < data.length + 31; i += 32) { uint256 word; assembly { word := mload(add(add(data, 32), i)) }
7,078
199
// Throws if called by any account other than the feeToSetter.
modifier onlyFTS() { require(msg.sender == feeToSetter); // FORBIDDEN _; }
modifier onlyFTS() { require(msg.sender == feeToSetter); // FORBIDDEN _; }
44,782
5
// https:docs.chain.link/docs/get-the-latest-price/getting-a-different-price-denomination
function getDerivedPrice() internal view returns (int256) { (, int256 basePrice, , , ) = BASE.latestRoundData(); uint8 baseDecimals = BASE.decimals(); basePrice = scalePrice(basePrice, baseDecimals, DECIMALS); (, int256 quotePrice, , , ) = QUOTE.latestRoundData(); uint8 quoteDecimals = QUOTE.decimals(); quotePrice = scalePrice(quotePrice, quoteDecimals, DECIMALS); return (basePrice * int256(10**uint256(DECIMALS))) / quotePrice; }
function getDerivedPrice() internal view returns (int256) { (, int256 basePrice, , , ) = BASE.latestRoundData(); uint8 baseDecimals = BASE.decimals(); basePrice = scalePrice(basePrice, baseDecimals, DECIMALS); (, int256 quotePrice, , , ) = QUOTE.latestRoundData(); uint8 quoteDecimals = QUOTE.decimals(); quotePrice = scalePrice(quotePrice, quoteDecimals, DECIMALS); return (basePrice * int256(10**uint256(DECIMALS))) / quotePrice; }
42,902
4,902
// 2453
entry "burgeoningly" : ENG_ADVERB
entry "burgeoningly" : ENG_ADVERB
23,289
57
// Set redemption fee minimum_redemptionFeeMinimum Redemption fee minimum /
function setRedemptionFeeMinimum(uint256 _redemptionFeeMinimum) external override onlyOwner { uint256 oldValue = redemptionFeeMinimum; redemptionFeeMinimum = _redemptionFeeMinimum; emit RedemptionFeeMinimumUpdated( oldValue, redemptionFeeMinimum ); }
function setRedemptionFeeMinimum(uint256 _redemptionFeeMinimum) external override onlyOwner { uint256 oldValue = redemptionFeeMinimum; redemptionFeeMinimum = _redemptionFeeMinimum; emit RedemptionFeeMinimumUpdated( oldValue, redemptionFeeMinimum ); }
29,745
156
// Authorized caller transfers tokens from one account to another/self Stored token from token contract/_from Address to send tokens from/_to Address to send tokens to/_value Number of tokens to send/ return True if completed
function transferFrom(TokenStorage storage self, address _from, address _to, uint256 _value) public returns (bool)
function transferFrom(TokenStorage storage self, address _from, address _to, uint256 _value) public returns (bool)
13,415
25
// updateScore(win1,win2,w1Score,w2Score,player1Address,player2Address);
if(resultScores.length == 0){ scoreArr memory wizard1Score = scoreArr(address(0),0,0,0,0,0,0,0,0,0); wizard1Score.plrAddress = wizardAdr1; wizard1Score.totalScore = wizard1RoundScore; wizard1Score.plrStatus = 1; wizard1Score.noOfWins = wizard1RoundWin; wizard1Score.noOfLoss = wizard1RoundLoss; wizard1Score.noOftie = wizard1RoundTie; wizard1Score.elementalWin = wizard1ElementalWin; wizard1Score.elementalLoss = wizard1ElementalLoss;
if(resultScores.length == 0){ scoreArr memory wizard1Score = scoreArr(address(0),0,0,0,0,0,0,0,0,0); wizard1Score.plrAddress = wizardAdr1; wizard1Score.totalScore = wizard1RoundScore; wizard1Score.plrStatus = 1; wizard1Score.noOfWins = wizard1RoundWin; wizard1Score.noOfLoss = wizard1RoundLoss; wizard1Score.noOftie = wizard1RoundTie; wizard1Score.elementalWin = wizard1ElementalWin; wizard1Score.elementalLoss = wizard1ElementalLoss;
47,477
202
// Fallback to be able to receive ETH payments (just in case!)
receive() external payable {} function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return LibAppStorage.getTokenUri(tokenId); }
receive() external payable {} function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return LibAppStorage.getTokenUri(tokenId); }
70,145
21
// Internal function to set the status of an account for a given termaccount Address of the account to set the status for termIndex Term index for which to update status for statusNew status of the account /
function _setAccountStatus( address account, uint256 termIndex, bool status
function _setAccountStatus( address account, uint256 termIndex, bool status
36,000
120
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount);
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount);
430
26
// Pausable functionality adapted from OpenZeppelin / /Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused(){ require(!paused); _; }
modifier whenNotPaused(){ require(!paused); _; }
78,786
57
// Wipes the balance of a frozen address, burning the tokensand setting the approval to zero. _addr The new frozen address to wipe. /
function wipeFrozenAddress(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address is not frozen"); uint256 _balance = balances[_addr]; balances[_addr] = 0; totalSupply_ = totalSupply_.sub(_balance); emit FrozenAddressWiped(_addr); emit SupplyDecreased(_addr, _balance); emit Transfer(_addr, address(0), _balance); }
function wipeFrozenAddress(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address is not frozen"); uint256 _balance = balances[_addr]; balances[_addr] = 0; totalSupply_ = totalSupply_.sub(_balance); emit FrozenAddressWiped(_addr); emit SupplyDecreased(_addr, _balance); emit Transfer(_addr, address(0), _balance); }
17,060
459
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange
63,154
32
// function to keep track of the total token allocation
function changeTotalSupply(uint256 _amount) onlyCrowdFundAddress { totalAllocatedTokens = totalAllocatedTokens.add(_amount); tokensAllocatedToCrowdFund = tokensAllocatedToCrowdFund.sub(_amount); }
function changeTotalSupply(uint256 _amount) onlyCrowdFundAddress { totalAllocatedTokens = totalAllocatedTokens.add(_amount); tokensAllocatedToCrowdFund = tokensAllocatedToCrowdFund.sub(_amount); }
46,113
412
// Emitted when liquidity is minted for a given position/sender The address that minted the liquidity/owner The owner of the position and recipient of any minted liquidity/tickLower The lower tick of the position/tickUpper The upper tick of the position/amount The amount of liquidity minted to the position range/amount0 How much token0 was required for the minted liquidity/amount1 How much token1 was required for the minted liquidity
event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 );
event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 );
39,941
0
// using SafeERC20 for IERC20;
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
8,703
67
// Fetch the complete provenance entry attributes _provId refers to the provenance identifierreturn did return relatedDid return agentIdreturn activityId return agentInvolvedId return methodreturn createdBy return blockNumberUpdated return signature/
function getProvenanceEntry( bytes32 _provId ) public view returns ( bytes32 did, bytes32 relatedDid, address agentId,
function getProvenanceEntry( bytes32 _provId ) public view returns ( bytes32 did, bytes32 relatedDid, address agentId,
11,359
37
// uint d =TWAPWithZeros - getIV(_token); uint s = d.mul(_totalSupply); uint z = s.mul(icv);
amountToSellForTheNext8Hrs=9; //z.div(1e18);
amountToSellForTheNext8Hrs=9; //z.div(1e18);
9,819
110
// Returns the number of teams in a particular contest/_contestId ID of contest we are inquiring about
function getContestTeamCount(uint32 _contestId) public view returns (uint32 count) { require((_contestId > 0) && (_contestId < contests.length)); Contest storage c = contests[_contestId]; count = uint32(c.teamIds.length); }
function getContestTeamCount(uint32 _contestId) public view returns (uint32 count) { require((_contestId > 0) && (_contestId < contests.length)); Contest storage c = contests[_contestId]; count = uint32(c.teamIds.length); }
48,499
301
// Caller must own the matron and sire
require(_owns(msg.sender, _matronId)); require(_owns(msg.sender, _sireId));
require(_owns(msg.sender, _matronId)); require(_owns(msg.sender, _sireId));
49,282
166
// This is pure profit, figure out allocation Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
if(_executor != address(0)){
24,948
7
// copy data
for(i = 0; i < _values.length; ++i) { bytes memory _val = _values[i]; uint _valPtr; assembly { _valPtr := add(_val, 0x20) }
for(i = 0; i < _values.length; ++i) { bytes memory _val = _values[i]; uint _valPtr; assembly { _valPtr := add(_val, 0x20) }
29,694
3
// Withdraw the sent _amount from contract._amount Amount of funds to withdraw from contract./
function withdraw(uint256 _amount) public { address msgSender = msg.sender; require(_deposits[msgSender] >= _amount, "Withdraw: user does not have enough funds"); if(_amount > 0) { token.transfer(msgSender, _amount); _deposits[msgSender] = _deposits[msgSender].sub(_amount); emit Withdrawn(msg.sender, _amount); } }
function withdraw(uint256 _amount) public { address msgSender = msg.sender; require(_deposits[msgSender] >= _amount, "Withdraw: user does not have enough funds"); if(_amount > 0) { token.transfer(msgSender, _amount); _deposits[msgSender] = _deposits[msgSender].sub(_amount); emit Withdrawn(msg.sender, _amount); } }
75,777
22
// Returns the address of the ERC20 token managed by the vesting contract./
function getToken() external view
function getToken() external view
11,801
1
// Track variability of cash balance when ETH transfering in.
modifier tracksValue() { openCash = msg.value; _; openCash = 0; }
modifier tracksValue() { openCash = msg.value; _; openCash = 0; }
80,058
61
// Update the claimer's next valid timestamp to mint. If next mint timestamp overflows, cap it to max uint256.
uint256 timestampIndex = _claimConditionIndex + claimConditions[_tokenId].timstampLimitIndex; claimConditions[_tokenId].timestampOfLastClaim[_msgSender()][timestampIndex] = block.timestamp; _mint(_msgSender(), _tokenId, _quantityBeingClaimed, "");
uint256 timestampIndex = _claimConditionIndex + claimConditions[_tokenId].timstampLimitIndex; claimConditions[_tokenId].timestampOfLastClaim[_msgSender()][timestampIndex] = block.timestamp; _mint(_msgSender(), _tokenId, _quantityBeingClaimed, "");
19,169
20
// get bounty for the people./
function getBounty() public payable { require(bounty[msg.sender] != true); // 1 address = 1 token require(balances[this] != 0); bounty[msg.sender] = true; withdrawBounty(msg.sender, 1 * 10 ** uint(decimals)); }
function getBounty() public payable { require(bounty[msg.sender] != true); // 1 address = 1 token require(balances[this] != 0); bounty[msg.sender] = true; withdrawBounty(msg.sender, 1 * 10 ** uint(decimals)); }
12,560
35
// This interface should be implemented by all exchanges which needs to integrate with the paraswap protocol/
interface IExchange { /** * @dev The function which performs the swap on an exchange. * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Amount of source tokens to be swapped * @param toAmount Minimum destination token amount expected out of this swap * @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap * @param payload Any exchange specific data which is required can be passed in this argument in encoded format which * will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism */ function swap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload) external payable returns (uint256); /** * @dev The function which performs the swap on an exchange. * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Max Amount of source tokens to be swapped * @param toAmount Destination token amount expected out of this swap * @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap * @param payload Any exchange specific data which is required can be passed in this argument in encoded format which * will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism */ function buy( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload) external payable returns (uint256); /** * @dev This function is used to perform onChainSwap. It build all the parameters onchain. Basically the information * encoded in payload param of swap will calculated in this case * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Amount of source tokens to be swapped * @param toAmount Minimum destination token amount expected out of this swap */ function onChainSwap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount ) external payable returns (uint256); }
interface IExchange { /** * @dev The function which performs the swap on an exchange. * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Amount of source tokens to be swapped * @param toAmount Minimum destination token amount expected out of this swap * @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap * @param payload Any exchange specific data which is required can be passed in this argument in encoded format which * will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism */ function swap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload) external payable returns (uint256); /** * @dev The function which performs the swap on an exchange. * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Max Amount of source tokens to be swapped * @param toAmount Destination token amount expected out of this swap * @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap * @param payload Any exchange specific data which is required can be passed in this argument in encoded format which * will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism */ function buy( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload) external payable returns (uint256); /** * @dev This function is used to perform onChainSwap. It build all the parameters onchain. Basically the information * encoded in payload param of swap will calculated in this case * Exchange needs to implement this method in order to support swapping of tokens through it * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Amount of source tokens to be swapped * @param toAmount Minimum destination token amount expected out of this swap */ function onChainSwap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount ) external payable returns (uint256); }
27,853
120
// set status
status = BuyoutStatus.ENDED;
status = BuyoutStatus.ENDED;
16,387
1
// using MerkleProof Library to verify Merkle proofs
using MerkleProof for bytes32[];
using MerkleProof for bytes32[];
3,844
35
// Freezes all the transfers /
function freezeTransfers() external;
function freezeTransfers() external;
3,339
704
// Temporarily grant the deployer the turbo admin role for setup
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, true); pool._setPendingAdmin(address(admin)); admin._acceptAdmin();
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, true); pool._setPendingAdmin(address(admin)); admin._acceptAdmin();
30,546
9
// Base Tip Dollar Amount
uint256 baseDollars = 1; AggregatorV3Interface internal priceFeedUsd;
uint256 baseDollars = 1; AggregatorV3Interface internal priceFeedUsd;
886
5
// mapping of proxy address to deployer address
mapping(address => address) public deployer;
mapping(address => address) public deployer;
2,551
4
// now call Run of ScriptIt
Run( 123, "json:https://api.kraken.com/0/public/Ticker?pair=ETHUSD", // here comes the url of Kraken "result.XETHZUSD.a[0]", // here comes the json query "", // no npm modules required 1, // 1 slice = 10 seconds is required to perform the query 100000, // use 100k gas units max for the return of the query Result DEFAULT_GAS_PRICE // use the default gas price as defined in usingCaptainJS );
Run( 123, "json:https://api.kraken.com/0/public/Ticker?pair=ETHUSD", // here comes the url of Kraken "result.XETHZUSD.a[0]", // here comes the json query "", // no npm modules required 1, // 1 slice = 10 seconds is required to perform the query 100000, // use 100k gas units max for the return of the query Result DEFAULT_GAS_PRICE // use the default gas price as defined in usingCaptainJS );
8,589
2
// secretHash = _secret;
emit success();
emit success();
16,738
9
// Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, Emits an {ApprovalForAll} event. Requirements: - `operator` cannot be the caller. /
function setApprovalForAll(address operator, bool approved) external;
function setApprovalForAll(address operator, bool approved) external;
2,927
19
// Change coldAddress to newAddress. newAddress the new address for coldAddress /
function changeColdAddress(address payable newAddress) external onlyExchangeDepositor onlyAlive onlyAdmin
function changeColdAddress(address payable newAddress) external onlyExchangeDepositor onlyAlive onlyAdmin
8,873
38
// Recover address used to sign an ecrypted msg. message.return Address of signer. /
function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); }
function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); }
37,082
88
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
bytes32 private constant DOMAIN_TYPE_SIGNATURE_HASH = bytes32(0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f);
bytes32 private constant DOMAIN_TYPE_SIGNATURE_HASH = bytes32(0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f);
24,083
50
// restricted token
DependLike_3(seniorToken).depend("memberlist", seniorMemberlist); DependLike_3(juniorToken).depend("memberlist", juniorMemberlist);
DependLike_3(seniorToken).depend("memberlist", seniorMemberlist); DependLike_3(juniorToken).depend("memberlist", juniorMemberlist);
59,657
48
// Get the list of all freelancer's Gigs
function getAllFreelancerGigs(address fl) public view returns (Gig[] memory)
function getAllFreelancerGigs(address fl) public view returns (Gig[] memory)
16,128
405
// royalties ERC2981 in bps
uint16 public royalties; // 2 address public allowancesRef; // 20
uint16 public royalties; // 2 address public allowancesRef; // 20
50,706
41
// Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word. /
function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_16; }
function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_16; }
43,487
75
// MultiSig dYdX Multi-Signature Wallet.Allows multiple parties to agree on transactions before execution.Adapted from Stefan George's MultiSigWallet contract. Logic Changes: - Removed the fallback function - Ensure newOwner is notNull Syntax Changes: - Update Solidity syntax for 0.5.X: use `emit` keyword (events), use `view` keyword (functions) - Add braces to all `if` and `for` statements - Remove named return variables - Add space before and after comparison operators - Add ADDRESS_ZERO as a constant - uint => uint256 - external_call => externalCall /
contract MultiSig is MultiSigLibEIP712 { using LibBytes for bytes; // ============ Events ============ event Deposit(address indexed depositer, uint256 amount); event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); // ============ Constants ============ uint256 constant public MAX_OWNER_COUNT = 50; address constant ADDRESS_ZERO = address(0x0); // ============ Storage ============ mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint256 public required; uint256 public transactionCount; // ============ Structs ============ struct Transaction { address destination; uint256 value; bytes data; bool executed; } // ============ Modifiers ============ modifier onlyWallet() { /* solium-disable-next-line error-reason */ require(msg.sender == address(this)); _; } modifier ownerDoesNotExist( address owner ) { /* solium-disable-next-line error-reason */ require(!isOwner[owner]); _; } modifier ownerExists( address owner ) { /* solium-disable-next-line error-reason */ require(isOwner[owner]); _; } modifier transactionExists( uint256 transactionId ) { /* solium-disable-next-line error-reason */ require(transactions[transactionId].destination != ADDRESS_ZERO); _; } modifier confirmed( uint256 transactionId, address owner ) { /* solium-disable-next-line error-reason */ require(confirmations[transactionId][owner]); _; } modifier notConfirmed( uint256 transactionId, address owner ) { /* solium-disable-next-line error-reason */ require(!confirmations[transactionId][owner]); _; } modifier notExecuted( uint256 transactionId ) { /* solium-disable-next-line error-reason */ require(!transactions[transactionId].executed); _; } modifier notNull( address _address ) { /* solium-disable-next-line error-reason */ require(_address != ADDRESS_ZERO); _; } modifier validRequirement( uint256 ownerCount, uint256 _required ) { /* solium-disable-next-line error-reason */ require( ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0 ); _; } // ========= Fallback function ========== receive() external payable { emit Deposit(msg.sender, msg.value); } // ============ Constructor ============ /** * Contract constructor sets initial owners and required number of confirmations. * * @param _owners List of initial owners. * @param _required Number of required confirmations. */ constructor( address[] memory _owners, uint256 _required ) public validRequirement(_owners.length, _required) MultiSigLibEIP712() { for (uint256 i = 0; i < _owners.length; i++) { /* solium-disable-next-line error-reason */ require(!isOwner[_owners[i]] && _owners[i] != ADDRESS_ZERO); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } // ============ Wallet-Only Functions ============ /** * Allows to add a new owner. Transaction has to be sent by wallet. * * @param owner Address of new owner. */ function addOwner( address owner ) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /** * Allows to remove an owner. Transaction has to be sent by wallet. * * @param owner Address of owner. */ function removeOwner( address owner ) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } delete owners[owners.length - 1]; if (required > owners.length) { changeRequirement(owners.length); } emit OwnerRemoval(owner); } /** * Allows to replace an owner with a new owner. Transaction has to be sent by wallet. * * @param owner Address of owner to be replaced. * @param newOwner Address of new owner. */ function replaceOwner( address owner, address newOwner ) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) notNull(newOwner) { for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /** * Allows to change the number of required confirmations. Transaction has to be sent by wallet. * * @param _required Number of required confirmations. */ function changeRequirement( uint256 _required ) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } // ============ Owner Functions ============ /** * Allows an owner to submit and confirm a transaction. * * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Transaction ID. */ function submitTransaction( address destination, uint256 value, bytes memory data ) public returns (uint256) { uint256 transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); return transactionId; } /** * Allows an owner to submit and confirm a transaction via meta transaction. * * @param signer Signer of the meta transaction. * @param transactionId Transaction ID of this transaction. * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @param sig Signature. * @return Transaction ID. */ function submitTransaction( address signer, uint256 transactionId, address destination, uint256 value, bytes memory data, bytes memory sig ) public ownerExists(signer) returns (uint256) { // SUBMIT_TRANSACTION_TYPE_HASH = keccak256("submitTransaction(uint256 transactionId,address destination,uint256 value,bytes data)"); bytes32 EIP712SignDigest = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0x01), EIP712_DOMAIN_SEPARATOR, keccak256( abi.encode( SUBMIT_TRANSACTION_TYPE_HASH, transactionId, destination, value, data ) ) ) ); validateSignature(signer, EIP712SignDigest, sig); uint256 _transactionId = addTransaction(destination, value, data); require(transactionId == _transactionId); confirmTransactionBySigner(signer, transactionId); return transactionId; } // confirm transaction on behalf of signer, not msg.sender function confirmTransactionBySigner( address signer, uint256 transactionId ) internal transactionExists(transactionId) notConfirmed(transactionId, signer) { // Confirm confirmations[transactionId][signer] = true; emit Confirmation(signer, transactionId); // Execute executeTransactionBySigner(signer, transactionId); } // execute transaction on behalf of signer, not msg.sender function executeTransactionBySigner( address signer, uint256 transactionId ) internal notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (externalCall( txn.destination, txn.value, txn.data.length, txn.data) ) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); txn.executed = false; } } } /** * Allows an owner to confirm a transaction. * * @param transactionId Transaction ID. */ function confirmTransaction( uint256 transactionId ) public virtual ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /** * Allows an owner to confirm a transaction via meta transaction. * * @param signer Signer of the meta transaction. * @param transactionId Transaction ID. * @param sig Signature. */ function confirmTransaction( address signer, uint256 transactionId, bytes memory sig ) public virtual ownerExists(signer) transactionExists(transactionId) notConfirmed(transactionId, signer) { // CONFIRM_TRANSACTION_TYPE_HASH = keccak256("confirmTransaction(uint256 transactionId)"); bytes32 EIP712SignDigest = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0x01), EIP712_DOMAIN_SEPARATOR, keccak256( abi.encode( CONFIRM_TRANSACTION_TYPE_HASH, transactionId ) ) ) ); validateSignature(signer, EIP712SignDigest, sig); confirmations[transactionId][signer] = true; emit Confirmation(signer, transactionId); executeTransactionBySigner(signer, transactionId); } /** * Allows an owner to revoke a confirmation for a transaction. * * @param transactionId Transaction ID. */ function revokeConfirmation( uint256 transactionId ) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /** * Allows an owner to execute a confirmed transaction. * * @param transactionId Transaction ID. */ function executeTransaction( uint256 transactionId ) public virtual ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (externalCall( txn.destination, txn.value, txn.data.length, txn.data) ) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); txn.executed = false; } } } // ============ Getter Functions ============ /** * Returns the confirmation status of a transaction. * * @param transactionId Transaction ID. * @return Confirmation status. */ function isConfirmed( uint256 transactionId ) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } if (count == required) { return true; } } } /** * Returns number of confirmations of a transaction. * * @param transactionId Transaction ID. * @return Number of confirmations. */ function getConfirmationCount( uint256 transactionId ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } } return count; } /** * Returns total number of transactions after filers are applied. * * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Total number of transactions after filters are applied. */ function getTransactionCount( bool pending, bool executed ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < transactionCount; i++) { if ( pending && !transactions[i].executed || executed && transactions[i].executed ) { count += 1; } } return count; } /** * Returns array of owners. * * @return Array of owner addresses. */ function getOwners() public view returns (address[] memory) { return owners; } /** * Returns array with owner addresses, which confirmed transaction. * * @param transactionId Transaction ID. * @return Array of owner addresses. */ function getConfirmations( uint256 transactionId ) public view returns (address[] memory) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } address[] memory _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } return _confirmations; } /** * Returns list of transaction IDs in defined range. * * @param from Index start position of transaction array. * @param to Index end position of transaction array. * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Array of transaction IDs. */ function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) { if ( pending && !transactions[i].executed || executed && transactions[i].executed ) { transactionIdsTemp[count] = i; count += 1; } } uint256[] memory _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } return _transactionIds; } // ============ Helper Functions ============ function validateSignature( address signer, bytes32 digest, bytes memory sig ) internal { require(sig.length == 65); uint8 v = uint8(sig[64]); bytes32 r = sig.readBytes32(0); bytes32 s = sig.readBytes32(32); address recovered = ecrecover(digest, v, r, s); require(signer == recovered); } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function externalCall( address destination, uint256 value, uint256 dataLength, bytes memory data ) internal returns (bool) { bool result; /* solium-disable-next-line security/no-inline-assembly */ assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas(), 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /** * Adds a new transaction to the transaction mapping, if transaction does not exist yet. * * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Transaction ID. */ function addTransaction( address destination, uint256 value, bytes memory data ) internal notNull(destination) returns (uint256) { uint256 transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); return transactionId; } }
contract MultiSig is MultiSigLibEIP712 { using LibBytes for bytes; // ============ Events ============ event Deposit(address indexed depositer, uint256 amount); event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); // ============ Constants ============ uint256 constant public MAX_OWNER_COUNT = 50; address constant ADDRESS_ZERO = address(0x0); // ============ Storage ============ mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint256 public required; uint256 public transactionCount; // ============ Structs ============ struct Transaction { address destination; uint256 value; bytes data; bool executed; } // ============ Modifiers ============ modifier onlyWallet() { /* solium-disable-next-line error-reason */ require(msg.sender == address(this)); _; } modifier ownerDoesNotExist( address owner ) { /* solium-disable-next-line error-reason */ require(!isOwner[owner]); _; } modifier ownerExists( address owner ) { /* solium-disable-next-line error-reason */ require(isOwner[owner]); _; } modifier transactionExists( uint256 transactionId ) { /* solium-disable-next-line error-reason */ require(transactions[transactionId].destination != ADDRESS_ZERO); _; } modifier confirmed( uint256 transactionId, address owner ) { /* solium-disable-next-line error-reason */ require(confirmations[transactionId][owner]); _; } modifier notConfirmed( uint256 transactionId, address owner ) { /* solium-disable-next-line error-reason */ require(!confirmations[transactionId][owner]); _; } modifier notExecuted( uint256 transactionId ) { /* solium-disable-next-line error-reason */ require(!transactions[transactionId].executed); _; } modifier notNull( address _address ) { /* solium-disable-next-line error-reason */ require(_address != ADDRESS_ZERO); _; } modifier validRequirement( uint256 ownerCount, uint256 _required ) { /* solium-disable-next-line error-reason */ require( ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0 ); _; } // ========= Fallback function ========== receive() external payable { emit Deposit(msg.sender, msg.value); } // ============ Constructor ============ /** * Contract constructor sets initial owners and required number of confirmations. * * @param _owners List of initial owners. * @param _required Number of required confirmations. */ constructor( address[] memory _owners, uint256 _required ) public validRequirement(_owners.length, _required) MultiSigLibEIP712() { for (uint256 i = 0; i < _owners.length; i++) { /* solium-disable-next-line error-reason */ require(!isOwner[_owners[i]] && _owners[i] != ADDRESS_ZERO); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } // ============ Wallet-Only Functions ============ /** * Allows to add a new owner. Transaction has to be sent by wallet. * * @param owner Address of new owner. */ function addOwner( address owner ) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /** * Allows to remove an owner. Transaction has to be sent by wallet. * * @param owner Address of owner. */ function removeOwner( address owner ) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } delete owners[owners.length - 1]; if (required > owners.length) { changeRequirement(owners.length); } emit OwnerRemoval(owner); } /** * Allows to replace an owner with a new owner. Transaction has to be sent by wallet. * * @param owner Address of owner to be replaced. * @param newOwner Address of new owner. */ function replaceOwner( address owner, address newOwner ) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) notNull(newOwner) { for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /** * Allows to change the number of required confirmations. Transaction has to be sent by wallet. * * @param _required Number of required confirmations. */ function changeRequirement( uint256 _required ) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } // ============ Owner Functions ============ /** * Allows an owner to submit and confirm a transaction. * * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Transaction ID. */ function submitTransaction( address destination, uint256 value, bytes memory data ) public returns (uint256) { uint256 transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); return transactionId; } /** * Allows an owner to submit and confirm a transaction via meta transaction. * * @param signer Signer of the meta transaction. * @param transactionId Transaction ID of this transaction. * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @param sig Signature. * @return Transaction ID. */ function submitTransaction( address signer, uint256 transactionId, address destination, uint256 value, bytes memory data, bytes memory sig ) public ownerExists(signer) returns (uint256) { // SUBMIT_TRANSACTION_TYPE_HASH = keccak256("submitTransaction(uint256 transactionId,address destination,uint256 value,bytes data)"); bytes32 EIP712SignDigest = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0x01), EIP712_DOMAIN_SEPARATOR, keccak256( abi.encode( SUBMIT_TRANSACTION_TYPE_HASH, transactionId, destination, value, data ) ) ) ); validateSignature(signer, EIP712SignDigest, sig); uint256 _transactionId = addTransaction(destination, value, data); require(transactionId == _transactionId); confirmTransactionBySigner(signer, transactionId); return transactionId; } // confirm transaction on behalf of signer, not msg.sender function confirmTransactionBySigner( address signer, uint256 transactionId ) internal transactionExists(transactionId) notConfirmed(transactionId, signer) { // Confirm confirmations[transactionId][signer] = true; emit Confirmation(signer, transactionId); // Execute executeTransactionBySigner(signer, transactionId); } // execute transaction on behalf of signer, not msg.sender function executeTransactionBySigner( address signer, uint256 transactionId ) internal notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (externalCall( txn.destination, txn.value, txn.data.length, txn.data) ) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); txn.executed = false; } } } /** * Allows an owner to confirm a transaction. * * @param transactionId Transaction ID. */ function confirmTransaction( uint256 transactionId ) public virtual ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /** * Allows an owner to confirm a transaction via meta transaction. * * @param signer Signer of the meta transaction. * @param transactionId Transaction ID. * @param sig Signature. */ function confirmTransaction( address signer, uint256 transactionId, bytes memory sig ) public virtual ownerExists(signer) transactionExists(transactionId) notConfirmed(transactionId, signer) { // CONFIRM_TRANSACTION_TYPE_HASH = keccak256("confirmTransaction(uint256 transactionId)"); bytes32 EIP712SignDigest = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0x01), EIP712_DOMAIN_SEPARATOR, keccak256( abi.encode( CONFIRM_TRANSACTION_TYPE_HASH, transactionId ) ) ) ); validateSignature(signer, EIP712SignDigest, sig); confirmations[transactionId][signer] = true; emit Confirmation(signer, transactionId); executeTransactionBySigner(signer, transactionId); } /** * Allows an owner to revoke a confirmation for a transaction. * * @param transactionId Transaction ID. */ function revokeConfirmation( uint256 transactionId ) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /** * Allows an owner to execute a confirmed transaction. * * @param transactionId Transaction ID. */ function executeTransaction( uint256 transactionId ) public virtual ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (externalCall( txn.destination, txn.value, txn.data.length, txn.data) ) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); txn.executed = false; } } } // ============ Getter Functions ============ /** * Returns the confirmation status of a transaction. * * @param transactionId Transaction ID. * @return Confirmation status. */ function isConfirmed( uint256 transactionId ) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } if (count == required) { return true; } } } /** * Returns number of confirmations of a transaction. * * @param transactionId Transaction ID. * @return Number of confirmations. */ function getConfirmationCount( uint256 transactionId ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } } return count; } /** * Returns total number of transactions after filers are applied. * * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Total number of transactions after filters are applied. */ function getTransactionCount( bool pending, bool executed ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < transactionCount; i++) { if ( pending && !transactions[i].executed || executed && transactions[i].executed ) { count += 1; } } return count; } /** * Returns array of owners. * * @return Array of owner addresses. */ function getOwners() public view returns (address[] memory) { return owners; } /** * Returns array with owner addresses, which confirmed transaction. * * @param transactionId Transaction ID. * @return Array of owner addresses. */ function getConfirmations( uint256 transactionId ) public view returns (address[] memory) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } address[] memory _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } return _confirmations; } /** * Returns list of transaction IDs in defined range. * * @param from Index start position of transaction array. * @param to Index end position of transaction array. * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Array of transaction IDs. */ function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) { if ( pending && !transactions[i].executed || executed && transactions[i].executed ) { transactionIdsTemp[count] = i; count += 1; } } uint256[] memory _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } return _transactionIds; } // ============ Helper Functions ============ function validateSignature( address signer, bytes32 digest, bytes memory sig ) internal { require(sig.length == 65); uint8 v = uint8(sig[64]); bytes32 r = sig.readBytes32(0); bytes32 s = sig.readBytes32(32); address recovered = ecrecover(digest, v, r, s); require(signer == recovered); } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function externalCall( address destination, uint256 value, uint256 dataLength, bytes memory data ) internal returns (bool) { bool result; /* solium-disable-next-line security/no-inline-assembly */ assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas(), 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /** * Adds a new transaction to the transaction mapping, if transaction does not exist yet. * * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Transaction ID. */ function addTransaction( address destination, uint256 value, bytes memory data ) internal notNull(destination) returns (uint256) { uint256 transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); return transactionId; } }
33,628
25
// _reserve underlying token address/_user users address
function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve
function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve
13,124
89
// total register name count
uint256 public _totalRegisterCount = 0;
uint256 public _totalRegisterCount = 0;
15,698
37
// Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded.
* Emits a {Transfer} event. * * Requirements: * - Sender's account must have sufficient balance to transfer * - Sender must have sufficient allowance to transfer * - 0 value transfers are allowed */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
* Emits a {Transfer} event. * * Requirements: * - Sender's account must have sufficient balance to transfer * - Sender must have sufficient allowance to transfer * - 0 value transfers are allowed */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
5,721
4
// Grab the next available token ID
uint256 tokenId = nextTokenIdToMint();
uint256 tokenId = nextTokenIdToMint();
3,888
7
// Modifier for checking if the account is not frozen /
modifier onlyNotFrozen(address a) { require(!isFrozen[a], "Any account in this function must not be frozen"); _; }
modifier onlyNotFrozen(address a) { require(!isFrozen[a], "Any account in this function must not be frozen"); _; }
16,835
0
// SPDX-License-Identifier: MIT//
interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); 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 decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); 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); }
10,030
285
// We use Math.min here to prevent integer overflow (ie. go negative) when calculating numSecondsElapsed. Typically this shouldn't be possible, because the interestAccruedAsOf couldn't be after the current timestamp. However, when assessing we allow this function to be called with a past timestamp, which raises the possibility of overflow. This use of min should not generate incorrect interest calculations, since this function's purpose is just to normalize balances, and handing in a past timestamp will necessarily return zero interest accrued (because zero elapsed time), which is correct.
uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf()); return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays);
uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf()); return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays);
65,014
78
// transfers crowdsale token from mintable to transferrable state
function releaseTokens() external onlyOwner() // manager is CrowdsaleController instance hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale was successful
function releaseTokens() external onlyOwner() // manager is CrowdsaleController instance hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale was successful
32,893