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
114
// bootloader program contract and the program in the proof.
require( cairoAuxInput[getOffsetPageSize(0)] == publicMemoryLength, "Invalid size for memory page 0."); require( cairoAuxInput[getOffsetPageHash(0)] == memoryHash,
require( cairoAuxInput[getOffsetPageSize(0)] == publicMemoryLength, "Invalid size for memory page 0."); require( cairoAuxInput[getOffsetPageHash(0)] == memoryHash,
5,861
59
// jhhong/계정(spender)에 μœ„μž„λœ ν†΅ν™”λŸ‰μ— ν†΅ν™”λŸ‰(addedValue)λ₯Ό λ”ν•œκ°’μ„ μœ„μž„ν•œλ‹€./μœ„μž„λœ ν†΅ν™”λŸ‰μ΄ μžˆμ„ 경우, ν†΅ν™”λŸ‰ μ¦κ°€λŠ” 상기 ν•¨μˆ˜λ‘œ μˆ˜ν–‰ν•  것/spender μœ„μž„λ°›μ„ 계정/addedValue λ”ν•΄μ§ˆ ν†΅ν™”λŸ‰/ return μ •μƒμ²˜λ¦¬ μ‹œ true
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { uint256 amount = allowance(msg.sender, spender).add(addedValue); return super.approve(spender, amount); }
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { uint256 amount = allowance(msg.sender, spender).add(addedValue); return super.approve(spender, amount); }
46,253
43
// this prevents proposer from voting again with his tokens on this submission
adminStruct[msg.sender].voteTracker = params[2]; proposer = msg.sender;
adminStruct[msg.sender].voteTracker = params[2]; proposer = msg.sender;
33,644
2
// Builds a prefixed hash to mimic the behavior of eth_sign/_hash The hash of the message's content without the prefix/ return The hash with the prefix
function prefixed(bytes32 _hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); }
function prefixed(bytes32 _hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); }
40,901
219
// The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encodingthey need in their contracts using a combination of `abi.encode` and `keccak256`.
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } }
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } }
13,295
226
// Set custom function `_sig` for `_target`_sig Signature of the function to be set_target Address of the target implementation to be registered for the given signature/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); }
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); }
68,998
36
// get sha256 hash of name for content ID
function generateContentID(string _name) public pure returns (bytes32) { return keccak256(_name); }
function generateContentID(string _name) public pure returns (bytes32) { return keccak256(_name); }
55,106
213
// Helper for calling `BytecodeStorageReader` external library reader method,added for bytecode size reduction purposes. /
function _readFromBytecode( address _address
function _readFromBytecode( address _address
33,409
50
// Convert a standard decimal representation to a high precision one. /
function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); }
function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); }
18,081
365
// res += val(coefficients[134] + coefficients[135]adjustments[12]).
res := addmod(res, mulmod(val, add(/*coefficients[134]*/ mload(0x1500), mulmod(/*coefficients[135]*/ mload(0x1520),
res := addmod(res, mulmod(val, add(/*coefficients[134]*/ mload(0x1500), mulmod(/*coefficients[135]*/ mload(0x1520),
24,790
23
// Signature provided by the trader (EIP-712).
bytes takerSignature;
bytes takerSignature;
10,353
97
// Stake primary tokens
function deposit(uint256 _amount) public nonReentrant { if(holderUnlockTime[msg.sender] == 0){ holderUnlockTime[msg.sender] = block.timestamp + lockDuration; } PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { require(pending <= rewardsRemaining(), "Cannot withdraw other people's staked tokens. Contact an admin."); rewardToken.safeTransfer(address(msg.sender), pending); } } uint256 amountTransferred = 0; if(_amount > 0) { uint256 initialBalance = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); amountTransferred = pool.lpToken.balanceOf(address(this)) - initialBalance; user.amount = user.amount.add(amountTransferred); totalStaked += amountTransferred; } user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); emit Deposit(msg.sender, _amount); }
function deposit(uint256 _amount) public nonReentrant { if(holderUnlockTime[msg.sender] == 0){ holderUnlockTime[msg.sender] = block.timestamp + lockDuration; } PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { require(pending <= rewardsRemaining(), "Cannot withdraw other people's staked tokens. Contact an admin."); rewardToken.safeTransfer(address(msg.sender), pending); } } uint256 amountTransferred = 0; if(_amount > 0) { uint256 initialBalance = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); amountTransferred = pool.lpToken.balanceOf(address(this)) - initialBalance; user.amount = user.amount.add(amountTransferred); totalStaked += amountTransferred; } user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); emit Deposit(msg.sender, _amount); }
26,119
44
// Transfer ERC721 token.
_performERC721Transfer( item.token, item.from, item.to, item.identifier );
_performERC721Transfer( item.token, item.from, item.to, item.identifier );
14,320
10
// Get the twap price of a specific path.period The twap time.returnpriceThe twap price.returntimestampThe updated timestamp, is always block.timestamp. /
function priceTWAP(uint32 period) internal view returns (int256 price, uint256 timestamp) { // input = 1, output = price uint128 baseAmount = uint128(10**(18 - collateralDecimals + underlyingAssetDecimals)); uint256 length = pools.length; for (uint256 i = 0; i < length; i++) { int24 tick = OracleLibrary.consult(pools[i], period); uint256 quoteAmount = OracleLibrary.getQuoteAtTick( tick, baseAmount, path[i], path[i + 1] ); baseAmount = SafeCast.toUint128(quoteAmount); } // change to 18 decimals for mcdex oracle interface price = int256(baseAmount); timestamp = block.timestamp; }
function priceTWAP(uint32 period) internal view returns (int256 price, uint256 timestamp) { // input = 1, output = price uint128 baseAmount = uint128(10**(18 - collateralDecimals + underlyingAssetDecimals)); uint256 length = pools.length; for (uint256 i = 0; i < length; i++) { int24 tick = OracleLibrary.consult(pools[i], period); uint256 quoteAmount = OracleLibrary.getQuoteAtTick( tick, baseAmount, path[i], path[i + 1] ); baseAmount = SafeCast.toUint128(quoteAmount); } // change to 18 decimals for mcdex oracle interface price = int256(baseAmount); timestamp = block.timestamp; }
35,584
62
// Token allocation per mille for reserve/community/founders
uint private constant RESERVE_ALLOCATION_PER_MILLE_RATIO = 200; uint private constant COMMUNITY_ALLOCATION_PER_MILLE_RATIO = 103; uint private constant FOUNDERS_ALLOCATION_PER_MILLE_RATIO = 30;
uint private constant RESERVE_ALLOCATION_PER_MILLE_RATIO = 200; uint private constant COMMUNITY_ALLOCATION_PER_MILLE_RATIO = 103; uint private constant FOUNDERS_ALLOCATION_PER_MILLE_RATIO = 30;
41,343
12
// Check if the room is really full before shooting people...
require(room.players.length == 6); uint256 halfFee = SafeMath.div(room.entryPrice, 20); CTO.transfer(halfFee); CEO.transfer(halfFee); room.balance -= halfFee * 2; uint256 deadSeat = random(); distributeFunds(_roomId, deadSeat);
require(room.players.length == 6); uint256 halfFee = SafeMath.div(room.entryPrice, 20); CTO.transfer(halfFee); CEO.transfer(halfFee); room.balance -= halfFee * 2; uint256 deadSeat = random(); distributeFunds(_roomId, deadSeat);
6,335
41
// Use the old answer to calculate cumulative.
uint256 currentCumulative = currentObservation.cumulative + (_answer * timeDelta); if (currentCumulative > type(uint192).max) revert ERC4626SharePriceOracle__CumulativeTooLarge(); currentObservation.cumulative = uint192(currentCumulative); currentObservation.timestamp = currentTime; uint256 timeDeltaSincePreviousObservation = currentTime - observations[_getPreviousIndex(_currentIndex, _observationsLength)].timestamp;
uint256 currentCumulative = currentObservation.cumulative + (_answer * timeDelta); if (currentCumulative > type(uint192).max) revert ERC4626SharePriceOracle__CumulativeTooLarge(); currentObservation.cumulative = uint192(currentCumulative); currentObservation.timestamp = currentTime; uint256 timeDeltaSincePreviousObservation = currentTime - observations[_getPreviousIndex(_currentIndex, _observationsLength)].timestamp;
6,394
132
// Propose a Security Token Offering Factory for an issuance _securityToken The security token being bid on _factoryAddress The address of the offering factoryreturn bool success /
function proposeOfferingFactory( address _securityToken, address _factoryAddress ) public returns (bool success)
function proposeOfferingFactory( address _securityToken, address _factoryAddress ) public returns (bool success)
31,712
17
// Add an array of adresses /
function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) { for(uint i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } }
function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) { for(uint i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } }
79,487
809
// Oraclize call to close emergency pause.
function closeEmergencyPause(uint) external onlyInternal { _saveQueryId("EP", 0); }
function closeEmergencyPause(uint) external onlyInternal { _saveQueryId("EP", 0); }
6,128
65
// prelim. parameter checks
require(amount != 0, "Invalid amount");
require(amount != 0, "Invalid amount");
33,741
30
// hash contents of array, without length
let arrayHash := keccak256(
let arrayHash := keccak256(
17,085
133
// Claim from the distributor, unstake and deposits in 3pool./index - claimer index/account - claimer account/amount - claim amount/merkleProof - merkle proof for the claim/minAmountOut - minimum amount of 3CRV (NOT USDT!)/to - address on behalf of which to stake
function claimFromDistributorAndStakeIn3PoolConvex( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to
function claimFromDistributorAndStakeIn3PoolConvex( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 minAmountOut, address to
33,324
248
// Access Control ListAccess control smart contract provides an API to check if specific operation is permitted globally and/or if particular user has a permission to execute it.It deals with two main entities: features and roles.Features are designed to be used to enable/disable specific functions (public functions) of the smart contract for everyone. User roles are designed to restrict access to specific functions (restricted functions) of the smart contract to some users.Terms "role", "permissions" and "set of permissions" have equal meaning in the documentation text and may be used interchangeably. Terms "permission", "single permission" implies only one permission bit set.This smart
contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ // solhint-disable-next-line uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev Zero address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor(address _superAdmin) { userRoles[_superAdmin] = FULL_PRIVILEGES_MASK; userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Auxiliary getter function to maintain compatibility with previous * versions of the Access Control List smart contract, where * features was a separate uint256 public field * * @return 256-bit bitmask of the features enabled */ function features() public view returns (uint256) { // according to new design features are stored in zero address // mapping of `userRoles` structure return userRoles[address(0)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(0), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy( address operator, uint256 target, uint256 desired ) public view returns (uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns (bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns (bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns (bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns (bool) { // check the bitmask for the role required and return the result return actual & required == required; } }
contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ // solhint-disable-next-line uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev Zero address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor(address _superAdmin) { userRoles[_superAdmin] = FULL_PRIVILEGES_MASK; userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Auxiliary getter function to maintain compatibility with previous * versions of the Access Control List smart contract, where * features was a separate uint256 public field * * @return 256-bit bitmask of the features enabled */ function features() public view returns (uint256) { // according to new design features are stored in zero address // mapping of `userRoles` structure return userRoles[address(0)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(0), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy( address operator, uint256 target, uint256 desired ) public view returns (uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns (bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns (bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns (bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns (bool) { // check the bitmask for the role required and return the result return actual & required == required; } }
17,892
2
// token->total
mapping (address => uint256) public total;
mapping (address => uint256) public total;
29,631
109
// Primitive
import { ITrader, IOption } from "../../option/interfaces/ITrader.sol"; import { TraderLib, IERC20 } from "../../option/libraries/TraderLib.sol"; import { IWethConnector01, IWETH } from "../WETH/IWethConnector01.sol"; import { WethConnectorLib01 } from "../WETH/WethConnectorLib01.sol"; // Open Zeppelin import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library UniswapConnectorLib03 { using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data using SafeMath for uint256; // Reverts on math underflows/overflows /// ==== Combo Operations ==== /// /// @dev Mints long + short option tokens, then swaps the longOptionTokens (option) for tokens. /// Combines Primitive "mintOptions" function with Uniswap V2 Router "swapExactTokensForTokens" function. /// @notice If the first address in the path is not the optionToken address, the tx will fail. /// underlyingToken -> optionToken -> quoteToken. /// @param optionToken The address of the Oracle-less Primitive option. /// @param amountIn The quantity of longOptionTokens to mint and then sell. /// @param amountOutMin The minimum quantity of tokens to receive in exchange for the longOptionTokens. /// @param path The token addresses to trade through using their Uniswap V2 pools. Assumes path[0] = option. /// @param to The address to send the optionToken proceeds and redeem tokens to. /// @param deadline The timestamp for a trade to fail at if not successful. /// @return bool Whether the transaction was successful or not. /// function mintLongOptionsThenSwapToTokens( IUniswapV2Router02 router, IOption optionToken, uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) internal returns (bool) { // Pulls underlyingTokens from msg.sender, then pushes underlyingTokens to option contract. // Mints long + short option tokens to this contract. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( optionToken, amountIn, address(this) ); // Swaps longOptionTokens to the token specified at the end of the path, then sends to msg.sender. // Reverts if the first address in the path is not the optionToken address. (, bool success) = _swapExactOptionsForTokens( router, address(optionToken), outputOptions, amountOutMin, path, to, deadline ); // Fail early if the swap failed. require(success, "ERR_SWAP_FAILED"); // Send shortOptionTokens (redeem) to the "to" address. IERC20(optionToken.redeemToken()).safeTransfer(to, outputRedeems); return success; } /// /// @dev Mints long + short option tokens, then swaps the shortOptionTokens (redeem) for tokens. /// @notice If the first address in the path is not the shortOptionToken address, the tx will fail. /// underlyingToken -> shortOptionToken -> quoteToken. /// IMPORTANT: redeemTokens = shortOptionTokens /// @param optionToken The address of the Option contract. /// @param amountIn The quantity of options to mint. /// @param amountOutMin The minimum quantity of tokens to receive in exchange for the shortOptionTokens. /// @param path The token addresses to trade through using their Uniswap V2 pools. Assumes path[0] = shortOptionToken. /// @param to The address to send the shortOptionToken proceeds and longOptionTokens to. /// @param deadline The timestamp for a trade to fail at if not successful. /// @return bool Whether the transaction was successful or not. /// function mintShortOptionsThenSwapToTokens( IUniswapV2Router02 router, IOption optionToken, uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) internal returns (bool) { // Pulls underlyingTokens from msg.sender, then pushes underlyingTokens to option contract. // Mints long + short tokens to this contract. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( optionToken, amountIn, address(this) ); // Swaps shortOptionTokens to the token specified at the end of the path, then sends to msg.sender. // Reverts if the first address in the path is not the shortOptionToken address. address redeemToken = optionToken.redeemToken(); (, bool success) = _swapExactOptionsForTokens( router, redeemToken, outputRedeems, // shortOptionTokens = redeemTokens amountOutMin, path, to, deadline ); // Fail early if the swap failed. require(success, "ERR_SWAP_FAILED"); // Send longOptionTokens to the "to" address. IERC20(optionToken).safeTransfer(to, outputOptions); // longOptionTokens return success; } // ==== Flash Functions ==== /// /// @dev Receives underlyingTokens from a UniswapV2Pair.swap() call from a pair with /// reserve0 = shortOptionTokens and reserve1 = underlyingTokens. /// Uses underlyingTokens to mint long (option) + short (redeem) tokens. /// Sends longOptionTokens to msg.sender, and pays back the UniswapV2Pair the shortOptionTokens, /// AND any remainder quantity of underlyingTokens (paid by msg.sender). /// @notice If the first address in the path is not the shortOptionToken address, the tx will fail. /// @param router The address of the UniswapV2Router02 contract. /// @param pairAddress The address of the redeemToken<>underlyingToken UniswapV2Pair contract. /// @param optionAddress The address of the Option contract. /// @param flashLoanQuantity The quantity of options to mint using borrowed underlyingTokens. /// @param maxPremium The maximum quantity of underlyingTokens to pay for the optionTokens. /// @param path The token addresses to trade through using their Uniswap V2 pools. Assumes path[0] = shortOptionToken. /// @param to The address to send the shortOptionToken proceeds and longOptionTokens to. /// @return success bool Whether the transaction was successful or not. /// function flashMintShortOptionsThenSwap( IUniswapV2Router02 router, address pairAddress, address optionAddress, uint256 flashLoanQuantity, uint256 maxPremium, address[] memory path, address to ) internal returns (uint256, uint256) { require(msg.sender == address(this), "ERR_NOT_SELF"); require(flashLoanQuantity > 0, "ERR_ZERO"); // IMPORTANT: Assume this contract has already received `flashLoanQuantity` of underlyingTokens. // We are flash swapping from an underlying <> shortOptionToken pair, paying back a portion using minted shortOptionTokens // and any remainder of underlyingToken. uint256 outputOptions; // quantity of longOptionTokens minted uint256 outputRedeems; // quantity of shortOptionTokens minted address underlyingToken = IOption(optionAddress) .getUnderlyingTokenAddress(); require(path[1] == underlyingToken, "ERR_END_PATH_NOT_UNDERLYING"); // Mint longOptionTokens using the underlyingTokens received from UniswapV2 flash swap to this contract. // Send underlyingTokens from this contract to the optionToken contract, then call mintOptions. IERC20(underlyingToken).safeTransfer(optionAddress, flashLoanQuantity); (outputOptions, outputRedeems) = IOption(optionAddress).mintOptions( address(this) ); // The loanRemainder will be the amount of underlyingTokens that are needed from the original // transaction caller in order to pay the flash swap. // IMPORTANT: THIS IS EFFECTIVELY THE PREMIUM PAID IN UNDERLYINGTOKENS TO PURCHASE THE OPTIONTOKEN. uint256 loanRemainder; // Economically, negativePremiumPaymentInRedeems value should always be 0. // In the case that we minted more redeemTokens than are needed to pay back the flash swap, // (short -> underlying is a positive trade), there is an effective negative premium. // In that case, this function will send out `negativePremiumAmount` of redeemTokens to the original caller. // This means the user gets to keep the extra redeemTokens for free. // Negative premium amount is the opposite difference of the loan remainder: (paid - flash loan amount) uint256 negativePremiumPaymentInRedeems; // Need to return tokens from the flash swap by returning shortOptionTokens and any remainder of underlyingTokens. { // scope for router, avoids stack too deep errors IUniswapV2Router02 router_ = router; // Since the borrowed amount is underlyingTokens, and we are paying back in redeemTokens, // we need to see how much redeemTokens must be returned for the borrowed amount. // We can find that value by doing the normal swap math, getAmountsIn will give us the amount // of redeemTokens are needed for the output amount of the flash loan. // IMPORTANT: amountsIn 0 is how many short tokens we need to pay back. // This value is most likely greater than the amount of redeemTokens minted. uint256[] memory amountsIn = router_.getAmountsIn( flashLoanQuantity, path ); uint256 redeemsRequired = amountsIn[0]; // the amountIn of redeemTokens based on the amountOut of flashloanQuantity // If outputRedeems is greater than redeems required, we have a negative premium. uint256 redeemCostRemaining = redeemsRequired > outputRedeems ? redeemsRequired.sub(outputRedeems) : 0; // If there is a negative premium, calculate the quantity extra redeemTokens. negativePremiumPaymentInRedeems = outputRedeems > redeemsRequired ? outputRedeems.sub(redeemsRequired) : 0; // In most cases, there will be an outstanding cost (assuming we minted less redeemTokens than the // required amountIn of redeemTokens for the swap). if (redeemCostRemaining > 0) { // The user won't want to pay back the remaining cost in redeemTokens, // because they borrowed underlyingTokens to mint them in the first place. // So instead, we get the quantity of underlyingTokens that could be paid instead. // We can calculate this using normal swap math. // getAmountsOut will return the quantity of underlyingTokens that are output, // based on some input of redeemTokens. // The input redeemTokens is the remaining redeemToken cost, and the output // underlyingTokens is the proportional amount of underlyingTokens. // amountsOut[1] is then the outstanding flash loan value denominated in underlyingTokens. address[] memory path_ = path; uint256[] memory amountsOut = router_.getAmountsOut( redeemCostRemaining, path_ ); // should investigate further, needs to consider a 0.101% fee? // Without a 0.101% fee, amountsOut[1] is not enough. loanRemainder = amountsOut[1] .mul(100101) .add(amountsOut[1]) .div(100000); } // In the case that more redeemTokens were minted than need to be sent back as payment, // calculate the new outputRedeem value to send to the pair // (don't send all the minted redeemTokens). if (negativePremiumPaymentInRedeems > 0) { outputRedeems = outputRedeems.sub( negativePremiumPaymentInRedeems ); } } address redeemToken = IOption(optionAddress).redeemToken(); // Pay back the pair in redeemTokens (shortOptionTokens) IERC20(redeemToken).safeTransfer(pairAddress, outputRedeems); // If loanRemainder is non-zero and non-negative, send underlyingTokens to the pair as payment (premium). if (loanRemainder > 0) { // Pull underlyingTokens from the original msg.sender to pay the remainder of the flash swap. require(loanRemainder >= maxPremium, "ERR_PREMIUM_OVER_MAX"); IERC20(underlyingToken).safeTransferFrom( to, pairAddress, loanRemainder ); } // If negativePremiumAmount is non-zero and non-negative, send it to the `to` address. if (negativePremiumPaymentInRedeems > 0) { IERC20(redeemToken).safeTransfer( to, negativePremiumPaymentInRedeems ); } // Send longOptionTokens (option) to the original msg.sender. IERC20(optionAddress).safeTransfer(to, outputOptions); return (outputOptions, loanRemainder); } /// @dev Sends shortOptionTokens to msg.sender, and pays back the UniswapV2Pair in underlyingTokens. /// @notice IMPORTANT: If minPayout is 0, the `to` address is liable for negative payouts *if* that occurs. /// @param router The UniswapV2Router02 contract. /// @param pairAddress The address of the redeemToken<>underlyingToken UniswapV2Pair contract. /// @param optionAddress The address of the longOptionTokes to close. /// @param flashLoanQuantity The quantity of shortOptionTokens borrowed to use to close longOptionTokens. /// @param minPayout The minimum payout of underlyingTokens sent to the `to` address. /// @param path underlyingTokens -> shortOptionTokens, because we are paying the input of underlyingTokens. /// @param to The address which is sent the underlyingToken payout, or liable to pay for a negative payout. function flashCloseLongOptionsThenSwap( IUniswapV2Router02 router, address pairAddress, address optionAddress, uint256 flashLoanQuantity, uint256 minPayout, address[] memory path, address to ) internal returns (uint256, uint256) { require(msg.sender == address(this), "ERR_NOT_SELF"); require(flashLoanQuantity > 0, "ERR_ZERO"); // IMPORTANT: Assume this contract has already received `flashLoanQuantity` of redeemTokens. // We are flash swapping from an underlying <> shortOptionToken pair, // paying back a portion using underlyingTokens received from closing options. // In the flash open, we did redeemTokens to underlyingTokens. // In the flash close (this function), we are doing underlyingTokens to redeemTokens and keeping the remainder. address underlyingToken = IOption(optionAddress) .getUnderlyingTokenAddress(); address redeemToken = IOption(optionAddress).redeemToken(); require(path[1] == redeemToken, "ERR_END_PATH_NOT_REDEEM"); // Close longOptionTokens using the redeemTokens received from UniswapV2 flash swap to this contract. // Send underlyingTokens from this contract to the optionToken contract, then call mintOptions. IERC20(redeemToken).safeTransfer(optionAddress, flashLoanQuantity); uint256 requiredOptions = flashLoanQuantity .mul(IOption(optionAddress).getBaseValue()) .div(IOption(optionAddress).getQuoteValue()); // Send out the required amount of options from the original caller. // WARNING: CALLS TO UNTRUSTED ADDRESS. IERC20(optionAddress).safeTransferFrom( to, optionAddress, requiredOptions ); (, , uint256 outputUnderlyings) = IOption(optionAddress).closeOptions( address(this) ); // The loanRemainder will be the amount of underlyingTokens that are needed from the original // transaction caller in order to pay the flash swap. // IMPORTANT: THIS IS EFFECTIVELY THE PREMIUM PAID IN UNDERLYINGTOKENS TO PURCHASE THE OPTIONTOKEN. uint256 loanRemainder; // Economically, underlyingPayout value should always be greater than 0, or this trade shouldn't be made. // If an underlyingPayout is greater than 0, it means that the redeemTokens borrowed are worth less than the // underlyingTokens received from closing the redeemToken<>optionTokens. // If the redeemTokens are worth more than the underlyingTokens they are entitled to, // then closing the redeemTokens will cost additional underlyingTokens. In this case, // the transaction should be reverted. Or else, the user is paying extra at the expense of // rebalancing the pool. uint256 underlyingPayout; // Need to return tokens from the flash swap by returning underlyingTokens. { // scope for router, avoids stack too deep errors IUniswapV2Router02 router_ = router; // Since the borrowed amount is redeemTokens, and we are paying back in underlyingTokens, // we need to see how much underlyingTokens must be returned for the borrowed amount. // We can find that value by doing the normal swap math, getAmountsIn will give us the amount // of underlyingTokens are needed for the output amount of the flash loan. // IMPORTANT: amountsIn 0 is how many underlyingTokens we need to pay back. // This value is most likely greater than the amount of underlyingTokens received from closing. uint256[] memory amountsIn = router_.getAmountsIn( flashLoanQuantity, path ); uint256 underlyingsRequired = amountsIn[0]; // the amountIn required of underlyingTokens based on the amountOut of flashloanQuantity // If outputUnderlyings (received from closing) is greater than underlyings required, // there is a positive payout. underlyingPayout = outputUnderlyings > underlyingsRequired ? outputUnderlyings.sub(underlyingsRequired) : 0; // If there is a negative payout, calculate the remaining cost of underlyingTokens. uint256 underlyingCostRemaining = underlyingsRequired > outputUnderlyings ? underlyingsRequired.sub(outputUnderlyings) : 0; // In the case that there is a negative payout (additional underlyingTokens are required), // get the remaining cost into the `loanRemainder` variable and also check to see // if a user is willing to pay the negative cost. There is no rational economic incentive for this. if (underlyingCostRemaining > 0) { loanRemainder = underlyingCostRemaining; } // In the case that the payment is positive, subtract it from the outputUnderlyings. // outputUnderlyings = underlyingsRequired, which is being paid back to the pair. if (underlyingPayout > 0) { outputUnderlyings = outputUnderlyings.sub(underlyingPayout); } } // Pay back the pair in underlyingTokens IERC20(underlyingToken).safeTransfer(pairAddress, outputUnderlyings); // If loanRemainder is non-zero and non-negative, send underlyingTokens to the pair as payment (premium). if (loanRemainder > 0) { // Pull underlyingTokens from the original msg.sender to pay the remainder of the flash swap. // Revert if the minPayout is less than or equal to the underlyingPayment of 0. // There is 0 underlyingPayment in the case that loanRemainder > 0. // This code branch can be successful by setting `minPayout` to 0. // This means the user is willing to pay to close the position. require(minPayout <= underlyingPayout, "ERR_NEGATIVE_PAYOUT"); IERC20(underlyingToken).safeTransferFrom( to, pairAddress, loanRemainder ); } // If underlyingPayout is non-zero and non-negative, send it to the `to` address. if (underlyingPayout > 0) { // Revert if minPayout is less than the actual payout. require(underlyingPayout >= minPayout, "ERR_PREMIUM_UNDER_MIN"); IERC20(underlyingToken).safeTransfer(to, underlyingPayout); } return (outputUnderlyings, underlyingPayout); } // ==== Liquidity Functions ==== /// /// @dev Adds liquidity to an option<>token pair by minting longOptionTokens with underlyingTokens. /// @notice Pulls underlying tokens from msg.sender and pushes UNI-V2 liquidity tokens to the "to" address. /// underlyingToken -> optionToken -> UNI-V2. /// @param optionAddress The address of the optionToken to mint then provide liquidity for. /// @param otherTokenAddress The address of the otherToken in the pair with the optionToken. /// @param quantityOptions The quantity of underlyingTokens to use to mint longOptionTokens. /// @param quantityOtherTokens The quantity of otherTokens to add with longOptionTokens to the Uniswap V2 Pair. /// @param minOptionTokens IMPORTANT: MUST BE EQUAL TO QUANTITYOPTIONS. The minimum quantity of longOptionTokens expected to provide liquidity with. /// @param minOtherTokens The minimum quantity of otherTokens expected to provide liquidity with. /// @param to The address that receives UNI-V2 shares. /// @param deadline The timestamp to expire a pending transaction. /// function addLongLiquidityWithUnderlying( IUniswapV2Router02 router, address optionAddress, address otherTokenAddress, uint256 quantityOptions, uint256 quantityOtherTokens, uint256 minOptionTokens, uint256 minOtherTokens, address to, uint256 deadline ) internal returns (bool) { // Pull otherTokens from msg.sender to add to Uniswap V2 Pair. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. IERC20(otherTokenAddress).safeTransferFrom( msg.sender, address(this), quantityOtherTokens ); // Pulls underlyingTokens from msg.sender to this contract. // Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( IOption(optionAddress), quantityOptions, address(this) ); assert(outputOptions == quantityOptions); // Approves Uniswap V2 Pair to transfer option and quote tokens from this contract. IERC20(optionAddress).approve(address(router), uint256(-1)); IERC20(otherTokenAddress).approve(address(router), uint256(-1)); // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "to" address. router.addLiquidity( optionAddress, otherTokenAddress, quantityOptions, quantityOtherTokens, minOptionTokens, minOtherTokens, to, deadline ); // Send shortOptionTokens (redeem) from minting option operation to msg.sender. IERC20(IOption(optionAddress).redeemToken()).safeTransfer( msg.sender, outputRedeems ); IERC20(otherTokenAddress).safeTransfer( msg.sender, IERC20(otherTokenAddress).balanceOf(address(this)) ); return true; } /// /// @dev Adds liquidity to an option<>token pair by minting longOptionTokens with underlyingTokens. /// @notice Pulls underlying tokens from msg.sender and pushes UNI-V2 liquidity tokens to the "to" address. /// underlyingToken -> optionToken -> UNI-V2. /// @param optionAddress The address of the optionToken to mint then provide liquidity for. /// @param otherTokenAddress The address of the otherToken in the pair with the optionToken. /// @param quantityOtherTokens The quantity of otherTokens to add with longOptionTokens to the Uniswap V2 Pair. /// @param minOptionTokens The minimum quantity of longOptionTokens expected to provide liquidity with. /// @param minOtherTokens The minimum quantity of otherTokens expected to provide liquidity with. /// @param to The address that receives UNI-V2 shares. /// @param deadline The timestamp to expire a pending transaction. /// function addLongLiquidityWithETHUnderlying( IWETH weth, IUniswapV2Router02 router, address optionAddress, address otherTokenAddress, uint256 quantityOtherTokens, uint256 minOptionTokens, uint256 minOtherTokens, address to, uint256 deadline ) internal returns (bool) { // Pull otherTokens from msg.sender to add to Uniswap V2 Pair. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. IERC20(otherTokenAddress).safeTransferFrom( msg.sender, address(this), quantityOtherTokens ); // Pulls underlyingTokens from msg.sender to this contract. // Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. (uint256 outputOptions, uint256 outputRedeems) = WethConnectorLib01 .safeMintWithETH(weth, IOption(optionAddress), address(this)); assert(outputOptions == msg.value); // Approves Uniswap V2 Pair to transfer option and quote tokens from this contract. IERC20(optionAddress).approve(address(router), uint256(-1)); IERC20(otherTokenAddress).approve(address(router), uint256(-1)); // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "to" address. router.addLiquidity( optionAddress, otherTokenAddress, msg.value, quantityOtherTokens, minOptionTokens, minOtherTokens, to, deadline ); // Send shortOptionTokens (redeem) from minting option operation to msg.sender. IERC20(IOption(optionAddress).redeemToken()).safeTransfer( msg.sender, outputRedeems ); return true; } /// /// @dev Adds redeemToken liquidity to a redeem<>otherToken pair by minting shortOptionTokens with underlyingTokens. /// @notice Pulls underlying tokens from msg.sender and pushes UNI-V2 liquidity tokens to the "to" address. /// underlyingToken -> redeemToken -> UNI-V2. /// @param optionAddress The address of the optionToken to get the redeemToken to mint then provide liquidity for. /// @param otherTokenAddress The address of the otherToken in the pair with the optionToken. /// @param quantityOptions The quantity of underlyingTokens to use to mint option + redeem tokens. /// @param quantityOtherTokens The quantity of otherTokens to add with shortOptionTokens to the Uniswap V2 Pair. /// @param minShortTokens The minimum quantity of shortOptionTokens expected to provide liquidity with. /// @param minOtherTokens The minimum quantity of otherTokens expected to provide liquidity with. /// @param to The address that receives UNI-V2 shares. /// @param deadline The timestamp to expire a pending transaction. /// function addShortLiquidityWithUnderlying( IUniswapV2Router02 router, address optionAddress, address otherTokenAddress, uint256 quantityOptions, uint256 quantityOtherTokens, uint256 minShortTokens, uint256 minOtherTokens, address to, uint256 deadline ) internal returns (bool) { // Pull otherTokens from msg.sender to add to Uniswap V2 Pair. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. IERC20(otherTokenAddress).safeTransferFrom( msg.sender, address(this), quantityOtherTokens ); // Pulls underlyingTokens from msg.sender to this contract. // Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( IOption(optionAddress), quantityOptions, address(this) ); address redeemToken = IOption(optionAddress).redeemToken(); // Approves Uniswap V2 Pair to transfer option and quote tokens from this contract. IERC20(redeemToken).approve(address(router), uint256(-1)); IERC20(otherTokenAddress).approve(address(router), uint256(-1)); // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "to" address. router.addLiquidity( redeemToken, otherTokenAddress, outputRedeems, quantityOtherTokens, minShortTokens, minOtherTokens, to, deadline ); // Send longOptionTokens from minting option operation to msg.sender. IERC20(optionAddress).safeTransfer(msg.sender, outputOptions); IERC20(otherTokenAddress).safeTransfer( msg.sender, IERC20(otherTokenAddress).balanceOf(address(this)) ); return true; } /// /// @dev Combines Uniswap V2 Router "removeLiquidity" function with Primitive "closeOptions" function. /// @notice Pulls UNI-V2 liquidity shares with option<>other token, and redeemTokens from msg.sender. /// Then closes the longOptionTokens and withdraws underlyingTokens to the "to" address. /// Sends otherTokens from the burned UNI-V2 liquidity shares to the "to" address. /// UNI-V2 -> optionToken -> underlyingToken. /// @param optionAddress The address of the option that will be closed from burned UNI-V2 liquidity shares. /// @param otherTokenAddress The address of the other token in the pair with the options. /// @param liquidity The quantity of liquidity tokens to pull from msg.sender and burn. /// @param amountAMin The minimum quantity of longOptionTokens to receive from removing liquidity. /// @param amountBMin The minimum quantity of otherTokens to receive from removing liquidity. /// @param to The address that receives otherTokens from burned UNI-V2, and underlyingTokens from closed options. /// @param deadline The timestamp to expire a pending transaction. /// function removeLongLiquidityThenCloseOptions( IUniswapV2Factory factory, IUniswapV2Router02 router, ITrader trader, address optionAddress, address otherTokenAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) internal returns (uint256, uint256) { // Store in memory for gas savings. IOption optionToken = IOption(optionAddress); { // Gets the Uniswap V2 Pair address for optionAddress and otherToken. // Transfers the LP tokens for the pair to this contract. // Warning: internal call to a non-trusted address `msg.sender`. address pair = factory.getPair(optionAddress, otherTokenAddress); IERC20(pair).safeTransferFrom(msg.sender, address(this), liquidity); IERC20(pair).approve(address(router), uint256(-1)); } // Remove liquidity from Uniswap V2 pool to receive pool tokens (option + quote tokens). (uint256 amountOptions, uint256 amountOtherTokens) = router .removeLiquidity( optionAddress, otherTokenAddress, liquidity, amountAMin, amountBMin, address(this), deadline ); // Approves trader to pull longOptionTokens and shortOptionTOkens from this contract to close options. { address redeemToken = optionToken.redeemToken(); IERC20(optionAddress).approve(address(trader), uint256(-1)); IERC20(redeemToken).approve(address(trader), uint256(-1)); // Calculate equivalent quantity of redeem (short option) tokens to close the option position. // Need to cancel base units and have quote units remaining. uint256 requiredRedeems = amountOptions .mul(optionToken.getQuoteValue()) .div(optionToken.getBaseValue()); // Pull the required shortOptionTokens from msg.sender to this contract. IERC20(redeemToken).safeTransferFrom( msg.sender, address(this), requiredRedeems ); } // Pushes option and redeem tokens to the option contract and calls "closeOption". // Receives underlyingTokens and sends them to the "to" address. trader.safeClose(optionToken, amountOptions, to); // Send the otherTokens received from burning liquidity shares to the "to" address. IERC20(otherTokenAddress).safeTransfer(to, amountOtherTokens); return (amountOptions, amountOtherTokens); } /// /// @dev Combines Uniswap V2 Router "removeLiquidity" function with Primitive "closeOptions" function. /// @notice Pulls UNI-V2 liquidity shares with shortOption<>quote token, and optionTokens from msg.sender. /// Then closes the longOptionTokens and withdraws underlyingTokens to the "to" address. /// Sends quoteTokens from the burned UNI-V2 liquidity shares to the "to" address. /// UNI-V2 -> optionToken -> underlyingToken. /// @param optionAddress The address of the option that will be closed from burned UNI-V2 liquidity shares. /// @param otherTokenAddress The address of the other token in the option pair. /// @param liquidity The quantity of liquidity tokens to pull from msg.sender and burn. /// @param amountAMin The minimum quantity of shortOptionTokens to receive from removing liquidity. /// @param amountBMin The minimum quantity of quoteTokens to receive from removing liquidity. /// @param to The address that receives quoteTokens from burned UNI-V2, and underlyingTokens from closed options. /// @param deadline The timestamp to expire a pending transaction. /// function removeShortLiquidityThenCloseOptions( IUniswapV2Factory factory, IUniswapV2Router02 router, ITrader trader, address optionAddress, address otherTokenAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) internal returns (uint256, uint256) { // Store in memory for gas savings. address redeemToken = IOption(optionAddress).redeemToken(); { // Gets the Uniswap V2 Pair address for shortOptionToken and otherTokens. // Transfers the LP tokens for the pair to this contract. // Warning: internal call to a non-trusted address `msg.sender`. address pair = factory.getPair(redeemToken, otherTokenAddress); IERC20(pair).safeTransferFrom(msg.sender, address(this), liquidity); IERC20(pair).approve(address(router), uint256(-1)); } // Remove liquidity from Uniswap V2 pool to receive pool tokens (shortOptionTokens + otherTokens). (uint256 amountShortOptions, uint256 amountOtherTokens) = router .removeLiquidity( redeemToken, otherTokenAddress, liquidity, amountAMin, amountBMin, address(this), deadline ); // Approves trader to pull longOptionTokens and shortOptionTOkens from this contract to close options. { IOption optionToken = IOption(optionAddress); IERC20(address(optionToken)).approve(address(trader), uint256(-1)); IERC20(redeemToken).approve(address(trader), uint256(-1)); // Calculate equivalent quantity of redeem (short option) tokens to close the option position. // Need to cancel base units and have quote units remaining. uint256 requiredLongOptionTokens = amountShortOptions .mul(optionToken.getBaseValue()) .mul(1 ether) .div(optionToken.getQuoteValue()) .div(1 ether); // Pull the required longOptionTokens from msg.sender to this contract. IERC20(address(optionToken)).safeTransferFrom( msg.sender, address(this), requiredLongOptionTokens ); // Pushes option and redeem tokens to the option contract and calls "closeOption". // Receives underlyingTokens and sends them to the "to" address. trader.safeClose(optionToken, requiredLongOptionTokens, to); } // Send the otherTokens received from burning liquidity shares to the "to" address. IERC20(otherTokenAddress).safeTransfer(to, amountOtherTokens); return (amountShortOptions, amountOtherTokens); } // ==== Internal Functions ==== /// /// @dev Calls the "swapExactTokensForTokens" function on the Uniswap V2 Router 02 Contract. /// @notice Fails early if the address in the beginning of the path is not the token address. /// @param tokenAddress The address of the token to swap from. /// @param amountIn The quantity of longOptionTokens to swap with. /// @param amountOutMin The minimum quantity of tokens to receive in exchange for the tokens swapped. /// @param path The token addresses to trade through using their Uniswap V2 pairs. /// @param to The address to send the token proceeds to. /// @param deadline The timestamp for a trade to fail at if not successful. /// function _swapExactOptionsForTokens( IUniswapV2Router02 router, address tokenAddress, uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) internal returns (uint256[] memory amounts, bool success) { // Fails early if the token being swapped from is not the optionToken. require(path[0] == tokenAddress, "ERR_PATH_OPTION_START"); // Approve the uniswap router to be able to transfer longOptionTokens from this contract. IERC20(tokenAddress).approve(address(router), uint256(-1)); // Call the Uniswap V2 function to swap longOptionTokens to quoteTokens. (amounts) = router.swapExactTokensForTokens( amountIn, amountOutMin, path, to, deadline ); success = true; } }
import { ITrader, IOption } from "../../option/interfaces/ITrader.sol"; import { TraderLib, IERC20 } from "../../option/libraries/TraderLib.sol"; import { IWethConnector01, IWETH } from "../WETH/IWethConnector01.sol"; import { WethConnectorLib01 } from "../WETH/WethConnectorLib01.sol"; // Open Zeppelin import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library UniswapConnectorLib03 { using SafeERC20 for IERC20; // Reverts when `transfer` or `transferFrom` erc20 calls don't return proper data using SafeMath for uint256; // Reverts on math underflows/overflows /// ==== Combo Operations ==== /// /// @dev Mints long + short option tokens, then swaps the longOptionTokens (option) for tokens. /// Combines Primitive "mintOptions" function with Uniswap V2 Router "swapExactTokensForTokens" function. /// @notice If the first address in the path is not the optionToken address, the tx will fail. /// underlyingToken -> optionToken -> quoteToken. /// @param optionToken The address of the Oracle-less Primitive option. /// @param amountIn The quantity of longOptionTokens to mint and then sell. /// @param amountOutMin The minimum quantity of tokens to receive in exchange for the longOptionTokens. /// @param path The token addresses to trade through using their Uniswap V2 pools. Assumes path[0] = option. /// @param to The address to send the optionToken proceeds and redeem tokens to. /// @param deadline The timestamp for a trade to fail at if not successful. /// @return bool Whether the transaction was successful or not. /// function mintLongOptionsThenSwapToTokens( IUniswapV2Router02 router, IOption optionToken, uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) internal returns (bool) { // Pulls underlyingTokens from msg.sender, then pushes underlyingTokens to option contract. // Mints long + short option tokens to this contract. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( optionToken, amountIn, address(this) ); // Swaps longOptionTokens to the token specified at the end of the path, then sends to msg.sender. // Reverts if the first address in the path is not the optionToken address. (, bool success) = _swapExactOptionsForTokens( router, address(optionToken), outputOptions, amountOutMin, path, to, deadline ); // Fail early if the swap failed. require(success, "ERR_SWAP_FAILED"); // Send shortOptionTokens (redeem) to the "to" address. IERC20(optionToken.redeemToken()).safeTransfer(to, outputRedeems); return success; } /// /// @dev Mints long + short option tokens, then swaps the shortOptionTokens (redeem) for tokens. /// @notice If the first address in the path is not the shortOptionToken address, the tx will fail. /// underlyingToken -> shortOptionToken -> quoteToken. /// IMPORTANT: redeemTokens = shortOptionTokens /// @param optionToken The address of the Option contract. /// @param amountIn The quantity of options to mint. /// @param amountOutMin The minimum quantity of tokens to receive in exchange for the shortOptionTokens. /// @param path The token addresses to trade through using their Uniswap V2 pools. Assumes path[0] = shortOptionToken. /// @param to The address to send the shortOptionToken proceeds and longOptionTokens to. /// @param deadline The timestamp for a trade to fail at if not successful. /// @return bool Whether the transaction was successful or not. /// function mintShortOptionsThenSwapToTokens( IUniswapV2Router02 router, IOption optionToken, uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) internal returns (bool) { // Pulls underlyingTokens from msg.sender, then pushes underlyingTokens to option contract. // Mints long + short tokens to this contract. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( optionToken, amountIn, address(this) ); // Swaps shortOptionTokens to the token specified at the end of the path, then sends to msg.sender. // Reverts if the first address in the path is not the shortOptionToken address. address redeemToken = optionToken.redeemToken(); (, bool success) = _swapExactOptionsForTokens( router, redeemToken, outputRedeems, // shortOptionTokens = redeemTokens amountOutMin, path, to, deadline ); // Fail early if the swap failed. require(success, "ERR_SWAP_FAILED"); // Send longOptionTokens to the "to" address. IERC20(optionToken).safeTransfer(to, outputOptions); // longOptionTokens return success; } // ==== Flash Functions ==== /// /// @dev Receives underlyingTokens from a UniswapV2Pair.swap() call from a pair with /// reserve0 = shortOptionTokens and reserve1 = underlyingTokens. /// Uses underlyingTokens to mint long (option) + short (redeem) tokens. /// Sends longOptionTokens to msg.sender, and pays back the UniswapV2Pair the shortOptionTokens, /// AND any remainder quantity of underlyingTokens (paid by msg.sender). /// @notice If the first address in the path is not the shortOptionToken address, the tx will fail. /// @param router The address of the UniswapV2Router02 contract. /// @param pairAddress The address of the redeemToken<>underlyingToken UniswapV2Pair contract. /// @param optionAddress The address of the Option contract. /// @param flashLoanQuantity The quantity of options to mint using borrowed underlyingTokens. /// @param maxPremium The maximum quantity of underlyingTokens to pay for the optionTokens. /// @param path The token addresses to trade through using their Uniswap V2 pools. Assumes path[0] = shortOptionToken. /// @param to The address to send the shortOptionToken proceeds and longOptionTokens to. /// @return success bool Whether the transaction was successful or not. /// function flashMintShortOptionsThenSwap( IUniswapV2Router02 router, address pairAddress, address optionAddress, uint256 flashLoanQuantity, uint256 maxPremium, address[] memory path, address to ) internal returns (uint256, uint256) { require(msg.sender == address(this), "ERR_NOT_SELF"); require(flashLoanQuantity > 0, "ERR_ZERO"); // IMPORTANT: Assume this contract has already received `flashLoanQuantity` of underlyingTokens. // We are flash swapping from an underlying <> shortOptionToken pair, paying back a portion using minted shortOptionTokens // and any remainder of underlyingToken. uint256 outputOptions; // quantity of longOptionTokens minted uint256 outputRedeems; // quantity of shortOptionTokens minted address underlyingToken = IOption(optionAddress) .getUnderlyingTokenAddress(); require(path[1] == underlyingToken, "ERR_END_PATH_NOT_UNDERLYING"); // Mint longOptionTokens using the underlyingTokens received from UniswapV2 flash swap to this contract. // Send underlyingTokens from this contract to the optionToken contract, then call mintOptions. IERC20(underlyingToken).safeTransfer(optionAddress, flashLoanQuantity); (outputOptions, outputRedeems) = IOption(optionAddress).mintOptions( address(this) ); // The loanRemainder will be the amount of underlyingTokens that are needed from the original // transaction caller in order to pay the flash swap. // IMPORTANT: THIS IS EFFECTIVELY THE PREMIUM PAID IN UNDERLYINGTOKENS TO PURCHASE THE OPTIONTOKEN. uint256 loanRemainder; // Economically, negativePremiumPaymentInRedeems value should always be 0. // In the case that we minted more redeemTokens than are needed to pay back the flash swap, // (short -> underlying is a positive trade), there is an effective negative premium. // In that case, this function will send out `negativePremiumAmount` of redeemTokens to the original caller. // This means the user gets to keep the extra redeemTokens for free. // Negative premium amount is the opposite difference of the loan remainder: (paid - flash loan amount) uint256 negativePremiumPaymentInRedeems; // Need to return tokens from the flash swap by returning shortOptionTokens and any remainder of underlyingTokens. { // scope for router, avoids stack too deep errors IUniswapV2Router02 router_ = router; // Since the borrowed amount is underlyingTokens, and we are paying back in redeemTokens, // we need to see how much redeemTokens must be returned for the borrowed amount. // We can find that value by doing the normal swap math, getAmountsIn will give us the amount // of redeemTokens are needed for the output amount of the flash loan. // IMPORTANT: amountsIn 0 is how many short tokens we need to pay back. // This value is most likely greater than the amount of redeemTokens minted. uint256[] memory amountsIn = router_.getAmountsIn( flashLoanQuantity, path ); uint256 redeemsRequired = amountsIn[0]; // the amountIn of redeemTokens based on the amountOut of flashloanQuantity // If outputRedeems is greater than redeems required, we have a negative premium. uint256 redeemCostRemaining = redeemsRequired > outputRedeems ? redeemsRequired.sub(outputRedeems) : 0; // If there is a negative premium, calculate the quantity extra redeemTokens. negativePremiumPaymentInRedeems = outputRedeems > redeemsRequired ? outputRedeems.sub(redeemsRequired) : 0; // In most cases, there will be an outstanding cost (assuming we minted less redeemTokens than the // required amountIn of redeemTokens for the swap). if (redeemCostRemaining > 0) { // The user won't want to pay back the remaining cost in redeemTokens, // because they borrowed underlyingTokens to mint them in the first place. // So instead, we get the quantity of underlyingTokens that could be paid instead. // We can calculate this using normal swap math. // getAmountsOut will return the quantity of underlyingTokens that are output, // based on some input of redeemTokens. // The input redeemTokens is the remaining redeemToken cost, and the output // underlyingTokens is the proportional amount of underlyingTokens. // amountsOut[1] is then the outstanding flash loan value denominated in underlyingTokens. address[] memory path_ = path; uint256[] memory amountsOut = router_.getAmountsOut( redeemCostRemaining, path_ ); // should investigate further, needs to consider a 0.101% fee? // Without a 0.101% fee, amountsOut[1] is not enough. loanRemainder = amountsOut[1] .mul(100101) .add(amountsOut[1]) .div(100000); } // In the case that more redeemTokens were minted than need to be sent back as payment, // calculate the new outputRedeem value to send to the pair // (don't send all the minted redeemTokens). if (negativePremiumPaymentInRedeems > 0) { outputRedeems = outputRedeems.sub( negativePremiumPaymentInRedeems ); } } address redeemToken = IOption(optionAddress).redeemToken(); // Pay back the pair in redeemTokens (shortOptionTokens) IERC20(redeemToken).safeTransfer(pairAddress, outputRedeems); // If loanRemainder is non-zero and non-negative, send underlyingTokens to the pair as payment (premium). if (loanRemainder > 0) { // Pull underlyingTokens from the original msg.sender to pay the remainder of the flash swap. require(loanRemainder >= maxPremium, "ERR_PREMIUM_OVER_MAX"); IERC20(underlyingToken).safeTransferFrom( to, pairAddress, loanRemainder ); } // If negativePremiumAmount is non-zero and non-negative, send it to the `to` address. if (negativePremiumPaymentInRedeems > 0) { IERC20(redeemToken).safeTransfer( to, negativePremiumPaymentInRedeems ); } // Send longOptionTokens (option) to the original msg.sender. IERC20(optionAddress).safeTransfer(to, outputOptions); return (outputOptions, loanRemainder); } /// @dev Sends shortOptionTokens to msg.sender, and pays back the UniswapV2Pair in underlyingTokens. /// @notice IMPORTANT: If minPayout is 0, the `to` address is liable for negative payouts *if* that occurs. /// @param router The UniswapV2Router02 contract. /// @param pairAddress The address of the redeemToken<>underlyingToken UniswapV2Pair contract. /// @param optionAddress The address of the longOptionTokes to close. /// @param flashLoanQuantity The quantity of shortOptionTokens borrowed to use to close longOptionTokens. /// @param minPayout The minimum payout of underlyingTokens sent to the `to` address. /// @param path underlyingTokens -> shortOptionTokens, because we are paying the input of underlyingTokens. /// @param to The address which is sent the underlyingToken payout, or liable to pay for a negative payout. function flashCloseLongOptionsThenSwap( IUniswapV2Router02 router, address pairAddress, address optionAddress, uint256 flashLoanQuantity, uint256 minPayout, address[] memory path, address to ) internal returns (uint256, uint256) { require(msg.sender == address(this), "ERR_NOT_SELF"); require(flashLoanQuantity > 0, "ERR_ZERO"); // IMPORTANT: Assume this contract has already received `flashLoanQuantity` of redeemTokens. // We are flash swapping from an underlying <> shortOptionToken pair, // paying back a portion using underlyingTokens received from closing options. // In the flash open, we did redeemTokens to underlyingTokens. // In the flash close (this function), we are doing underlyingTokens to redeemTokens and keeping the remainder. address underlyingToken = IOption(optionAddress) .getUnderlyingTokenAddress(); address redeemToken = IOption(optionAddress).redeemToken(); require(path[1] == redeemToken, "ERR_END_PATH_NOT_REDEEM"); // Close longOptionTokens using the redeemTokens received from UniswapV2 flash swap to this contract. // Send underlyingTokens from this contract to the optionToken contract, then call mintOptions. IERC20(redeemToken).safeTransfer(optionAddress, flashLoanQuantity); uint256 requiredOptions = flashLoanQuantity .mul(IOption(optionAddress).getBaseValue()) .div(IOption(optionAddress).getQuoteValue()); // Send out the required amount of options from the original caller. // WARNING: CALLS TO UNTRUSTED ADDRESS. IERC20(optionAddress).safeTransferFrom( to, optionAddress, requiredOptions ); (, , uint256 outputUnderlyings) = IOption(optionAddress).closeOptions( address(this) ); // The loanRemainder will be the amount of underlyingTokens that are needed from the original // transaction caller in order to pay the flash swap. // IMPORTANT: THIS IS EFFECTIVELY THE PREMIUM PAID IN UNDERLYINGTOKENS TO PURCHASE THE OPTIONTOKEN. uint256 loanRemainder; // Economically, underlyingPayout value should always be greater than 0, or this trade shouldn't be made. // If an underlyingPayout is greater than 0, it means that the redeemTokens borrowed are worth less than the // underlyingTokens received from closing the redeemToken<>optionTokens. // If the redeemTokens are worth more than the underlyingTokens they are entitled to, // then closing the redeemTokens will cost additional underlyingTokens. In this case, // the transaction should be reverted. Or else, the user is paying extra at the expense of // rebalancing the pool. uint256 underlyingPayout; // Need to return tokens from the flash swap by returning underlyingTokens. { // scope for router, avoids stack too deep errors IUniswapV2Router02 router_ = router; // Since the borrowed amount is redeemTokens, and we are paying back in underlyingTokens, // we need to see how much underlyingTokens must be returned for the borrowed amount. // We can find that value by doing the normal swap math, getAmountsIn will give us the amount // of underlyingTokens are needed for the output amount of the flash loan. // IMPORTANT: amountsIn 0 is how many underlyingTokens we need to pay back. // This value is most likely greater than the amount of underlyingTokens received from closing. uint256[] memory amountsIn = router_.getAmountsIn( flashLoanQuantity, path ); uint256 underlyingsRequired = amountsIn[0]; // the amountIn required of underlyingTokens based on the amountOut of flashloanQuantity // If outputUnderlyings (received from closing) is greater than underlyings required, // there is a positive payout. underlyingPayout = outputUnderlyings > underlyingsRequired ? outputUnderlyings.sub(underlyingsRequired) : 0; // If there is a negative payout, calculate the remaining cost of underlyingTokens. uint256 underlyingCostRemaining = underlyingsRequired > outputUnderlyings ? underlyingsRequired.sub(outputUnderlyings) : 0; // In the case that there is a negative payout (additional underlyingTokens are required), // get the remaining cost into the `loanRemainder` variable and also check to see // if a user is willing to pay the negative cost. There is no rational economic incentive for this. if (underlyingCostRemaining > 0) { loanRemainder = underlyingCostRemaining; } // In the case that the payment is positive, subtract it from the outputUnderlyings. // outputUnderlyings = underlyingsRequired, which is being paid back to the pair. if (underlyingPayout > 0) { outputUnderlyings = outputUnderlyings.sub(underlyingPayout); } } // Pay back the pair in underlyingTokens IERC20(underlyingToken).safeTransfer(pairAddress, outputUnderlyings); // If loanRemainder is non-zero and non-negative, send underlyingTokens to the pair as payment (premium). if (loanRemainder > 0) { // Pull underlyingTokens from the original msg.sender to pay the remainder of the flash swap. // Revert if the minPayout is less than or equal to the underlyingPayment of 0. // There is 0 underlyingPayment in the case that loanRemainder > 0. // This code branch can be successful by setting `minPayout` to 0. // This means the user is willing to pay to close the position. require(minPayout <= underlyingPayout, "ERR_NEGATIVE_PAYOUT"); IERC20(underlyingToken).safeTransferFrom( to, pairAddress, loanRemainder ); } // If underlyingPayout is non-zero and non-negative, send it to the `to` address. if (underlyingPayout > 0) { // Revert if minPayout is less than the actual payout. require(underlyingPayout >= minPayout, "ERR_PREMIUM_UNDER_MIN"); IERC20(underlyingToken).safeTransfer(to, underlyingPayout); } return (outputUnderlyings, underlyingPayout); } // ==== Liquidity Functions ==== /// /// @dev Adds liquidity to an option<>token pair by minting longOptionTokens with underlyingTokens. /// @notice Pulls underlying tokens from msg.sender and pushes UNI-V2 liquidity tokens to the "to" address. /// underlyingToken -> optionToken -> UNI-V2. /// @param optionAddress The address of the optionToken to mint then provide liquidity for. /// @param otherTokenAddress The address of the otherToken in the pair with the optionToken. /// @param quantityOptions The quantity of underlyingTokens to use to mint longOptionTokens. /// @param quantityOtherTokens The quantity of otherTokens to add with longOptionTokens to the Uniswap V2 Pair. /// @param minOptionTokens IMPORTANT: MUST BE EQUAL TO QUANTITYOPTIONS. The minimum quantity of longOptionTokens expected to provide liquidity with. /// @param minOtherTokens The minimum quantity of otherTokens expected to provide liquidity with. /// @param to The address that receives UNI-V2 shares. /// @param deadline The timestamp to expire a pending transaction. /// function addLongLiquidityWithUnderlying( IUniswapV2Router02 router, address optionAddress, address otherTokenAddress, uint256 quantityOptions, uint256 quantityOtherTokens, uint256 minOptionTokens, uint256 minOtherTokens, address to, uint256 deadline ) internal returns (bool) { // Pull otherTokens from msg.sender to add to Uniswap V2 Pair. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. IERC20(otherTokenAddress).safeTransferFrom( msg.sender, address(this), quantityOtherTokens ); // Pulls underlyingTokens from msg.sender to this contract. // Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( IOption(optionAddress), quantityOptions, address(this) ); assert(outputOptions == quantityOptions); // Approves Uniswap V2 Pair to transfer option and quote tokens from this contract. IERC20(optionAddress).approve(address(router), uint256(-1)); IERC20(otherTokenAddress).approve(address(router), uint256(-1)); // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "to" address. router.addLiquidity( optionAddress, otherTokenAddress, quantityOptions, quantityOtherTokens, minOptionTokens, minOtherTokens, to, deadline ); // Send shortOptionTokens (redeem) from minting option operation to msg.sender. IERC20(IOption(optionAddress).redeemToken()).safeTransfer( msg.sender, outputRedeems ); IERC20(otherTokenAddress).safeTransfer( msg.sender, IERC20(otherTokenAddress).balanceOf(address(this)) ); return true; } /// /// @dev Adds liquidity to an option<>token pair by minting longOptionTokens with underlyingTokens. /// @notice Pulls underlying tokens from msg.sender and pushes UNI-V2 liquidity tokens to the "to" address. /// underlyingToken -> optionToken -> UNI-V2. /// @param optionAddress The address of the optionToken to mint then provide liquidity for. /// @param otherTokenAddress The address of the otherToken in the pair with the optionToken. /// @param quantityOtherTokens The quantity of otherTokens to add with longOptionTokens to the Uniswap V2 Pair. /// @param minOptionTokens The minimum quantity of longOptionTokens expected to provide liquidity with. /// @param minOtherTokens The minimum quantity of otherTokens expected to provide liquidity with. /// @param to The address that receives UNI-V2 shares. /// @param deadline The timestamp to expire a pending transaction. /// function addLongLiquidityWithETHUnderlying( IWETH weth, IUniswapV2Router02 router, address optionAddress, address otherTokenAddress, uint256 quantityOtherTokens, uint256 minOptionTokens, uint256 minOtherTokens, address to, uint256 deadline ) internal returns (bool) { // Pull otherTokens from msg.sender to add to Uniswap V2 Pair. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. IERC20(otherTokenAddress).safeTransferFrom( msg.sender, address(this), quantityOtherTokens ); // Pulls underlyingTokens from msg.sender to this contract. // Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. (uint256 outputOptions, uint256 outputRedeems) = WethConnectorLib01 .safeMintWithETH(weth, IOption(optionAddress), address(this)); assert(outputOptions == msg.value); // Approves Uniswap V2 Pair to transfer option and quote tokens from this contract. IERC20(optionAddress).approve(address(router), uint256(-1)); IERC20(otherTokenAddress).approve(address(router), uint256(-1)); // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "to" address. router.addLiquidity( optionAddress, otherTokenAddress, msg.value, quantityOtherTokens, minOptionTokens, minOtherTokens, to, deadline ); // Send shortOptionTokens (redeem) from minting option operation to msg.sender. IERC20(IOption(optionAddress).redeemToken()).safeTransfer( msg.sender, outputRedeems ); return true; } /// /// @dev Adds redeemToken liquidity to a redeem<>otherToken pair by minting shortOptionTokens with underlyingTokens. /// @notice Pulls underlying tokens from msg.sender and pushes UNI-V2 liquidity tokens to the "to" address. /// underlyingToken -> redeemToken -> UNI-V2. /// @param optionAddress The address of the optionToken to get the redeemToken to mint then provide liquidity for. /// @param otherTokenAddress The address of the otherToken in the pair with the optionToken. /// @param quantityOptions The quantity of underlyingTokens to use to mint option + redeem tokens. /// @param quantityOtherTokens The quantity of otherTokens to add with shortOptionTokens to the Uniswap V2 Pair. /// @param minShortTokens The minimum quantity of shortOptionTokens expected to provide liquidity with. /// @param minOtherTokens The minimum quantity of otherTokens expected to provide liquidity with. /// @param to The address that receives UNI-V2 shares. /// @param deadline The timestamp to expire a pending transaction. /// function addShortLiquidityWithUnderlying( IUniswapV2Router02 router, address optionAddress, address otherTokenAddress, uint256 quantityOptions, uint256 quantityOtherTokens, uint256 minShortTokens, uint256 minOtherTokens, address to, uint256 deadline ) internal returns (bool) { // Pull otherTokens from msg.sender to add to Uniswap V2 Pair. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. IERC20(otherTokenAddress).safeTransferFrom( msg.sender, address(this), quantityOtherTokens ); // Pulls underlyingTokens from msg.sender to this contract. // Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. // Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted. (uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint( IOption(optionAddress), quantityOptions, address(this) ); address redeemToken = IOption(optionAddress).redeemToken(); // Approves Uniswap V2 Pair to transfer option and quote tokens from this contract. IERC20(redeemToken).approve(address(router), uint256(-1)); IERC20(otherTokenAddress).approve(address(router), uint256(-1)); // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "to" address. router.addLiquidity( redeemToken, otherTokenAddress, outputRedeems, quantityOtherTokens, minShortTokens, minOtherTokens, to, deadline ); // Send longOptionTokens from minting option operation to msg.sender. IERC20(optionAddress).safeTransfer(msg.sender, outputOptions); IERC20(otherTokenAddress).safeTransfer( msg.sender, IERC20(otherTokenAddress).balanceOf(address(this)) ); return true; } /// /// @dev Combines Uniswap V2 Router "removeLiquidity" function with Primitive "closeOptions" function. /// @notice Pulls UNI-V2 liquidity shares with option<>other token, and redeemTokens from msg.sender. /// Then closes the longOptionTokens and withdraws underlyingTokens to the "to" address. /// Sends otherTokens from the burned UNI-V2 liquidity shares to the "to" address. /// UNI-V2 -> optionToken -> underlyingToken. /// @param optionAddress The address of the option that will be closed from burned UNI-V2 liquidity shares. /// @param otherTokenAddress The address of the other token in the pair with the options. /// @param liquidity The quantity of liquidity tokens to pull from msg.sender and burn. /// @param amountAMin The minimum quantity of longOptionTokens to receive from removing liquidity. /// @param amountBMin The minimum quantity of otherTokens to receive from removing liquidity. /// @param to The address that receives otherTokens from burned UNI-V2, and underlyingTokens from closed options. /// @param deadline The timestamp to expire a pending transaction. /// function removeLongLiquidityThenCloseOptions( IUniswapV2Factory factory, IUniswapV2Router02 router, ITrader trader, address optionAddress, address otherTokenAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) internal returns (uint256, uint256) { // Store in memory for gas savings. IOption optionToken = IOption(optionAddress); { // Gets the Uniswap V2 Pair address for optionAddress and otherToken. // Transfers the LP tokens for the pair to this contract. // Warning: internal call to a non-trusted address `msg.sender`. address pair = factory.getPair(optionAddress, otherTokenAddress); IERC20(pair).safeTransferFrom(msg.sender, address(this), liquidity); IERC20(pair).approve(address(router), uint256(-1)); } // Remove liquidity from Uniswap V2 pool to receive pool tokens (option + quote tokens). (uint256 amountOptions, uint256 amountOtherTokens) = router .removeLiquidity( optionAddress, otherTokenAddress, liquidity, amountAMin, amountBMin, address(this), deadline ); // Approves trader to pull longOptionTokens and shortOptionTOkens from this contract to close options. { address redeemToken = optionToken.redeemToken(); IERC20(optionAddress).approve(address(trader), uint256(-1)); IERC20(redeemToken).approve(address(trader), uint256(-1)); // Calculate equivalent quantity of redeem (short option) tokens to close the option position. // Need to cancel base units and have quote units remaining. uint256 requiredRedeems = amountOptions .mul(optionToken.getQuoteValue()) .div(optionToken.getBaseValue()); // Pull the required shortOptionTokens from msg.sender to this contract. IERC20(redeemToken).safeTransferFrom( msg.sender, address(this), requiredRedeems ); } // Pushes option and redeem tokens to the option contract and calls "closeOption". // Receives underlyingTokens and sends them to the "to" address. trader.safeClose(optionToken, amountOptions, to); // Send the otherTokens received from burning liquidity shares to the "to" address. IERC20(otherTokenAddress).safeTransfer(to, amountOtherTokens); return (amountOptions, amountOtherTokens); } /// /// @dev Combines Uniswap V2 Router "removeLiquidity" function with Primitive "closeOptions" function. /// @notice Pulls UNI-V2 liquidity shares with shortOption<>quote token, and optionTokens from msg.sender. /// Then closes the longOptionTokens and withdraws underlyingTokens to the "to" address. /// Sends quoteTokens from the burned UNI-V2 liquidity shares to the "to" address. /// UNI-V2 -> optionToken -> underlyingToken. /// @param optionAddress The address of the option that will be closed from burned UNI-V2 liquidity shares. /// @param otherTokenAddress The address of the other token in the option pair. /// @param liquidity The quantity of liquidity tokens to pull from msg.sender and burn. /// @param amountAMin The minimum quantity of shortOptionTokens to receive from removing liquidity. /// @param amountBMin The minimum quantity of quoteTokens to receive from removing liquidity. /// @param to The address that receives quoteTokens from burned UNI-V2, and underlyingTokens from closed options. /// @param deadline The timestamp to expire a pending transaction. /// function removeShortLiquidityThenCloseOptions( IUniswapV2Factory factory, IUniswapV2Router02 router, ITrader trader, address optionAddress, address otherTokenAddress, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) internal returns (uint256, uint256) { // Store in memory for gas savings. address redeemToken = IOption(optionAddress).redeemToken(); { // Gets the Uniswap V2 Pair address for shortOptionToken and otherTokens. // Transfers the LP tokens for the pair to this contract. // Warning: internal call to a non-trusted address `msg.sender`. address pair = factory.getPair(redeemToken, otherTokenAddress); IERC20(pair).safeTransferFrom(msg.sender, address(this), liquidity); IERC20(pair).approve(address(router), uint256(-1)); } // Remove liquidity from Uniswap V2 pool to receive pool tokens (shortOptionTokens + otherTokens). (uint256 amountShortOptions, uint256 amountOtherTokens) = router .removeLiquidity( redeemToken, otherTokenAddress, liquidity, amountAMin, amountBMin, address(this), deadline ); // Approves trader to pull longOptionTokens and shortOptionTOkens from this contract to close options. { IOption optionToken = IOption(optionAddress); IERC20(address(optionToken)).approve(address(trader), uint256(-1)); IERC20(redeemToken).approve(address(trader), uint256(-1)); // Calculate equivalent quantity of redeem (short option) tokens to close the option position. // Need to cancel base units and have quote units remaining. uint256 requiredLongOptionTokens = amountShortOptions .mul(optionToken.getBaseValue()) .mul(1 ether) .div(optionToken.getQuoteValue()) .div(1 ether); // Pull the required longOptionTokens from msg.sender to this contract. IERC20(address(optionToken)).safeTransferFrom( msg.sender, address(this), requiredLongOptionTokens ); // Pushes option and redeem tokens to the option contract and calls "closeOption". // Receives underlyingTokens and sends them to the "to" address. trader.safeClose(optionToken, requiredLongOptionTokens, to); } // Send the otherTokens received from burning liquidity shares to the "to" address. IERC20(otherTokenAddress).safeTransfer(to, amountOtherTokens); return (amountShortOptions, amountOtherTokens); } // ==== Internal Functions ==== /// /// @dev Calls the "swapExactTokensForTokens" function on the Uniswap V2 Router 02 Contract. /// @notice Fails early if the address in the beginning of the path is not the token address. /// @param tokenAddress The address of the token to swap from. /// @param amountIn The quantity of longOptionTokens to swap with. /// @param amountOutMin The minimum quantity of tokens to receive in exchange for the tokens swapped. /// @param path The token addresses to trade through using their Uniswap V2 pairs. /// @param to The address to send the token proceeds to. /// @param deadline The timestamp for a trade to fail at if not successful. /// function _swapExactOptionsForTokens( IUniswapV2Router02 router, address tokenAddress, uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) internal returns (uint256[] memory amounts, bool success) { // Fails early if the token being swapped from is not the optionToken. require(path[0] == tokenAddress, "ERR_PATH_OPTION_START"); // Approve the uniswap router to be able to transfer longOptionTokens from this contract. IERC20(tokenAddress).approve(address(router), uint256(-1)); // Call the Uniswap V2 function to swap longOptionTokens to quoteTokens. (amounts) = router.swapExactTokensForTokens( amountIn, amountOutMin, path, to, deadline ); success = true; } }
4,664
17
// VIEWS//This view returns true if the given ERC20 token contract has been listed valid for deposit/asset_source Contract address for given ERC20 token/ return True if asset is listed
function is_asset_listed(address asset_source) public virtual view returns(bool);
function is_asset_listed(address asset_source) public virtual view returns(bool);
56,977
111
// Create the city
uint cityId = cities.push(City(_landId, msg.sender, 0, 0, false, 0, 0)) - 1; lands[_landId].landForSale == false; lands[_landId].landForRent == false; lands[_landId].cityRentingId = cityId; lands[_landId].isOccupied = true;
uint cityId = cities.push(City(_landId, msg.sender, 0, 0, false, 0, 0)) - 1; lands[_landId].landForSale == false; lands[_landId].landForRent == false; lands[_landId].cityRentingId = cityId; lands[_landId].isOccupied = true;
41,397
38
// installation of a lockup for safe,fixing free amount on balance,token installation (run once)
function setContract(Token _token, uint256 _lockup) thirdLevel public returns(bool){ require(_token != address(0x0)); require(!lockupIsSet); require(!tranche); token = _token; freeAmount = getMainBalance(); mainLockup = _lockup; tranche = true; lockupIsSet = true; return true; }
function setContract(Token _token, uint256 _lockup) thirdLevel public returns(bool){ require(_token != address(0x0)); require(!lockupIsSet); require(!tranche); token = _token; freeAmount = getMainBalance(); mainLockup = _lockup; tranche = true; lockupIsSet = true; return true; }
33,193
70
// update data for new owner
tokenOwner[_tokenId] = newOwner;
tokenOwner[_tokenId] = newOwner;
64,035
81
// fetch data
address _owner = voucher.ownerOf(id); uint256[3] memory packedOrdersMemory = _packedOrdersByStrategyId[id]; (Order[2] memory orders, bool ordersInverted) = _unpackOrders(packedOrdersMemory);
address _owner = voucher.ownerOf(id); uint256[3] memory packedOrdersMemory = _packedOrdersByStrategyId[id]; (Order[2] memory orders, bool ordersInverted) = _unpackOrders(packedOrdersMemory);
13,862
39
// Converts all of caller&39;s dividends to tokens.
function reinvest() onlyStronghands public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); }
function reinvest() onlyStronghands public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); }
22,961
24
// ESTIMATION FUNCTIONS //returns how much shares ( LP tokens ) send to user/amount1 and amount2 must have the same proportion in relation to reserves/use this formula to calculate _amountToken1 and _amountToken2/ x = totalToken1, y = totalToken2, dx = amount of token 1, dy = amount of token 2/ dx = xdy / y to prioritize amount of token 1/ dy = ydx / x to prioritize amount of token 2/_amountToken1 amount of token 1 to add at the pool/_amountToken2 amount of token 2 to add at the pool
function estimateShares( uint _amountToken1, uint _amountToken2 ) public view returns ( uint _shares ) { if( totalSupply() == 0 ) { require( _amountToken1 == _amountToken2, "Error: Genesis Amounts must be the same" ); _shares = _amountToken1; } else { uint share1 = (_amountToken1 * totalSupply()) / totalToken1; uint share2 = (_amountToken2 * totalSupply()) / totalToken2; require( _isEqual( share1, share2) , "Error: equivalent value not provided"); _shares = _min( share1, share2 ); } require( _shares > 0, "Error: shares with zero value" ); }
function estimateShares( uint _amountToken1, uint _amountToken2 ) public view returns ( uint _shares ) { if( totalSupply() == 0 ) { require( _amountToken1 == _amountToken2, "Error: Genesis Amounts must be the same" ); _shares = _amountToken1; } else { uint share1 = (_amountToken1 * totalSupply()) / totalToken1; uint share2 = (_amountToken2 * totalSupply()) / totalToken2; require( _isEqual( share1, share2) , "Error: equivalent value not provided"); _shares = _min( share1, share2 ); } require( _shares > 0, "Error: shares with zero value" ); }
20,667
157
// reset their index
holderTimestamps[msg.sender] = block.timestamp; sendETH(msg.sender, cut); checkForTheGamesEnd();
holderTimestamps[msg.sender] = block.timestamp; sendETH(msg.sender, cut); checkForTheGamesEnd();
16,877
0
// Price rate caches are used to avoid querying the price rate for a token every time we need to work with it. Data is stored with the following structure: [ expires | duration | price rate value ] [ uint64|uint64|uint128 ]
bytes32 private _priceRateCache0; bytes32 private _priceRateCache1; uint256 private constant _PRICE_RATE_CACHE_VALUE_OFFSET = 0; uint256 private constant _PRICE_RATE_CACHE_DURATION_OFFSET = 128; uint256 private constant _PRICE_RATE_CACHE_EXPIRES_OFFSET = 128 + 64; event OracleEnabledChanged(bool enabled); event PriceRateProviderSet(IERC20 indexed token, IRateProvider indexed provider, uint256 cacheDuration);
bytes32 private _priceRateCache0; bytes32 private _priceRateCache1; uint256 private constant _PRICE_RATE_CACHE_VALUE_OFFSET = 0; uint256 private constant _PRICE_RATE_CACHE_DURATION_OFFSET = 128; uint256 private constant _PRICE_RATE_CACHE_EXPIRES_OFFSET = 128 + 64; event OracleEnabledChanged(bool enabled); event PriceRateProviderSet(IERC20 indexed token, IRateProvider indexed provider, uint256 cacheDuration);
35,506
31
// Event emitted when user claim Asset token
event WithdrawedToken(uint id, address user, uint assetAmount);
event WithdrawedToken(uint id, address user, uint assetAmount);
20,542
5
// Tells the address of the owner return owner - the address of the owner/
function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; // solhint-disable-next-line no-inline-assembly assembly { owner := sload(position) } }
function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; // solhint-disable-next-line no-inline-assembly assembly { owner := sload(position) } }
11,063
11
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns(bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); ERC223TokenReceiver receiver = ERC223TokenReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; }
function transferToContract(address _to, uint _value, bytes _data) private returns(bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); ERC223TokenReceiver receiver = ERC223TokenReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; }
37,765
97
// Initializes access controls. _admin Admins address. /
function initAccessControls(address _admin) public { require(!initAccess, "Already initialised"); _setupRole(DEFAULT_ADMIN_ROLE, _admin); initAccess = true; }
function initAccessControls(address _admin) public { require(!initAccess, "Already initialised"); _setupRole(DEFAULT_ADMIN_ROLE, _admin); initAccess = true; }
13,970
17
// Set client address, must be called by owner /
function setClientAddress(address _newClient) public onlyOwner { clientAddress = _newClient; }
function setClientAddress(address _newClient) public onlyOwner { clientAddress = _newClient; }
20,977
259
// Only perform the call to transfer if there is a non-zero balance.
if (balance > 0) { if (!suppressRevert) {
if (balance > 0) { if (!suppressRevert) {
27,369
1
// Calculates absolute difference between a and b a uint256 to compare with b uint256 to compare withreturn Difference between a and b /
function difference(uint256 a, uint256 b) external pure returns (uint256) { return _difference(a, b); }
function difference(uint256 a, uint256 b) external pure returns (uint256) { return _difference(a, b); }
8,524
257
// Set the required fraction of all Havvens that need to be part ofa vote for it to pass. /
function setRequiredParticipation(uint fraction) external onlyOwner
function setRequiredParticipation(uint fraction) external onlyOwner
64,905
403
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
FixedPoint.Unsigned public disputeBondPct;
30,857
8
// set max power
var PowerContract = ERC20(powerAddr); uint256 authorizedPower = PowerContract.totalSupply(); contr.setMaxPower(authorizedPower);
var PowerContract = ERC20(powerAddr); uint256 authorizedPower = PowerContract.totalSupply(); contr.setMaxPower(authorizedPower);
30,798
10
// Solari/ @date Sep 2021/Solari Token implementation
contract Solari is ERC20, Ownable { using SafeMath for uint256; // Events event LogAddMinter(address indexed minter_); event LogRemoveMinter(address indexed minter_); // Minters mapping(address => bool) public minters; // Modifiers modifier onlyMinter() { require(minters[msg.sender] == true, "SOLARI: not a minter"); _; } // ERC20 `variables` // solhint-disable-next-line const-name-snakecase string public constant symbol = "SOLARI"; // solhint-disable-next-line const-name-snakecase string public constant name = "Solari Token"; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; uint256 public override totalSupply; uint256 public constant MAX_SUPPLY = 1e27; // 1 billion tokens /// @dev mints `amount` tokens to account `to` /// @param to the account to mint to /// @param amount the amount to mint function mint(address to, uint256 amount) public onlyMinter { // solhint-disable-next-line reason-string require(to != address(0), "SOLARI: can not mint to zero address"); require(MAX_SUPPLY >= totalSupply.add(amount), "SOLARI: Don't go over MAX"); totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @dev minter access control functions function addMinter(address minter_) public onlyOwner { minters[minter_] = true; emit LogAddMinter(minter_); } function removeMinter(address minter_) public onlyOwner { minters[minter_] = false; emit LogRemoveMinter(minter_); } }
contract Solari is ERC20, Ownable { using SafeMath for uint256; // Events event LogAddMinter(address indexed minter_); event LogRemoveMinter(address indexed minter_); // Minters mapping(address => bool) public minters; // Modifiers modifier onlyMinter() { require(minters[msg.sender] == true, "SOLARI: not a minter"); _; } // ERC20 `variables` // solhint-disable-next-line const-name-snakecase string public constant symbol = "SOLARI"; // solhint-disable-next-line const-name-snakecase string public constant name = "Solari Token"; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; uint256 public override totalSupply; uint256 public constant MAX_SUPPLY = 1e27; // 1 billion tokens /// @dev mints `amount` tokens to account `to` /// @param to the account to mint to /// @param amount the amount to mint function mint(address to, uint256 amount) public onlyMinter { // solhint-disable-next-line reason-string require(to != address(0), "SOLARI: can not mint to zero address"); require(MAX_SUPPLY >= totalSupply.add(amount), "SOLARI: Don't go over MAX"); totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @dev minter access control functions function addMinter(address minter_) public onlyOwner { minters[minter_] = true; emit LogAddMinter(minter_); } function removeMinter(address minter_) public onlyOwner { minters[minter_] = false; emit LogRemoveMinter(minter_); } }
50,933
232
// In the specific case of a Lock, each owner can own only at most 1 key.return The number of NFTs owned by `_keyOwner`, either 0 or 1./
function balanceOf( address _keyOwner ) public view returns (uint)
function balanceOf( address _keyOwner ) public view returns (uint)
41,596
20
// We only need settle the transfering in of the assetToTransferIn
_settleTokenTransfer(assetToTransferIn, transfers[0], address(market));
_settleTokenTransfer(assetToTransferIn, transfers[0], address(market));
33,670
56
// gets the latest recorded price time return the last recorded time of a synths price/
function getLatestPriceTime() external view returns (uint) { return _latestobservedtime; }
function getLatestPriceTime() external view returns (uint) { return _latestobservedtime; }
67,856
4
// This emits when an operator is enabled or disabled for an owner./The operator can manage all NFTs of the owner.
event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved );
event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved );
48,429
17
// Creates a new lock by transferring 'amount' to a newly created holding contract. An NFT with the lockId is minted to the user. This NFT is transferrable and represents the ownership of the lock. token The token to transfer in amount The amount of tokens to transfer in unlockTimestamp The timestamp from which withdrawals become possible unlockableByGovernance Indicates whether the Locker operator should be able to unlock /
function createLock( IERC20 token, uint256 amount, uint256 unlockTimestamp, bool unlockableByGovernance
function createLock( IERC20 token, uint256 amount, uint256 unlockTimestamp, bool unlockableByGovernance
16,617
61
// Buying eggs from the company
contract EggPurchase is EggMinting, ExternalContracts { uint16[4] discountThresholds = [20, 100, 250, 500]; uint8[4] discountPercents = [75, 50, 30, 20 ]; // purchasing egg function purchaseEgg(uint64 userNumber, uint16 quality) external payable whenNotPaused { require(tokensCount >= uniquePetsCount); // checking egg availablity require(eggAvailable(quality)); // checking total count of presale eggs require(tokensCount <= globalPresaleLimit); // calculating price uint256 eggPrice = ( recommendedPrice(quality) * (100 - getCurrentDiscountPercent()) ) / 100; // checking payment amount require(msg.value >= eggPrice); // increment egg counter purchesedEggs[quality]++; // initialize variables for store child genes and quility uint256 childGenes; uint16 childQuality; // get genes and quality of new pet by opening egg through external interface (childGenes, childQuality) = geneScience.openEgg(userNumber, quality); // creating new pet createPet( childGenes, // genes string childQuality, // child quality by open egg msg.sender // owner ); reward.get(msg.sender, recommendedPrice(quality)); } function getCurrentDiscountPercent() constant public returns (uint8 discount) { for(uint8 i = 0; i <= 3; i++) { if(tokensCount < (discountThresholds[i] + uniquePetsCount )) return discountPercents[i]; } return 10; } }
contract EggPurchase is EggMinting, ExternalContracts { uint16[4] discountThresholds = [20, 100, 250, 500]; uint8[4] discountPercents = [75, 50, 30, 20 ]; // purchasing egg function purchaseEgg(uint64 userNumber, uint16 quality) external payable whenNotPaused { require(tokensCount >= uniquePetsCount); // checking egg availablity require(eggAvailable(quality)); // checking total count of presale eggs require(tokensCount <= globalPresaleLimit); // calculating price uint256 eggPrice = ( recommendedPrice(quality) * (100 - getCurrentDiscountPercent()) ) / 100; // checking payment amount require(msg.value >= eggPrice); // increment egg counter purchesedEggs[quality]++; // initialize variables for store child genes and quility uint256 childGenes; uint16 childQuality; // get genes and quality of new pet by opening egg through external interface (childGenes, childQuality) = geneScience.openEgg(userNumber, quality); // creating new pet createPet( childGenes, // genes string childQuality, // child quality by open egg msg.sender // owner ); reward.get(msg.sender, recommendedPrice(quality)); } function getCurrentDiscountPercent() constant public returns (uint8 discount) { for(uint8 i = 0; i <= 3; i++) { if(tokensCount < (discountThresholds[i] + uniquePetsCount )) return discountPercents[i]; } return 10; } }
36,734
153
// handle transfers prior to adding newPrincipal to loanTokenSent
uint256 msgValue = _verifyTransfers( collateralTokenAddress, sentAddresses, sentAmounts, withdrawAmount );
uint256 msgValue = _verifyTransfers( collateralTokenAddress, sentAddresses, sentAmounts, withdrawAmount );
21,956
53
// OfficeHours Management ///
function canCast(uint40 _ts, bool _officeHours) public pure returns (bool) { if (_officeHours) { uint256 day = (_ts / 1 days + 3) % 7; if (day >= 5) { return false; } // Can only be cast on a weekday uint256 hour = _ts / 1 hours % 24; if (hour < 14 || hour >= 21) { return false; } // Outside office hours } return true; }
function canCast(uint40 _ts, bool _officeHours) public pure returns (bool) { if (_officeHours) { uint256 day = (_ts / 1 days + 3) % 7; if (day >= 5) { return false; } // Can only be cast on a weekday uint256 hour = _ts / 1 hours % 24; if (hour < 14 || hour >= 21) { return false; } // Outside office hours } return true; }
39,491
3
// Rauction
function getCounter() external returns (uint256); function setCounter(uint) external; function generateTokenId() external returns (uint256); function isLive(uint) external view returns (bool); function getTokens(uint256[] calldata) external view returns (DS.TokenData[] memory);
function getCounter() external returns (uint256); function setCounter(uint) external; function generateTokenId() external returns (uint256); function isLive(uint) external view returns (bool); function getTokens(uint256[] calldata) external view returns (DS.TokenData[] memory);
29,978
8
// todo to check the validity of new_vault
_transfer(_vault, new_vault, balanceOf(_vault)); _vault = new_vault; return true;
_transfer(_vault, new_vault, balanceOf(_vault)); _vault = new_vault; return true;
21,324
1
// Initialize inheritance chain
__Ownable_init(); __UUPSUpgradeable_init();
__Ownable_init(); __UUPSUpgradeable_init();
30,870
68
// Set max transaction
function setMaxTxAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; }
function setMaxTxAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; }
53,035
11
// Adds or changes a vote on a proposal. proposal The proposal struct. previousWeight The previous weight of the vote. currentWeight The current weight of the vote. previousVote The vote to be removed, or None for a new vote. currentVote The vote to be set. /
function updateVote( Proposal storage proposal, uint256 previousWeight, uint256 currentWeight, VoteValue previousVote, VoteValue currentVote
function updateVote( Proposal storage proposal, uint256 previousWeight, uint256 currentWeight, VoteValue previousVote, VoteValue currentVote
19,137
25
// Nonce for the next message to be sent, without the message version applied. Use themessageNonce getter which will insert the message version into the nonce to give youthe actual nonce to be used for the message. /
uint240 internal msgNonce;
uint240 internal msgNonce;
15,946
78
// release & release
event Release(address indexed _to, uint256 _amount); event Refund(address indexed _to, uint256 _amount); function release(address _addr) external returns (bool)
event Release(address indexed _to, uint256 _amount); event Refund(address indexed _to, uint256 _amount); function release(address _addr) external returns (bool)
14,221
15
// erc20 methods
function getTotalSupplies( address[] memory tokens ) public view returns (address[] memory, uint256[] memory)
function getTotalSupplies( address[] memory tokens ) public view returns (address[] memory, uint256[] memory)
15,753
37
// address array
function inArray(address[] storage array, address _item)
function inArray(address[] storage array, address _item)
68,267
7
// Withdraws from LP vault
uint256 _lpBefore = lp.balanceOf(address(this)); IVault(lpVault).withdraw(_lpVault); uint256 _lpAfter = lp.balanceOf(address(this));
uint256 _lpBefore = lp.balanceOf(address(this)); IVault(lpVault).withdraw(_lpVault); uint256 _lpAfter = lp.balanceOf(address(this));
17,452
22
// returns info list of ALL claims
function allClaims(uint256 offset, uint256 limit) external view returns (AllClaimInfo[] memory _allClaimsInfo);
function allClaims(uint256 offset, uint256 limit) external view returns (AllClaimInfo[] memory _allClaimsInfo);
49,966
18
// Vesting vaults can only contain fungible tokens. For this reason, the non-fungible and multi tokens are entirely disregarded in the pricing model. It is assumed that the vault factory will block any attempts at creating such a vault until the feature is supported.
if (!isVested) {
if (!isVested) {
20,873
132
// Checks whether the cap has been reached. return Whether the cap was reached/
function capReached() public view returns (bool) { return tokensSold >= cap; }
function capReached() public view returns (bool) { return tokensSold >= cap; }
11,231
3
// Taker order is not valid
string constant ORDER_IS_NOT_FILLABLE = "ORDER_IS_NOT_FILLABLE"; string constant MAKER_ORDER_CAN_NOT_BE_MARKET_ORDER = "MAKER_ORDER_CAN_NOT_BE_MARKET_ORDER"; string constant TRANSFER_FROM_FAILED = "TRANSFER_FROM_FAILED"; string constant MAKER_ORDER_OVER_MATCH = "MAKER_ORDER_OVER_MATCH"; string constant TAKER_ORDER_OVER_MATCH = "TAKER_ORDER_OVER_MATCH"; string constant ORDER_VERSION_NOT_SUPPORTED = "ORDER_VERSION_NOT_SUPPORTED"; string constant MAKER_ONLY_ORDER_CANNOT_BE_TAKER = "MAKER_ONLY_ORDER_CANNOT_BE_TAKER"; string constant TRANSFER_FAILED = "TRANSFER_FAILED"; string constant MINT_POSITION_TOKENS_FAILED = "MINT_FAILED"; string constant REDEEM_POSITION_TOKENS_FAILED = "REDEEM_FAILED";
string constant ORDER_IS_NOT_FILLABLE = "ORDER_IS_NOT_FILLABLE"; string constant MAKER_ORDER_CAN_NOT_BE_MARKET_ORDER = "MAKER_ORDER_CAN_NOT_BE_MARKET_ORDER"; string constant TRANSFER_FROM_FAILED = "TRANSFER_FROM_FAILED"; string constant MAKER_ORDER_OVER_MATCH = "MAKER_ORDER_OVER_MATCH"; string constant TAKER_ORDER_OVER_MATCH = "TAKER_ORDER_OVER_MATCH"; string constant ORDER_VERSION_NOT_SUPPORTED = "ORDER_VERSION_NOT_SUPPORTED"; string constant MAKER_ONLY_ORDER_CANNOT_BE_TAKER = "MAKER_ONLY_ORDER_CANNOT_BE_TAKER"; string constant TRANSFER_FAILED = "TRANSFER_FAILED"; string constant MINT_POSITION_TOKENS_FAILED = "MINT_FAILED"; string constant REDEEM_POSITION_TOKENS_FAILED = "REDEEM_FAILED";
11,325
5
// Sets the base token URI prefix.
function setBaseTokenURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; }
function setBaseTokenURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; }
14,202
8
// transfer the nft to maxbidder
IERC721(_nft).safeTransferFrom( address(this), auction.maxBidUser, _tokenId);
IERC721(_nft).safeTransferFrom( address(this), auction.maxBidUser, _tokenId);
44,511
1
// Burns a specific amount of tokens._value The amount of token to be burned./
function burn(uint256 _value) public;
function burn(uint256 _value) public;
26,195
53
// Check if the buyer has bought tokens
uint256 tokensBought = amountBought[_buyers[i]]; if (tokensBought == 0) continue;
uint256 tokensBought = amountBought[_buyers[i]]; if (tokensBought == 0) continue;
22,983
43
// PUBLIC: Get NFT contract address based on the collectible type /
function getNFTAddress(CollectibleType collectibleType) internal view returns (address payable collectibleAddress)
function getNFTAddress(CollectibleType collectibleType) internal view returns (address payable collectibleAddress)
20,008
236
// the referenced Uniswap pair contract
IUniswapV2Pair public override pair;
IUniswapV2Pair public override pair;
16,707
1,067
// Ensure the sAAVE synth Proxy is correctly connected to the Synth;
proxysaave_i.setTarget(Proxyable(new_SynthsAAVE_contract));
proxysaave_i.setTarget(Proxyable(new_SynthsAAVE_contract));
49,028
153
// This function is an owner only function, it can change baseURI. /
function setBaseURI(string memory uri) public onlyOwner { require(!_baseURILocked_, "GhettoSharkhodd: BaseURI has been locked, it cannot be changed anymore."); _baseURI_ = uri; }
function setBaseURI(string memory uri) public onlyOwner { require(!_baseURILocked_, "GhettoSharkhodd: BaseURI has been locked, it cannot be changed anymore."); _baseURI_ = uri; }
38,261
44
// Step two
raffles[_raffleId].participants.pop(); raffles[_raffleId].tickets.pop();
raffles[_raffleId].participants.pop(); raffles[_raffleId].tickets.pop();
28,995
0
// allocate initial supply;
_balances[msg.sender] = _initialSupply;
_balances[msg.sender] = _initialSupply;
38,394
27
// Whether the uniswap proxy has been changed -> needs manual update
bool public isValidUniswapProxy = true;
bool public isValidUniswapProxy = true;
31,138
466
// Returns length of the voting power history array for the delegate specified; useful since reading an entire array just to get its length is expensive (gas cost)_of delegate to query voting power history length forreturn voting power history array length for the delegate of interest /
function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; }
function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; }
7,158
210
// queried by others ({ERC165Checker}).For an implementation, see {ERC165}./ Returns true if this contract implements the interface defined by`interfaceId`. See the correspondingto learn more about how these ids are created. This function call must use less than 30 000 gas. /
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
382
8
// Returns the active state of the game /
function getGameActive() public view returns(bool) { return gameActive; }
function getGameActive() public view returns(bool) { return gameActive; }
3,649
48
// Adds an address to the list of agents authorizedto make 'modifyBeneficiary' mutations to the registry. /
function addAuthorizedEditAgent(address agent) public onlyOwner
function addAuthorizedEditAgent(address agent) public onlyOwner
21,282
92
// vID must be available
Validator storage validator = idToValidators[vID]; uint256 currentTimeStamp = block.timestamp; uint256 interval = currentTimeStamp - validator.lastEpochTimestamp;
Validator storage validator = idToValidators[vID]; uint256 currentTimeStamp = block.timestamp; uint256 interval = currentTimeStamp - validator.lastEpochTimestamp;
23,505
27
// anyone that doesn't own any pupe gets maxTime remaining
function abandonTime(address _ownerAddress) public view returns (uint256)
function abandonTime(address _ownerAddress) public view returns (uint256)
16,887
61
// Check if genders match - male is really male
require(getData().kangarooIsMale(male) == true && getData().kangarooIsMale(female) == false,"Couple genders mismatched");
require(getData().kangarooIsMale(male) == true && getData().kangarooIsMale(female) == false,"Couple genders mismatched");
43,797
0
// ------------------------------------------------------ generic object events
event onNewTransaction(uint transactionId); event onUpdatedTransaction(uint transactionId); event onNewPurchase(uint purchaseId); event onUpdatedPurchase(uint purchaseId); event onNewProduct(bytes32 productId); event onUpdatedProduct(bytes32 productId); event onNewCategory(bytes32 categoryId); event onUpdatedCategory(bytes32 categoryId); event onNewSupplier(bytes32 supplierId); event onUpdatedSupplier(bytes32 supplierId);
event onNewTransaction(uint transactionId); event onUpdatedTransaction(uint transactionId); event onNewPurchase(uint purchaseId); event onUpdatedPurchase(uint purchaseId); event onNewProduct(bytes32 productId); event onUpdatedProduct(bytes32 productId); event onNewCategory(bytes32 categoryId); event onUpdatedCategory(bytes32 categoryId); event onNewSupplier(bytes32 supplierId); event onUpdatedSupplier(bytes32 supplierId);
54,390
147
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
14,871
3
// Burns a specific amount of tokens. _value The amount of token to be burned. /
function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); }
function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); }
5,994
0
// Interface for the Buy Back Reward contract that can be used to buildcustom logic to elevate user rewards /
interface IConditional { /** * @dev Returns whether a wallet passes the test. */ function passesTest(address wallet) external view returns (bool); }
interface IConditional { /** * @dev Returns whether a wallet passes the test. */ function passesTest(address wallet) external view returns (bool); }
16,742
84
// setting the number of selectors
assembly { mstore(selectors, numSelectors) }
assembly { mstore(selectors, numSelectors) }
18,369
24
// token是WETHοΌŒε…¨ιƒ¨ζηŽ°
IWETH(WETH).withdraw(balanceAfter); uint toCoinbase = _profit * _coinbasePercent / 100; uint toSender = balanceAfter - toCoinbase; require(toSender > 0, "CaV3: sender no profit"); _safeTransferETH(msg.sender, toSender); if(toCoinbase > 0){ if(_coinbaseAddress == EMPT){
IWETH(WETH).withdraw(balanceAfter); uint toCoinbase = _profit * _coinbasePercent / 100; uint toSender = balanceAfter - toCoinbase; require(toSender > 0, "CaV3: sender no profit"); _safeTransferETH(msg.sender, toSender); if(toCoinbase > 0){ if(_coinbaseAddress == EMPT){
18,628
6
// Convert signed 128.128 fixed point number into signed 64.64-bit fixed pointnumber rounding down.Revert on overflow.x signed 128.128-bin fixed point numberreturn signed 64.64-bit fixed point number /
function from128x128(int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } }
function from128x128(int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } }
5,795
64
// _numTokensWrapped++;we might just assign this
numTokensWrapped++;
numTokensWrapped++;
47,238
188
// Finish this.
(, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minEthIn, msg.value, to);
(, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minEthIn, msg.value, to);
31,546
37
// Decode a CBOR value into a Result instance. _cborValue An instance of `CBOR.Value`.return A `Result` instance. /
function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); }
function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); }
25,175
308
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but we allocate 0x80 bytes to keep the free memory pointer 32-byte word aligned. We will need 1 32-byte word to store the length, and 3 32-byte words to store a maximum of 78 digits. Total: 0x20 + 30x20 = 0x80.
str := add(mload(0x40), 0x80)
str := add(mload(0x40), 0x80)
18,444
11
// Prevents a function from being called with a gas price higher/ than the specified limit.//_gasPriceLimit The gas price upper-limit in Wei.
modifier withGasPriceLimit(uint256 _gasPriceLimit) { require(tx.gasprice <= _gasPriceLimit, "gas price too high"); _; }
modifier withGasPriceLimit(uint256 _gasPriceLimit) { require(tx.gasprice <= _gasPriceLimit, "gas price too high"); _; }
12,603
12
// Update buffer length
mstore(bufptr, add(buflen, mload(data))) src := add(data, 32)
mstore(bufptr, add(buflen, mload(data))) src := add(data, 32)
13,071
143
// Dispute
enum Period { evidence, // Evidence can be submitted. This is also when drawing has to take place. commit, // Jurors commit a hashed vote. This is skipped for courts without hidden votes. vote, // Jurors reveal/cast their vote depending on whether the court has hidden votes or not. appeal, // The dispute can be appealed. execution // Tokens are redistributed and the ruling is executed. }
enum Period { evidence, // Evidence can be submitted. This is also when drawing has to take place. commit, // Jurors commit a hashed vote. This is skipped for courts without hidden votes. vote, // Jurors reveal/cast their vote depending on whether the court has hidden votes or not. appeal, // The dispute can be appealed. execution // Tokens are redistributed and the ruling is executed. }
29,195