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
1
// Maps a rate feed to its breakers and their breaker status. (rateFeedID => (breaker => BreakerStatus)
mapping(address => mapping(address => BreakerStatus)) public rateFeedBreakerStatus;
mapping(address => mapping(address => BreakerStatus)) public rateFeedBreakerStatus;
26,153
49
// This is the max fee that the contract will accept, it is hard-coded to protect buyers This includes the buy AND the sell fee!
uint256 private maxPossibleFee = 20;
uint256 private maxPossibleFee = 20;
18,760
18
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32) mstore8(dest, data)
let dest := add(add(bufptr, off), 32) mstore8(dest, data)
6,176
100
// Creates and returns stake data in StakeInfoResponse struct format using PoolInfo and StakeInfo from storage /
function createStakeInfoResponse( address _address, uint256 _poolId, uint256 _stakeId
function createStakeInfoResponse( address _address, uint256 _poolId, uint256 _stakeId
7,200
11
// The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" );
bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" );
27,710
0
// save the code address
bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, contractLogic) }
bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, contractLogic) }
11,183
56
// A unique identifier for this peggy instance to use in signatures
bytes32 _peggyId,
bytes32 _peggyId,
67,778
160
// begins the minting of the NFTs
function switchToPresale() public onlyOwner{ require(saleState_ == State.NoSale, "Presale has already opened!"); saleState_ = State.Presale; presaleLaunchTime = block.timestamp; }
function switchToPresale() public onlyOwner{ require(saleState_ == State.NoSale, "Presale has already opened!"); saleState_ = State.Presale; presaleLaunchTime = block.timestamp; }
40,956
88
// Delegates votes from signer to `delegatee`. /
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
7,509
6
// NFT used for auctions
IERC721 public tomiDNS;
IERC721 public tomiDNS;
30,699
40
// Returns the token collection name. /
function name() public view virtual override returns (string memory) { return ERC721AStorage.layout()._name; }
function name() public view virtual override returns (string memory) { return ERC721AStorage.layout()._name; }
6,934
26
// 3 is the last room.
if (uint256(_room) == 3) { ceiling = 20000; } else {
if (uint256(_room) == 3) { ceiling = 20000; } else {
70,510
72
// Constructor function./
constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); }
constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); }
19,967
59
// decreasing value requires different calculation
return endOffset.sub(current).mul(startScale.sub(endScale)).div(range).add(endScale);
return endOffset.sub(current).mul(startScale.sub(endScale)).div(range).add(endScale);
20,915
16
// Performance fee charged on premiums earned in rollToNextRound. Only charged when there is no loss.
uint256 public performanceFee;
uint256 public performanceFee;
8,371
258
// The next available ID to be assumed by the next pool added.
uint256 public nextPoolId;
uint256 public nextPoolId;
46,448
116
// DeFiYieldProtocol with Governance.
contract DeFiYieldProtocol is ERC20("DeFiYieldProtocol", "DYP"), Ownable { /// @notice Creates total supply of 30.000.000 DYP constructor() public { _mint(msg.sender, 30000000000000000000000000); } /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "DYP::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "DYP::delegateBySig: invalid nonce"); require(now <= expiry, "DYP::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "DYP::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying DYPs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "DYP::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract DeFiYieldProtocol is ERC20("DeFiYieldProtocol", "DYP"), Ownable { /// @notice Creates total supply of 30.000.000 DYP constructor() public { _mint(msg.sender, 30000000000000000000000000); } /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "DYP::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "DYP::delegateBySig: invalid nonce"); require(now <= expiry, "DYP::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "DYP::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying DYPs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "DYP::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
16,766
361
// Claim on behalf
function approveClaimOnBehalf(address delegate) external { _setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate); }
function approveClaimOnBehalf(address delegate) external { _setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate); }
5,836
17
// Update the value of tokens currently held by the contract.
contract_eth_value -= balances[msg.sender];
contract_eth_value -= balances[msg.sender];
35,567
18
// Operator address and data fields are null, _partition = defaultPartition
_transferByPartition(msg.sender, _to, defaultPartition, _value, "", address(0), ""); emit Transfer(msg.sender, _to, _value); return true;
_transferByPartition(msg.sender, _to, defaultPartition, _value, "", address(0), ""); emit Transfer(msg.sender, _to, _value); return true;
26,743
15
// Read and write to persistent storage at a fraction of the cost./Solmate (https:github.com/Rari-Capital/solmate/blob/main/src/utils/SSTORE2.sol)/Modified from 0xSequence (https:github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
library SSTORE2 { uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called. /*////////////////////////////////////////////////////////////// WRITE LOGIC //////////////////////////////////////////////////////////////*/ function write(bytes memory data) internal returns (address pointer) { // Prefix the bytecode with a STOP opcode to ensure it cannot be called. bytes memory runtimeCode = abi.encodePacked(hex"00", data); bytes memory creationCode = abi.encodePacked( //---------------------------------------------------------------------------------------------------------------// // Opcode | Opcode + Arguments | Description | Stack View // //---------------------------------------------------------------------------------------------------------------// // 0x60 | 0x600B | PUSH1 11 | codeOffset // // 0x59 | 0x59 | MSIZE | 0 codeOffset // // 0x81 | 0x81 | DUP2 | codeOffset 0 codeOffset // // 0x38 | 0x38 | CODESIZE | codeSize codeOffset 0 codeOffset // // 0x03 | 0x03 | SUB | (codeSize - codeOffset) 0 codeOffset // // 0x80 | 0x80 | DUP | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset // // 0x92 | 0x92 | SWAP3 | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) // // 0x59 | 0x59 | MSIZE | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) // // 0x39 | 0x39 | CODECOPY | 0 (codeSize - codeOffset) // // 0xf3 | 0xf3 | RETURN | // //---------------------------------------------------------------------------------------------------------------// hex"60_0B_59_81_38_03_80_92_59_39_F3", // Returns all code in the contract except for the first 11 (0B in hex) bytes. runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit. ); assembly { // Deploy a new contract with the generated creation code. // We start 32 bytes into the code to avoid copying the byte length. pointer := create(0, add(creationCode, 32), mload(creationCode)) } require(pointer != address(0), "DEPLOYMENT_FAILED"); } /*////////////////////////////////////////////////////////////// READ LOGIC //////////////////////////////////////////////////////////////*/ function read(address pointer) internal view returns (bytes memory) { return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET); } function read(address pointer, uint256 start) internal view returns (bytes memory) { start += DATA_OFFSET; return readBytecode(pointer, start, pointer.code.length - start); } function read( address pointer, uint256 start, uint256 end ) internal view returns (bytes memory) { start += DATA_OFFSET; end += DATA_OFFSET; require(pointer.code.length >= end, "OUT_OF_BOUNDS"); return readBytecode(pointer, start, end - start); } /*////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function readBytecode( address pointer, uint256 start, uint256 size ) private view returns (bytes memory data) { assembly { // Get a pointer to some free memory. data := mload(0x40) // Update the free memory pointer to prevent overriding our data. // We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)). // Adding 31 to size and running the result through the logic above ensures // the memory pointer remains word-aligned, following the Solidity convention. mstore(0x40, add(data, and(add(add(size, 32), 31), not(31)))) // Store the size of the data in the first 32 byte chunk of free memory. mstore(data, size) // Copy the code into memory right after the 32 bytes we used to store the size. extcodecopy(pointer, add(data, 32), start, size) } } }
library SSTORE2 { uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called. /*////////////////////////////////////////////////////////////// WRITE LOGIC //////////////////////////////////////////////////////////////*/ function write(bytes memory data) internal returns (address pointer) { // Prefix the bytecode with a STOP opcode to ensure it cannot be called. bytes memory runtimeCode = abi.encodePacked(hex"00", data); bytes memory creationCode = abi.encodePacked( //---------------------------------------------------------------------------------------------------------------// // Opcode | Opcode + Arguments | Description | Stack View // //---------------------------------------------------------------------------------------------------------------// // 0x60 | 0x600B | PUSH1 11 | codeOffset // // 0x59 | 0x59 | MSIZE | 0 codeOffset // // 0x81 | 0x81 | DUP2 | codeOffset 0 codeOffset // // 0x38 | 0x38 | CODESIZE | codeSize codeOffset 0 codeOffset // // 0x03 | 0x03 | SUB | (codeSize - codeOffset) 0 codeOffset // // 0x80 | 0x80 | DUP | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset // // 0x92 | 0x92 | SWAP3 | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) // // 0x59 | 0x59 | MSIZE | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) // // 0x39 | 0x39 | CODECOPY | 0 (codeSize - codeOffset) // // 0xf3 | 0xf3 | RETURN | // //---------------------------------------------------------------------------------------------------------------// hex"60_0B_59_81_38_03_80_92_59_39_F3", // Returns all code in the contract except for the first 11 (0B in hex) bytes. runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit. ); assembly { // Deploy a new contract with the generated creation code. // We start 32 bytes into the code to avoid copying the byte length. pointer := create(0, add(creationCode, 32), mload(creationCode)) } require(pointer != address(0), "DEPLOYMENT_FAILED"); } /*////////////////////////////////////////////////////////////// READ LOGIC //////////////////////////////////////////////////////////////*/ function read(address pointer) internal view returns (bytes memory) { return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET); } function read(address pointer, uint256 start) internal view returns (bytes memory) { start += DATA_OFFSET; return readBytecode(pointer, start, pointer.code.length - start); } function read( address pointer, uint256 start, uint256 end ) internal view returns (bytes memory) { start += DATA_OFFSET; end += DATA_OFFSET; require(pointer.code.length >= end, "OUT_OF_BOUNDS"); return readBytecode(pointer, start, end - start); } /*////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function readBytecode( address pointer, uint256 start, uint256 size ) private view returns (bytes memory data) { assembly { // Get a pointer to some free memory. data := mload(0x40) // Update the free memory pointer to prevent overriding our data. // We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)). // Adding 31 to size and running the result through the logic above ensures // the memory pointer remains word-aligned, following the Solidity convention. mstore(0x40, add(data, and(add(add(size, 32), 31), not(31)))) // Store the size of the data in the first 32 byte chunk of free memory. mstore(data, size) // Copy the code into memory right after the 32 bytes we used to store the size. extcodecopy(pointer, add(data, 32), start, size) } } }
34,638
12
// Same TokenURI for all existing tokens. /
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(uint16(tokenId)), "ERC721Metadata: URI query for nonexistent token"); return _metadataURI; }
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(uint16(tokenId)), "ERC721Metadata: URI query for nonexistent token"); return _metadataURI; }
29,346
66
// Divides x between y, assuming they are both fixed point with 27 digits.
function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); }
function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); }
78,312
32
// ERC20 total supply/ return The current total supply of the resource
function totalSupply() public constant returns(uint)
function totalSupply() public constant returns(uint)
59,159
12
// Set SDVD address
sdvd = _sdvd;
sdvd = _sdvd;
44,723
14
// God can unpause the game
function godUnpause() public onlyGod
function godUnpause() public onlyGod
15,987
122
// Top up Vesper deployer address
function topUp() external { _topUp(); }
function topUp() external { _topUp(); }
53,049
36
// Crypto Union Contract/Nikki Nikolenko/You can use this contract to transfer money to another address associated with a given country/Only ETH transfers are supported for now
contract CryptoUnion is Ownable, Pausable, ReentrancyGuard { //transfer id uint256 public transferCount = 0; //the initator needs to send > minValue for the transaction to go through uint256 public minValue = 3e15; //contry code (3 chars max) -> address mapping mapping(string => address) public addresses; //wallet address -> count of pending transfers mapping mapping(address => uint256) public pendingTransfers; // transfer id -> Transfer mapping mapping(uint256 => Transfer) public transfers; /// @notice Status enum which can either be "Sent" or "Confirmed" enum Status { Sent, Confirmed } /// @notice Transfer struct that captures all the necessary information about a transafer struct Transfer { uint256 transferId; address payable from; string to; //country code of the recepient Status status; uint256 amount; } /* * Events */ /// @notice Emitted after successful address update for country code -> address pair /// @param countryCode Three-letter country code, e.g. BHS /// @param oldWallet An old address associated with the country code /// @param newWallet A new address associated with the country code event LogCountryAddressUpdated( string countryCode, address oldWallet, address newWallet ); /// @notice Emitted after we have successfully sent the money to an address associated with a given country /// @param transferId id of the transfer, can be used to view the transfer later /// @param from Sender's address /// @param to Three-letter country code, e.g. BHS /// @param amount Amount transferred (msg.value - contract fee) /// @param status Status of the transfer /// @param contractFee contract fee event LogTransferSent( uint256 transferId, address from, string to, uint256 amount, Status status, uint256 contractFee ); /// @notice Emitted if the send money call failed /// @param transferId id of the transfer, can be used to view the transfer later /// @param from Sender's address /// @param to Three-letter country code, e.g. BHS /// @param amount Amount transferred (msg.value - contract fee) event LogTransferFailed( uint256 transferId, address from, string to, uint256 amount ); /* * Modifiers */ /// @notice Validate the given country code /// @dev Inputs longer than three English letters will be rejected /// @param countryCode Three-letter country code, e.g. BHS modifier validCountryCode(string memory countryCode) { bytes memory tempEmptyStringTest = bytes(countryCode); require(tempEmptyStringTest.length == 3, "Invalid country code!"); _; } /// @notice Validate that the sender has send more ETH than the contract fee modifier paidEnough() { require(msg.value >= minValue, "Insufficient ammount!"); _; } /// @notice Validate that the transfer status is not Confirmed /// @param status The transfer status modifier checkStatus(Status status) { require(status == Status.Sent, "Transfer is already confirmed!"); _; } /// @notice Validate that there are no pending transfers for a given country code /// @param countryCode Three-letter country code, e.g. BHS modifier noPendingTransfers(string memory countryCode) { require( pendingTransfers[addresses[countryCode]] == 0, "There are still unconfirmed transfers at this address!" ); _; } /// @notice Validate that the transfer with a given transfer id exists /// @param _transferId Transfer id modifier transferExists(uint256 _transferId) { address from = transfers[_transferId].from; require(from != address(0), "Transfer does not exist!"); _; } /// @notice Checks if the transaction was sent by the contract owner /// @dev Used for admin sign-in in the web UI /// @return true if the sender address belongs to contract owner, false otherwise. function adminSignIn() public view returns (bool) { return msg.sender == owner(); } /// @notice Set the country code -> address pair /// @dev Also allows you to delete supported country codes by setting the wallet to address to 0 /// @param countryCode Three-letter country code, e.g. BHS /// @param wallet Wallet address corresponding to the country code function setAddress(string memory countryCode, address wallet) public onlyOwner whenNotPaused validCountryCode(countryCode) noPendingTransfers(countryCode) { address oldWallet = addresses[countryCode]; addresses[countryCode] = wallet; emit LogCountryAddressUpdated(countryCode, oldWallet, wallet); } /// @notice Get an address corresponding to a give country code /// @dev Inputs longer than three English letters will be rejected /// @param countryCode Three-letter country code, e.g. BHS /// @return address corresponding the country code function getAddress(string memory countryCode) public view validCountryCode(countryCode) returns (address) { return addresses[countryCode]; } /// @notice Get the contract fee /// @return contract fee function getMinValue() public view returns (uint256) { return minValue; } /// @notice Get transfer count /// @return transfer count function getTransferCount() public view returns (uint256) { return transferCount; } /// @notice Send ETH to a given country, contract fee will be withheld /// @dev If we are unable to perform the send the whole transaction is reverted /// @param countryCode Three-letter country code, e.g. BHS function sendEthToCountry(string memory countryCode) public payable paidEnough validCountryCode(countryCode) whenNotPaused nonReentrant { // Here are the approximate steps: // 1. Create a transfer - need to figure out how much the contract should charge for the service if (addresses[countryCode] == address(0)) { revert("Invalid address"); } uint256 amount = msg.value - minValue; transfers[transferCount] = Transfer( transferCount, payable(msg.sender), countryCode, Status.Sent, amount ); pendingTransfers[addresses[countryCode]] += 1; transferCount += 1; // 2. Try to send money to addresses[countryCode] (bool sent, ) = addresses[countryCode].call{value: amount}(""); if (!sent) { emit LogTransferFailed( transferCount - 1, msg.sender, countryCode, amount ); } // defending afainst https://swcregistry.io/docs/SWC-104 require(sent, "Failed to send Ether"); // 3. If success, change the status to Sent emit LogTransferSent( transferCount - 1, msg.sender, countryCode, amount, Status.Sent, minValue ); } /// @notice Get information about a given trasfer /// @param _transferId transfer id /// @return transfer information: transfer id, from - address of the sender, to - receiving country code, status - status of the transfer, amount transferred (in ETH), contract fee function getTransfer(uint256 _transferId) public view transferExists(_transferId) returns ( uint256, address, string memory, Status, uint256, uint256 ) { return ( transfers[_transferId].transferId, transfers[_transferId].from, transfers[_transferId].to, transfers[_transferId].status, transfers[_transferId].amount, minValue ); } /// @notice Confirm a given transfer, should be done after Admin has transferred the money to the recepient off-chain /// @param _transferId transfer id function confirmTransfer(uint256 _transferId) public onlyOwner whenNotPaused transferExists(_transferId) checkStatus(transfers[_transferId].status) { transfers[_transferId].status = Status.Confirmed; pendingTransfers[addresses[transfers[_transferId].to]] -= 1; } /// @notice Withdraw contract's balance to the owner's address /// @dev The function will revert if the send wasn't successful function withdraw() public onlyOwner nonReentrant { (bool sent, ) = msg.sender.call{value: address(this).balance}(""); require(sent, "Failed to send Ether"); } /// @notice pause the contract -- the contract will start functioning in read-only mode. /// @dev Implementing the circuit breaker pattern function pause() public onlyOwner { Pausable._pause(); } /// @notice resume the contract for both reads and writes /// @dev Implementing the circuit breaker pattern function unpause() public onlyOwner { Pausable._unpause(); } }
contract CryptoUnion is Ownable, Pausable, ReentrancyGuard { //transfer id uint256 public transferCount = 0; //the initator needs to send > minValue for the transaction to go through uint256 public minValue = 3e15; //contry code (3 chars max) -> address mapping mapping(string => address) public addresses; //wallet address -> count of pending transfers mapping mapping(address => uint256) public pendingTransfers; // transfer id -> Transfer mapping mapping(uint256 => Transfer) public transfers; /// @notice Status enum which can either be "Sent" or "Confirmed" enum Status { Sent, Confirmed } /// @notice Transfer struct that captures all the necessary information about a transafer struct Transfer { uint256 transferId; address payable from; string to; //country code of the recepient Status status; uint256 amount; } /* * Events */ /// @notice Emitted after successful address update for country code -> address pair /// @param countryCode Three-letter country code, e.g. BHS /// @param oldWallet An old address associated with the country code /// @param newWallet A new address associated with the country code event LogCountryAddressUpdated( string countryCode, address oldWallet, address newWallet ); /// @notice Emitted after we have successfully sent the money to an address associated with a given country /// @param transferId id of the transfer, can be used to view the transfer later /// @param from Sender's address /// @param to Three-letter country code, e.g. BHS /// @param amount Amount transferred (msg.value - contract fee) /// @param status Status of the transfer /// @param contractFee contract fee event LogTransferSent( uint256 transferId, address from, string to, uint256 amount, Status status, uint256 contractFee ); /// @notice Emitted if the send money call failed /// @param transferId id of the transfer, can be used to view the transfer later /// @param from Sender's address /// @param to Three-letter country code, e.g. BHS /// @param amount Amount transferred (msg.value - contract fee) event LogTransferFailed( uint256 transferId, address from, string to, uint256 amount ); /* * Modifiers */ /// @notice Validate the given country code /// @dev Inputs longer than three English letters will be rejected /// @param countryCode Three-letter country code, e.g. BHS modifier validCountryCode(string memory countryCode) { bytes memory tempEmptyStringTest = bytes(countryCode); require(tempEmptyStringTest.length == 3, "Invalid country code!"); _; } /// @notice Validate that the sender has send more ETH than the contract fee modifier paidEnough() { require(msg.value >= minValue, "Insufficient ammount!"); _; } /// @notice Validate that the transfer status is not Confirmed /// @param status The transfer status modifier checkStatus(Status status) { require(status == Status.Sent, "Transfer is already confirmed!"); _; } /// @notice Validate that there are no pending transfers for a given country code /// @param countryCode Three-letter country code, e.g. BHS modifier noPendingTransfers(string memory countryCode) { require( pendingTransfers[addresses[countryCode]] == 0, "There are still unconfirmed transfers at this address!" ); _; } /// @notice Validate that the transfer with a given transfer id exists /// @param _transferId Transfer id modifier transferExists(uint256 _transferId) { address from = transfers[_transferId].from; require(from != address(0), "Transfer does not exist!"); _; } /// @notice Checks if the transaction was sent by the contract owner /// @dev Used for admin sign-in in the web UI /// @return true if the sender address belongs to contract owner, false otherwise. function adminSignIn() public view returns (bool) { return msg.sender == owner(); } /// @notice Set the country code -> address pair /// @dev Also allows you to delete supported country codes by setting the wallet to address to 0 /// @param countryCode Three-letter country code, e.g. BHS /// @param wallet Wallet address corresponding to the country code function setAddress(string memory countryCode, address wallet) public onlyOwner whenNotPaused validCountryCode(countryCode) noPendingTransfers(countryCode) { address oldWallet = addresses[countryCode]; addresses[countryCode] = wallet; emit LogCountryAddressUpdated(countryCode, oldWallet, wallet); } /// @notice Get an address corresponding to a give country code /// @dev Inputs longer than three English letters will be rejected /// @param countryCode Three-letter country code, e.g. BHS /// @return address corresponding the country code function getAddress(string memory countryCode) public view validCountryCode(countryCode) returns (address) { return addresses[countryCode]; } /// @notice Get the contract fee /// @return contract fee function getMinValue() public view returns (uint256) { return minValue; } /// @notice Get transfer count /// @return transfer count function getTransferCount() public view returns (uint256) { return transferCount; } /// @notice Send ETH to a given country, contract fee will be withheld /// @dev If we are unable to perform the send the whole transaction is reverted /// @param countryCode Three-letter country code, e.g. BHS function sendEthToCountry(string memory countryCode) public payable paidEnough validCountryCode(countryCode) whenNotPaused nonReentrant { // Here are the approximate steps: // 1. Create a transfer - need to figure out how much the contract should charge for the service if (addresses[countryCode] == address(0)) { revert("Invalid address"); } uint256 amount = msg.value - minValue; transfers[transferCount] = Transfer( transferCount, payable(msg.sender), countryCode, Status.Sent, amount ); pendingTransfers[addresses[countryCode]] += 1; transferCount += 1; // 2. Try to send money to addresses[countryCode] (bool sent, ) = addresses[countryCode].call{value: amount}(""); if (!sent) { emit LogTransferFailed( transferCount - 1, msg.sender, countryCode, amount ); } // defending afainst https://swcregistry.io/docs/SWC-104 require(sent, "Failed to send Ether"); // 3. If success, change the status to Sent emit LogTransferSent( transferCount - 1, msg.sender, countryCode, amount, Status.Sent, minValue ); } /// @notice Get information about a given trasfer /// @param _transferId transfer id /// @return transfer information: transfer id, from - address of the sender, to - receiving country code, status - status of the transfer, amount transferred (in ETH), contract fee function getTransfer(uint256 _transferId) public view transferExists(_transferId) returns ( uint256, address, string memory, Status, uint256, uint256 ) { return ( transfers[_transferId].transferId, transfers[_transferId].from, transfers[_transferId].to, transfers[_transferId].status, transfers[_transferId].amount, minValue ); } /// @notice Confirm a given transfer, should be done after Admin has transferred the money to the recepient off-chain /// @param _transferId transfer id function confirmTransfer(uint256 _transferId) public onlyOwner whenNotPaused transferExists(_transferId) checkStatus(transfers[_transferId].status) { transfers[_transferId].status = Status.Confirmed; pendingTransfers[addresses[transfers[_transferId].to]] -= 1; } /// @notice Withdraw contract's balance to the owner's address /// @dev The function will revert if the send wasn't successful function withdraw() public onlyOwner nonReentrant { (bool sent, ) = msg.sender.call{value: address(this).balance}(""); require(sent, "Failed to send Ether"); } /// @notice pause the contract -- the contract will start functioning in read-only mode. /// @dev Implementing the circuit breaker pattern function pause() public onlyOwner { Pausable._pause(); } /// @notice resume the contract for both reads and writes /// @dev Implementing the circuit breaker pattern function unpause() public onlyOwner { Pausable._unpause(); } }
24,523
201
// The amount of interest has been accrued per token address. /
mapping(address => uint256) private earnings;
mapping(address => uint256) private earnings;
8,179
30
// Add Vault/It is excuted by proxy/_vault vault address/_phase phase ex) 1,2,3/_vaultNamehash of vault's name
function addVault( address _vault, uint256 _phase, bytes32 _vaultName ) external;
function addVault( address _vault, uint256 _phase, bytes32 _vaultName ) external;
43,086
67
// Hook that is called after any transfer of tokens. This includesminting and burning. Calling conditions: - when `from` and `to` are both non-zero.- `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. /
function _afterTokenTransfer( address from, address to, uint256 tokenId
function _afterTokenTransfer( address from, address to, uint256 tokenId
8,437
22
// case where player deposit does not change
if(_finalBalance == lockedFunds[_playerAddr]) { unlockPlayerFunds(_playerAddr); }
if(_finalBalance == lockedFunds[_playerAddr]) { unlockPlayerFunds(_playerAddr); }
9,591
211
// Warning LTV: ratio at which we will repay
uint16 public warningLTVMultiplier = 8_000; // 80% of liquidation LTV
uint16 public warningLTVMultiplier = 8_000; // 80% of liquidation LTV
33,922
119
// Provide an accurate estimate for the total amount of assets (principle + return) that this Strategy is currently managing, denominated in terms of `want` tokens.This total should be "realizable" e.g. the total value that could actually be obtained from this Strategy if it were to divest its entire position based on current on-chain conditions. Care must be taken in using this function, since it relies on external systems, which could be manipulated by the attacker to give an inflated (or reduced) value produced by this function, based on current on-chain conditions (e.g. this function is possible to influence through flashloan
function estimatedTotalAssets() public virtual view returns (uint256);
function estimatedTotalAssets() public virtual view returns (uint256);
4,488
310
// Withdraw assets from the Prize Pool instantly.A fairness fee may be charged for an early exit./from The address to redeem tokens from./amount The amount of tokens to redeem for assets./controlledToken The address of the token to redeem (i.e. ticket or sponsorship)/maximumExitFee The maximum exit fee the caller is willing to pay.This should be pre-calculated by the calculateExitFee() fxn./ return The actual exit fee paid
function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256)
function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256)
57,933
159
// Main Crowdsale basic contractversion 1.0 /
contract CrowdsaleRaspberry is MintedCrowdsale, PausableCrowdsale { constructor (uint256 rate, address payable wallet, ERC20Chocolate token, bool _isPausable) public Crowdsale(rate, wallet, token) { // solhint-disable-previous-line no-empty-blocks _setPausableActive(_isPausable); } }
contract CrowdsaleRaspberry is MintedCrowdsale, PausableCrowdsale { constructor (uint256 rate, address payable wallet, ERC20Chocolate token, bool _isPausable) public Crowdsale(rate, wallet, token) { // solhint-disable-previous-line no-empty-blocks _setPausableActive(_isPausable); } }
6,751
88
// Called by proxy to initialize this contract _pool Vesper pool address _rewardTokens Array of reward token addresses /
function initialize(address _pool, address[] memory _rewardTokens) public initializer { require(_pool != address(0), "pool-address-is-zero"); require(_rewardTokens.length != 0, "invalid-reward-tokens"); pool = _pool; rewardTokens = _rewardTokens; for (uint256 i = 0; i < _rewardTokens.length; i++) { isRewardToken[_rewardTokens[i]] = true; } }
function initialize(address _pool, address[] memory _rewardTokens) public initializer { require(_pool != address(0), "pool-address-is-zero"); require(_rewardTokens.length != 0, "invalid-reward-tokens"); pool = _pool; rewardTokens = _rewardTokens; for (uint256 i = 0; i < _rewardTokens.length; i++) { isRewardToken[_rewardTokens[i]] = true; } }
28,869
3
// create new mixing contract with _participants amount of mixing participants,_payment - expected payment from each participant.
function Laundromat(uint _participants, uint _payment) { owner = msg.sender; arithContract = ArithLib(arithAddress); participants = _participants; payment = _payment; }
function Laundromat(uint _participants, uint _payment) { owner = msg.sender; arithContract = ArithLib(arithAddress); participants = _participants; payment = _payment; }
12,639
125
// whitelist to set sale
mapping(address => bool) public whitelist;
mapping(address => bool) public whitelist;
46,655
65
// calcInGivenOut aI = tokenAmountIn bO = tokenBalanceOut // bO\(wO / wI)\bI = tokenBalanceInbI|| ------------| ^- 1| aO = tokenAmountOutaI =\\ ( bO - aO ) / /wI = tokenWeightIn --------------------------------------------wO = tokenWeightOut( 1 - sF )sF = swapFee/
{ uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; }
{ uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; }
16,455
0
// uint256 MAX_INT = 2256 - 1
event LogNote(string, uint256);
event LogNote(string, uint256);
16,981
20
// ------------------------------------------------------------------------ Token owner can approve for spender to transferFrom(...) tokens from the token owner's account recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; }
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; }
3,704
13
// Returns the 8-bit number at the specified index of self.self The byte string.idx The index into the bytes return The specified 8 bits of the string, interpreted as an integer./
function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { require(idx + 1 <= self.length); assembly { ret := and(mload(add(add(self, 1), idx)), 0xFF) } }
function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { require(idx + 1 <= self.length); assembly { ret := and(mload(add(add(self, 1), idx)), 0xFF) } }
26,902
119
// Crowdsale for the Trees.
contract Crowdsale is ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 private _token; address payable private _wallet; uint256 private _rate; uint256 private _weiRaised; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } receive () external payable { this.buyTokens{value: msg.value}(msg.sender); } function token() public view returns (IERC20) { return _token; } function wallet() public view returns (address payable) { return _wallet; } function rate() public view returns (uint256) { return _rate; } function weiRaised() public view returns (uint256) { return _weiRaised; } function buyTokens(address beneficiary) public nonReentrant whenNotPaused payable { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); tokens = tokens.mul(10 ** uint256(18)); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); } function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } function _deliverTokens(address beneficiary, uint256 tokenAmount) virtual internal { _token.safeTransfer(beneficiary, tokenAmount); } function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.div(_rate); } function _forwardFunds() internal { _wallet.transfer(msg.value); } }
contract Crowdsale is ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 private _token; address payable private _wallet; uint256 private _rate; uint256 private _weiRaised; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } receive () external payable { this.buyTokens{value: msg.value}(msg.sender); } function token() public view returns (IERC20) { return _token; } function wallet() public view returns (address payable) { return _wallet; } function rate() public view returns (uint256) { return _rate; } function weiRaised() public view returns (uint256) { return _weiRaised; } function buyTokens(address beneficiary) public nonReentrant whenNotPaused payable { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); tokens = tokens.mul(10 ** uint256(18)); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); } function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } function _deliverTokens(address beneficiary, uint256 tokenAmount) virtual internal { _token.safeTransfer(beneficiary, tokenAmount); } function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.div(_rate); } function _forwardFunds() internal { _wallet.transfer(msg.value); } }
38,612
26
// after how many buy sell should redue to final tax
uint256 private _reduceBuyTaxAt=15; uint256 private _reduceSellTaxAt=15; uint256 private _preventSwapBefore=10; uint256 private _buyCount=0; uint8 private constant _decimals = 9; uint256 private constant _tTotal = 100000000 * 10**_decimals; // 100 million max supply string private constant _name = "Viva-GO" ; string private constant _symbol = "VIVA" ; uint256 public _maxTxAmount = 2000000 * 10**_decimals; // 2% of the supply
uint256 private _reduceBuyTaxAt=15; uint256 private _reduceSellTaxAt=15; uint256 private _preventSwapBefore=10; uint256 private _buyCount=0; uint8 private constant _decimals = 9; uint256 private constant _tTotal = 100000000 * 10**_decimals; // 100 million max supply string private constant _name = "Viva-GO" ; string private constant _symbol = "VIVA" ; uint256 public _maxTxAmount = 2000000 * 10**_decimals; // 2% of the supply
9,920
151
// Continue processing the purchase.
super._processPurchase(_beneficiary, _tokenAmount);
super._processPurchase(_beneficiary, _tokenAmount);
14,758
33
// View helper functions
function collateralizationP() public view returns(uint) { // PRECISION (%) return accPnlPerTokenUsed > 0 ? (PRECISION - uint(accPnlPerTokenUsed)) * 100 : (PRECISION + uint(accPnlPerTokenUsed * (-1))) * 100; }
function collateralizationP() public view returns(uint) { // PRECISION (%) return accPnlPerTokenUsed > 0 ? (PRECISION - uint(accPnlPerTokenUsed)) * 100 : (PRECISION + uint(accPnlPerTokenUsed * (-1))) * 100; }
22,767
20
// Push 32 ETH x count to allowed vault, where ETH going to Deposit Contract
function pushToVault(address vault, uint256 count) external onlyOperator nonReentrant { require(_allowedVaults[vault], "GlobalPool: vault not allowed"); require(count > 0, "GlobalPool: count is zero"); uint256 amount = count.mul(32 ether); require(address(this).balance >= amount, "GlobalPool: pending ethers not enough"); _unsafeTransfer(vault, amount, false); emit PushedToVault(vault, count); }
function pushToVault(address vault, uint256 count) external onlyOperator nonReentrant { require(_allowedVaults[vault], "GlobalPool: vault not allowed"); require(count > 0, "GlobalPool: count is zero"); uint256 amount = count.mul(32 ether); require(address(this).balance >= amount, "GlobalPool: pending ethers not enough"); _unsafeTransfer(vault, amount, false); emit PushedToVault(vault, count); }
8,485
6
// contract address => resourceID
mapping (address => bytes32) public _contractAddressToResourceID;
mapping (address => bytes32) public _contractAddressToResourceID;
57,709
11
// Allows Foundation to change the collection implementation used for future collections.This call will auto-increment the version.Existing collections are not impacted. /
function adminUpdateImplementation(address _implementation) external onlyAdmin { _updateImplementation(_implementation); }
function adminUpdateImplementation(address _implementation) external onlyAdmin { _updateImplementation(_implementation); }
4,012
60
// new sale times must be internally consistent
require( newConfig.startTime + newConfig.maxQueueTime < newConfig.endTime, "sale must be open for at least maxQueueTime" ); _;
require( newConfig.startTime + newConfig.maxQueueTime < newConfig.endTime, "sale must be open for at least maxQueueTime" ); _;
29,632
7
// The currency type to be delivered, Euro or Ether.
bytes32 currency;
bytes32 currency;
7,459
16
// solhint-disable-next-line not-rely-on-time / Validate `s` and `v` values for a malleability concern described in EIP2. Only signatures with `s` value in the lower half of the secp256k1 curve's order and `v` value of 27 or 28 are considered valid.
require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Invalid signature 's' value" ); require(v == 27 || v == 28, "Invalid signature 'v' value"); bytes32 digest = keccak256( abi.encodePacked(
require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Invalid signature 's' value" ); require(v == 27 || v == 28, "Invalid signature 'v' value"); bytes32 digest = keccak256( abi.encodePacked(
9,115
98
// This is denominated in D100Token, because the shares-D100 conversion might change before it's fully paid.
mapping(address => mapping(address => uint256)) private _allowedD100; bool public transfersPaused; bool public rebasesPaused; mapping(address => bool) public transferPauseExemptList;
mapping(address => mapping(address => uint256)) private _allowedD100; bool public transfersPaused; bool public rebasesPaused; mapping(address => bool) public transferPauseExemptList;
19,932
99
// Set the DAO Fee /
function queueRaiseDaoFee(uint _newDaoFee) external onlyOwner { raiseDaoFeeTimelockEnd = block.number.add(timelockInBlocks); newDaoFee = _newDaoFee; }
function queueRaiseDaoFee(uint _newDaoFee) external onlyOwner { raiseDaoFeeTimelockEnd = block.number.add(timelockInBlocks); newDaoFee = _newDaoFee; }
17,743
13
// Decrease remaining reserve
reserve.funds = reserve.funds.sub(claimAmount); emit ReserveClaimed(_reserveHolder, _claimant, claimAmount);
reserve.funds = reserve.funds.sub(claimAmount); emit ReserveClaimed(_reserveHolder, _claimant, claimAmount);
36,926
142
// set relationship between ethers and the corresponding Compound cETH contract _cEtherContract compound token contract address (cETH contract, on Kovan: 0x41b5844f4680a8c38fbb695b7f9cfd1f64474a72) /
function setCEtherContract(address _cEtherContract) external onlyAdmins { cEthToken = ICEth(_cEtherContract); cTokenContracts[address(0)] = _cEtherContract; }
function setCEtherContract(address _cEtherContract) external onlyAdmins { cEthToken = ICEth(_cEtherContract); cTokenContracts[address(0)] = _cEtherContract; }
21,771
30
// Get amount of takerToken required to buy a certain amount of makerToken for a given trade.Should match the takerToken amount used in exchangeForAmount. If the order cannot provideexactly desiredMakerToken, then it must return the price to buy the minimum amount greaterthan desiredMakerToken makerToken Address of makerToken, the token to receivetakerToken Address of takerToken, the token to paydesiredMakerTokenAmount of makerToken requestedorderDataArbitrary bytes data for any information to pass to the exchangereturnAmount of takerToken the needed to complete the transaction /
function getExchangeCost(
function getExchangeCost(
41,340
26
// Set the NFT registry contractNOTE: Calling this function will break the ownership model unlessit is replaced with a fully migrated version of the NFT contract stateUse with care. _subgraphNFT Address of the ERC721 contract /
function setSubgraphNFT(address _subgraphNFT) external onlyGovernor { _setSubgraphNFT(_subgraphNFT); }
function setSubgraphNFT(address _subgraphNFT) external onlyGovernor { _setSubgraphNFT(_subgraphNFT); }
20,035
17
// then approve the ctoken repay amount to be spent
token.approve(address(ctoken), _repayAmount);
token.approve(address(ctoken), _repayAmount);
29,011
16
// Decode an array of natural numeric values from a Witnet.Result as a `uint[]` value./_result An instance of Witnet.Result./ return The `uint[]` decoded from the Witnet.Result.
function asUint64Array(Witnet.Result memory _result) external pure returns (uint[] memory);
function asUint64Array(Witnet.Result memory _result) external pure returns (uint[] memory);
14,054
3
// Only update if price data if price array contains 2 or more valuesIf there is no new price data pricedate array will have 0 length
if(priceData.length > 0 && bullEquity != 0 && bearEquity != 0) { (uint256 rBullEquity, uint256 rBearEquity) = priceCalcLoop(priceData, bullEquity, bearEquity, ivault); uint256[6] memory data = equityToReturnData(bull, bear, rBullEquity, rBearEquity, ivault); return(data, roundId, true); }
if(priceData.length > 0 && bullEquity != 0 && bearEquity != 0) { (uint256 rBullEquity, uint256 rBearEquity) = priceCalcLoop(priceData, bullEquity, bearEquity, ivault); uint256[6] memory data = equityToReturnData(bull, bear, rBullEquity, rBearEquity, ivault); return(data, roundId, true); }
4,735
23
// Get number of tokens approved for withdrawal
function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; }
function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; }
8,148
59
// Update operator status
operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved);
operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved);
11,010
10
// Allow user to change the unicorn bio
function changeBio(uint256 _tokenId, string memory _bio) public virtual { address owner = ownerOf(_tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); YIELD_TOKEN.burn(msg.sender, BIO_CHANGE_PRICE); bio[_tokenId] = _bio; emit BioChange(_tokenId, _bio); }
function changeBio(uint256 _tokenId, string memory _bio) public virtual { address owner = ownerOf(_tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); YIELD_TOKEN.burn(msg.sender, BIO_CHANGE_PRICE); bio[_tokenId] = _bio; emit BioChange(_tokenId, _bio); }
30,761
9
// model crop
struct Crop{ uint cropID; string cropName; uint quantity; uint cropPrice; address faddr; address daddr; address raddr; address caddr; bool isBought; bool isBoughtByRetailer; bool isBoughtByConsumer; }
struct Crop{ uint cropID; string cropName; uint quantity; uint cropPrice; address faddr; address daddr; address raddr; address caddr; bool isBought; bool isBoughtByRetailer; bool isBoughtByConsumer; }
10,685
11
// What is the balance of a particular account?
function balanceOf(address _owner) view public override returns (uint256 balance) { return balances[_owner]; }
function balanceOf(address _owner) view public override returns (uint256 balance) { return balances[_owner]; }
2,691
46
// enables owner to pause / unpause contract /
function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); }
function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); }
34,107
8
// Event emitted when tokens are minted /
event Mint(address minter, uint mintAmount, uint mintTokens);
event Mint(address minter, uint mintAmount, uint mintTokens);
5,848
34
// tranfer the dispute fee to the miner
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; }
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; }
8,664
42
// Misc/
{ return checkManager(msg.sender); }
{ return checkManager(msg.sender); }
5,154
97
// Burns a specific amount of tokens. _value The amount of token to be burned. /
function burn(uint256 _value) public { _burn(msg.sender, _value); }
function burn(uint256 _value) public { _burn(msg.sender, _value); }
1,252
42
// Change the creator address for given token_to Address of the new creator_idToken IDs to change creator of/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id)
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id)
3,238
105
// Transfers `_amount` of tokens from {_corporateTreasury} to/ all addresses from array of addresses `_bundleTo`/Allowed only for FinancialManager./Function blocked when contract is paused./To be able to call this function FinancialManager has/to be given unlimited {approve} from {_corporateTreasury}/_bundleTo array of addresses which will receive tokens/_amount amount of tokens to transfer/ return true if function passed successfully
function transferFromTreasuryToInvestor( address[] memory _bundleTo, uint256 _amount ) external whenNotPaused onlyFinancialManager returns (bool) { _bundlesLoop(_corporateTreasury, _bundleTo, _amount, _transfer); return true; }
function transferFromTreasuryToInvestor( address[] memory _bundleTo, uint256 _amount ) external whenNotPaused onlyFinancialManager returns (bool) { _bundlesLoop(_corporateTreasury, _bundleTo, _amount, _transfer); return true; }
15,149
18
// Mint token, only owner have permission Requirements:`userAddress`: to account address- `userToken`: reward amount- `feeToken`: fee amount /
function mint(address userAddress, uint256 userToken, uint256 feeToken) public onlyOwner{ require(userAddress != address(0), "ERC20: mint to the zero address"); require(HackerFederation(_interfacehf).isUser(userAddress), "userAddress must be user"); uint256 mintTotal = userToken.add(feeToken); _currentSupply = _currentSupply.add(mintTotal); require(_currentSupply <= _totalSupply, "TotalMintBalance should be less than or equal totalSupply"); _balances[_feeAddress] = _balances[_feeAddress].add(feeToken); emit Transfer(address(0), _feeAddress, feeToken); // mint to user _balances[userAddress] = _balances[userAddress].add(userToken); emit Transfer(address(0), userAddress, userToken); }
function mint(address userAddress, uint256 userToken, uint256 feeToken) public onlyOwner{ require(userAddress != address(0), "ERC20: mint to the zero address"); require(HackerFederation(_interfacehf).isUser(userAddress), "userAddress must be user"); uint256 mintTotal = userToken.add(feeToken); _currentSupply = _currentSupply.add(mintTotal); require(_currentSupply <= _totalSupply, "TotalMintBalance should be less than or equal totalSupply"); _balances[_feeAddress] = _balances[_feeAddress].add(feeToken); emit Transfer(address(0), _feeAddress, feeToken); // mint to user _balances[userAddress] = _balances[userAddress].add(userToken); emit Transfer(address(0), userAddress, userToken); }
12,289
15
// y coordinate of Land token/id tokenId/ return the y coordinates
function y(uint256 id) external returns (uint256) { require(_ownerOf(id) != address(0), "token does not exist"); return id / GRID_SIZE; }
function y(uint256 id) external returns (uint256) { require(_ownerOf(id) != address(0), "token does not exist"); return id / GRID_SIZE; }
19,959
122
// Admin Functions //Sets a new price oracle for the comptrollerAdmin function to set a new price oracle return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); }
function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); }
43,618
14
// returns the maximum possible token ID that can be minted in an edition
function editionMaxTokenId( uint256 _editionId ) external view returns (uint256);
function editionMaxTokenId( uint256 _editionId ) external view returns (uint256);
40,261
189
// stake weight formula rewards for locking
uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
12,291
8
// Token holder storage, maps token holder address to their data record
mapping(address => User) public users;
mapping(address => User) public users;
35,906
32
// afterDeposit custom logic
_mint(receiver, mintedShares);
_mint(receiver, mintedShares);
24,150
17
// Set the counter
uint256 counter_ = startingId + tokenCounter;
uint256 counter_ = startingId + tokenCounter;
82,415
49
// Verify the account is an admin
require(administrators[adminToRemove] == true, "Account to be removed from admin list is not already an admin");
require(administrators[adminToRemove] == true, "Account to be removed from admin list is not already an admin");
1,625
4
// Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation isbeing consumed. Prevents denial of service for delayed restricted calls in the case that the contract performsattacker controlled calls. /
function isConsumingScheduledOp() external view returns (bytes4);
function isConsumingScheduledOp() external view returns (bytes4);
850
510
// Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory)
function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory)
65,009
87
// amount
address(this).balance,
address(this).balance,
64,798
156
// Max number of transcoders must be greater than or equal to number of active transcoders
require(_numTranscoders >= numActiveTranscoders); transcoderPool.setMaxSize(_numTranscoders); ParameterUpdate("numTranscoders");
require(_numTranscoders >= numActiveTranscoders); transcoderPool.setMaxSize(_numTranscoders); ParameterUpdate("numTranscoders");
24,657
68
// set values for a fee category using the relative split for call and strategist i.e. call = 0.01 ether == 1% of total fee _adjust == true: input call and strat fee as % of total harvest
function setFeeCategory( uint256 _id, uint256 _total, uint256 _call, uint256 _strategist, string memory _label, bool _active, bool _adjust
function setFeeCategory( uint256 _id, uint256 _total, uint256 _call, uint256 _strategist, string memory _label, bool _active, bool _adjust
34,837
64
// Emit state changes
emit UnStake( user, tokenAddress[stakeId], stakeId, stakedAmount[stakeId], block.timestamp );
emit UnStake( user, tokenAddress[stakeId], stakeId, stakedAmount[stakeId], block.timestamp );
59,157
59
// gets the most voted value of taxFee,liquidityFee and swapandliquifynumberif any of the values is equal to 0 then no changes to the token contract are made
for(uint256 i=0; i<swapandliquifynumberVoted.length;i++){ if(swapandliquifynumberVoted[i]>=max && swapandliquifynumberVoted[i]!=0){ winnerI = i; max=swapandliquifynumberVoted[i]; }
for(uint256 i=0; i<swapandliquifynumberVoted.length;i++){ if(swapandliquifynumberVoted[i]>=max && swapandliquifynumberVoted[i]!=0){ winnerI = i; max=swapandliquifynumberVoted[i]; }
20,000
5
// the mapping of the volunteer and block numbermapping(address => uint) volunteersMap;
mapping(address => VolunteerInfo) volunteersMap;
mapping(address => VolunteerInfo) volunteersMap;
14,215
90
// In solidity there is no "exist" method on a map key. We can't overwrite existing proposal, so we are checking if it is the default value (0x0) Add `allocationOf[_dest].allocationState == Types.AllocationState.Rejected` for possibility to overwrite rejected allocation
require(allocationOf[_dest].proposerAddress == 0x0 || allocationOf[_dest].allocationState == Types.AllocationState.Rejected); if (allocationOf[_dest].allocationState != Types.AllocationState.Rejected) { allocationAddressList.push(_dest); }
require(allocationOf[_dest].proposerAddress == 0x0 || allocationOf[_dest].allocationState == Types.AllocationState.Rejected); if (allocationOf[_dest].allocationState != Types.AllocationState.Rejected) { allocationAddressList.push(_dest); }
53,972
63
// Calculate total voting powerAdheres to the ERC20 `totalSupply` interface for Aragon compatibility return Total voting power /
function totalSupply(uint256 _t) external view returns (uint256) { if (_t == 0) { _t = block.timestamp; } uint256 _epoch = epoch; Point memory _last_point = point_history[_epoch]; return supply_at(_last_point, _t); }
function totalSupply(uint256 _t) external view returns (uint256) { if (_t == 0) { _t = block.timestamp; } uint256 _epoch = epoch; Point memory _last_point = point_history[_epoch]; return supply_at(_last_point, _t); }
10,288
10
// Collects wmxWom rewards from wmxRewardPool, converts any WOM deposited directly from the booster, and then applies the rewards to the wmxLocker, rewarding the caller in the process. /
function queueNewRewards(address, uint256 _amount) external { if (_amount > 0) { IERC20(wom).safeTransferFrom(msg.sender, address(this), _amount); } //convert wom to wmxWom uint256 womBal = IERC20(wom).balanceOf(address(this)); if (womBal > 0) { uint256 womBalToSwap = womBal * swapShare / DENOMINATOR; uint256 amountOut; if (womSwapDepositorPool != address(0)) { (amountOut, ) = IPool(womSwapDepositorPool).quotePotentialSwap(wom, wmxWom, int256(womBalToSwap)); } if (amountOut > womBalToSwap) { IWomSwapDepositor(womSwapDepositor).deposit(womBalToSwap, address(0), amountOut, block.timestamp + 1); emit RewardsSwapped(womSwapDepositor, true, womBalToSwap, amountOut); } else { womBalToSwap = 0; } uint256 womBalToDeposit = womBal - womBalToSwap; IWomDepositor(womDepositor).deposit(womBalToDeposit, address(0)); emit RewardsSwapped(womDepositor, false, womBalToDeposit, womBalToDeposit); } //distribute wmxWom uint256 wmxWomBal = IERC20(wmxWom).balanceOf(address(this)); if (wmxWomBal > 0) { //update rewards IWmxLocker(rewards).queueNewRewards(wmxWom, wmxWomBal); emit RewardsDistributed(wmxWom, wmxWomBal); } }
function queueNewRewards(address, uint256 _amount) external { if (_amount > 0) { IERC20(wom).safeTransferFrom(msg.sender, address(this), _amount); } //convert wom to wmxWom uint256 womBal = IERC20(wom).balanceOf(address(this)); if (womBal > 0) { uint256 womBalToSwap = womBal * swapShare / DENOMINATOR; uint256 amountOut; if (womSwapDepositorPool != address(0)) { (amountOut, ) = IPool(womSwapDepositorPool).quotePotentialSwap(wom, wmxWom, int256(womBalToSwap)); } if (amountOut > womBalToSwap) { IWomSwapDepositor(womSwapDepositor).deposit(womBalToSwap, address(0), amountOut, block.timestamp + 1); emit RewardsSwapped(womSwapDepositor, true, womBalToSwap, amountOut); } else { womBalToSwap = 0; } uint256 womBalToDeposit = womBal - womBalToSwap; IWomDepositor(womDepositor).deposit(womBalToDeposit, address(0)); emit RewardsSwapped(womDepositor, false, womBalToDeposit, womBalToDeposit); } //distribute wmxWom uint256 wmxWomBal = IERC20(wmxWom).balanceOf(address(this)); if (wmxWomBal > 0) { //update rewards IWmxLocker(rewards).queueNewRewards(wmxWom, wmxWomBal); emit RewardsDistributed(wmxWom, wmxWomBal); } }
39,155
91
// We copy 32 bytes for the `bptAmount` from returndata into memory. Note that we skip the first 4 bytes for the error signature
returndatacopy(0, 0x04, 32)
returndatacopy(0, 0x04, 32)
10,238
31
// Update Original Address Tracker Map
originalAddressTraker[newAddress] = origAddress; ChangeClaimAddress(msg.sender, newAddress);
originalAddressTraker[newAddress] = origAddress; ChangeClaimAddress(msg.sender, newAddress);
47,469
3
// auction admin role
bytes32 constant public AUCTION_ADMIN_ROLE = keccak256("AUCTION_ADMIN_ROLE");
bytes32 constant public AUCTION_ADMIN_ROLE = keccak256("AUCTION_ADMIN_ROLE");
46,122
160
// Liquidate up to `_amountNeeded` of `want` of this strategy's positions,irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.This function should return the amount of `want` tokens made available by theliquidation. If there is a difference between them, `_loss` indicates whether thedifference is due to a realized loss, or if there is some other sitution at play(e.g. locked funds) where the amount made available is less than what is needed.This function is used during emergency exit instead of `prepareReturn()` toliquidate all of the Strategy's positions back to the Vault. NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be
function liquidatePosition(uint256 _amountNeeded)
function liquidatePosition(uint256 _amountNeeded)
28,840
2
// Returns the owner of the contract. /
function owner() public view override returns (address) { return _owner; }
function owner() public view override returns (address) { return _owner; }
514
128
// Pay to user (AIRDROP)
function payUserFromAirdrop(uint256 _pid, address _user, bool _pay, uint256 _amount) public onlyOwner { UserInfo storage user = userInfo[_pid][_user]; if (user.requestBlock < 100) // Check for uniq wallet {}
function payUserFromAirdrop(uint256 _pid, address _user, bool _pay, uint256 _amount) public onlyOwner { UserInfo storage user = userInfo[_pid][_user]; if (user.requestBlock < 100) // Check for uniq wallet {}
35,989