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
279
// Swap WETH for Sushi
pair.swap(amount0Out, amount1Out, bar, new bytes(0));
pair.swap(amount0Out, amount1Out, bar, new bytes(0));
25,766
21
// Fix for the ERC20 short address attack/
modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { doThrow("Short address attack!"); } _; }
modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { doThrow("Short address attack!"); } _; }
27,458
19
// Semantic version./ @custom:semver 1.7.0
string public constant version = "1.7.0";
string public constant version = "1.7.0";
24,818
6
// The interface for Graviton oracle router/Forwards data about crosschain locking/unlocking events to balance keepers/Artemij Artamonov - <array.clean@gmail.com>/Anton Davydov - <fetsorn@gmail.com>
interface IOracleRouterV2 { /// @notice User that can grant access permissions and perform privileged actions function owner() external view returns (address); /// @notice Transfers ownership of the contract to a new account (`_owner`). /// @dev Can only be called by the current owner. function setOwner(address _owner) external; /// @notice Look up if `user` can route data to balance keepers function canRoute(address user) external view returns (bool); /// @notice Sets the permission to route data to balance keepers /// @dev Can only be called by the current owner. function setCanRoute(address parser, bool _canRoute) external; /// @notice Routes value to balance keepers according to the type of event associated with topic0 /// @param uuid Unique identifier of the routed data /// @param chain Type of blockchain associated with the routed event, i.e. "EVM" /// @param emiter The blockchain-specific address where the data event originated /// @param topic0 Unique identifier of the event /// @param token The blockchain-specific token address /// @param sender The blockchain-specific address that sent the tokens /// @param receiver The blockchain-specific address to receive the tokens /// @dev receiver is always same as sender, kept for compatibility /// @param amount The amount of tokens function routeValue( bytes16 uuid, string memory chain, bytes memory emiter, bytes32 topic0, bytes memory token, bytes memory sender, bytes memory receiver, uint256 amount ) external; /// @notice Event emitted when the owner changes via #setOwner`. /// @param ownerOld The account that was the previous owner of the contract /// @param ownerNew The account that became the owner of the contract event SetOwner(address indexed ownerOld, address indexed ownerNew); /// @notice Event emitted when the `parser` permission is updated via `#setCanRoute` /// @param owner The owner account at the time of change /// @param parser The account whose permission to route data was updated /// @param newBool Updated permission event SetCanRoute( address indexed owner, address indexed parser, bool indexed newBool ); /// @notice Event emitted when data is routed /// @param uuid Unique identifier of the routed data /// @param chain Type of blockchain associated with the routed event, i.e. "EVM" /// @param emiter The blockchain-specific address where the data event originated /// @param token The blockchain-specific token address /// @param sender The blockchain-specific address that sent the tokens /// @param receiver The blockchain-specific address to receive the tokens /// @dev receiver is always same as sender, kept for compatibility /// @param amount The amount of tokens event RouteValue( bytes16 uuid, string chain, bytes emiter, bytes indexed token, bytes indexed sender, bytes indexed receiver, uint256 amount ); }
interface IOracleRouterV2 { /// @notice User that can grant access permissions and perform privileged actions function owner() external view returns (address); /// @notice Transfers ownership of the contract to a new account (`_owner`). /// @dev Can only be called by the current owner. function setOwner(address _owner) external; /// @notice Look up if `user` can route data to balance keepers function canRoute(address user) external view returns (bool); /// @notice Sets the permission to route data to balance keepers /// @dev Can only be called by the current owner. function setCanRoute(address parser, bool _canRoute) external; /// @notice Routes value to balance keepers according to the type of event associated with topic0 /// @param uuid Unique identifier of the routed data /// @param chain Type of blockchain associated with the routed event, i.e. "EVM" /// @param emiter The blockchain-specific address where the data event originated /// @param topic0 Unique identifier of the event /// @param token The blockchain-specific token address /// @param sender The blockchain-specific address that sent the tokens /// @param receiver The blockchain-specific address to receive the tokens /// @dev receiver is always same as sender, kept for compatibility /// @param amount The amount of tokens function routeValue( bytes16 uuid, string memory chain, bytes memory emiter, bytes32 topic0, bytes memory token, bytes memory sender, bytes memory receiver, uint256 amount ) external; /// @notice Event emitted when the owner changes via #setOwner`. /// @param ownerOld The account that was the previous owner of the contract /// @param ownerNew The account that became the owner of the contract event SetOwner(address indexed ownerOld, address indexed ownerNew); /// @notice Event emitted when the `parser` permission is updated via `#setCanRoute` /// @param owner The owner account at the time of change /// @param parser The account whose permission to route data was updated /// @param newBool Updated permission event SetCanRoute( address indexed owner, address indexed parser, bool indexed newBool ); /// @notice Event emitted when data is routed /// @param uuid Unique identifier of the routed data /// @param chain Type of blockchain associated with the routed event, i.e. "EVM" /// @param emiter The blockchain-specific address where the data event originated /// @param token The blockchain-specific token address /// @param sender The blockchain-specific address that sent the tokens /// @param receiver The blockchain-specific address to receive the tokens /// @dev receiver is always same as sender, kept for compatibility /// @param amount The amount of tokens event RouteValue( bytes16 uuid, string chain, bytes emiter, bytes indexed token, bytes indexed sender, bytes indexed receiver, uint256 amount ); }
15,684
297
// Max balance doesn't apply to the token manager itself
if (_receiver == address(this)) { return true; }
if (_receiver == address(this)) { return true; }
7,339
5
// Creates `amount` new tokens for `to`.
* See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint( address to, uint256 amount ) public { require(isMinter(_msgSender()), "Transaction signer is not a minter"); _mint(to, amount); }
* See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint( address to, uint256 amount ) public { require(isMinter(_msgSender()), "Transaction signer is not a minter"); _mint(to, amount); }
21,543
3
// Function to receive Ether. msg.data must be empty
receive() external payable {} // Fallback function is called when msg.data is not empty fallback() external payable { emit Paid(msg.sender, msg.value); }
receive() external payable {} // Fallback function is called when msg.data is not empty fallback() external payable { emit Paid(msg.sender, msg.value); }
20,948
37
// To supply medicines from distributor to retailer
function Retail(uint256 _medicineID) public { require(_medicineID > 0 && _medicineID <= medicineCtr); uint256 _id = findRET(msg.sender); require(_id > 0); require(MedicineStock[_medicineID].stage == STAGE.Distribution); MedicineStock[_medicineID].RETid = _id; MedicineStock[_medicineID].stage = STAGE.Retail; }
function Retail(uint256 _medicineID) public { require(_medicineID > 0 && _medicineID <= medicineCtr); uint256 _id = findRET(msg.sender); require(_id > 0); require(MedicineStock[_medicineID].stage == STAGE.Distribution); MedicineStock[_medicineID].RETid = _id; MedicineStock[_medicineID].stage = STAGE.Retail; }
914
6
// mapping of user addresses to fee discount
mapping (address => uint256) discounts;
mapping (address => uint256) discounts;
43,205
1
// for mainnet currency, such as ETH, BNB etc, we hard coded its contract address as 0x0
address public constant mainnetTokenAddress = address(0x0);
address public constant mainnetTokenAddress = address(0x0);
11,534
10
// 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; address private immutable _CACHED_THIS; 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 = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } }
* 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; address private immutable _CACHED_THIS; 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 = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } }
18,658
41
// : Creates a Bequest _owner: To be owner of Bequest _referral: Referral code, if any /
function _createBequest(address _owner, string calldata _referral) internal { require(!isOwner(_owner), "Already owner"); uint256 creationFee = getCreationFee(_referral); require(msg.value >= creationFee, "Invalid fee"); if (bytes(_referral).length != 0) { Referral storage referralDetails = referralCodes[_referral]; if (referralDetails.profitShare > 0) { uint256 profit = (msg.value * referralDetails.profitShare) / 100; referralDetails.profit += profit; referralProfit += profit; } referralDetails.usesLeft--; } Bequest storage bequest = addressToBequest[_owner]; bequest.timestamp = uint96(block.timestamp); bequest.lastPaidYearlyFee = uint96(block.timestamp); bequest.renewalRate = ONE_YEAR; emit CreatedBequest(_owner); }
function _createBequest(address _owner, string calldata _referral) internal { require(!isOwner(_owner), "Already owner"); uint256 creationFee = getCreationFee(_referral); require(msg.value >= creationFee, "Invalid fee"); if (bytes(_referral).length != 0) { Referral storage referralDetails = referralCodes[_referral]; if (referralDetails.profitShare > 0) { uint256 profit = (msg.value * referralDetails.profitShare) / 100; referralDetails.profit += profit; referralProfit += profit; } referralDetails.usesLeft--; } Bequest storage bequest = addressToBequest[_owner]; bequest.timestamp = uint96(block.timestamp); bequest.lastPaidYearlyFee = uint96(block.timestamp); bequest.renewalRate = ONE_YEAR; emit CreatedBequest(_owner); }
28,187
55
// User-triggered (!) fund migrations in case contract got updated Similar to withdraw but we use a successor account instead As we don't store user tokens list on chain, it has to be passed from the outside
function migrateFunds(address[] _tokens) { // Get the latest successor in the chain require(successor != address(0)); TokenStore newExchange = TokenStore(successor); for (uint16 n = 0; n < 20; n++) { // We will look past 20 contracts in the future address nextSuccessor = newExchange.successor(); if (nextSuccessor == address(this)) { // Circular succession revert(); } if (nextSuccessor == address(0)) { // We reached the newest, stop break; } newExchange = TokenStore(nextSuccessor); } // Ether uint etherAmount = tokens[0][msg.sender]; if (etherAmount > 0) { tokens[0][msg.sender] = 0; newExchange.depositForUser.value(etherAmount)(msg.sender); } // Tokens for (n = 0; n < _tokens.length; n++) { address token = _tokens[n]; require(token != address(0)); // 0 = Ether, we handle it above uint tokenAmount = tokens[token][msg.sender]; if (tokenAmount == 0) { continue; } if (!Token(token).approve(newExchange, tokenAmount)) { revert(); } tokens[token][msg.sender] = 0; newExchange.depositTokenForUser(token, tokenAmount, msg.sender); } FundsMigrated(msg.sender); }
function migrateFunds(address[] _tokens) { // Get the latest successor in the chain require(successor != address(0)); TokenStore newExchange = TokenStore(successor); for (uint16 n = 0; n < 20; n++) { // We will look past 20 contracts in the future address nextSuccessor = newExchange.successor(); if (nextSuccessor == address(this)) { // Circular succession revert(); } if (nextSuccessor == address(0)) { // We reached the newest, stop break; } newExchange = TokenStore(nextSuccessor); } // Ether uint etherAmount = tokens[0][msg.sender]; if (etherAmount > 0) { tokens[0][msg.sender] = 0; newExchange.depositForUser.value(etherAmount)(msg.sender); } // Tokens for (n = 0; n < _tokens.length; n++) { address token = _tokens[n]; require(token != address(0)); // 0 = Ether, we handle it above uint tokenAmount = tokens[token][msg.sender]; if (tokenAmount == 0) { continue; } if (!Token(token).approve(newExchange, tokenAmount)) { revert(); } tokens[token][msg.sender] = 0; newExchange.depositTokenForUser(token, tokenAmount, msg.sender); } FundsMigrated(msg.sender); }
31,060
155
// EIP712 type data. solhint-disable-next-line
bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version)");
bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version)");
34,239
57
// trophyId to trophyName
mapping (uint256 => bytes32) public trophies;
mapping (uint256 => bytes32) public trophies;
30,675
3
// note: do not use a require statment because that will TranchedPool kill execution
if (_interestPaymentAmount > 0) { _allocateRewards(_interestPaymentAmount); }
if (_interestPaymentAmount > 0) { _allocateRewards(_interestPaymentAmount); }
40,591
7
// "SPDX-License-Identifier: UNLICENSED "/ SafeMath Math operations with safety checks that throw on error /
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } }
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } }
26,041
13
// Set the vault struct's properties
contractsCache.vaultManager.setVaultStatus(msg.sender, 1); contractsCache.vaultManager.increaseVaultColl(msg.sender, vars.netColl); contractsCache.vaultManager.increaseVaultDebt(msg.sender, vars.compositeDebt); contractsCache.vaultManager.updateVaultRewardSnapshots(msg.sender); vars.stake = contractsCache.vaultManager.updateStakeAndTotalStakes(msg.sender); sortedVaults.insert(msg.sender, vars.NICR, _upperHint, _lowerHint); vars.arrayIndex = contractsCache.vaultManager.addVaultOwnerToArray(msg.sender); emit VaultCreated(msg.sender, vars.arrayIndex);
contractsCache.vaultManager.setVaultStatus(msg.sender, 1); contractsCache.vaultManager.increaseVaultColl(msg.sender, vars.netColl); contractsCache.vaultManager.increaseVaultDebt(msg.sender, vars.compositeDebt); contractsCache.vaultManager.updateVaultRewardSnapshots(msg.sender); vars.stake = contractsCache.vaultManager.updateStakeAndTotalStakes(msg.sender); sortedVaults.insert(msg.sender, vars.NICR, _upperHint, _lowerHint); vars.arrayIndex = contractsCache.vaultManager.addVaultOwnerToArray(msg.sender); emit VaultCreated(msg.sender, vars.arrayIndex);
31,256
74
// https:explorer.optimism.io/address/0x1228c7D8BBc5bC53DB181bD7B1fcE765aa83bF8A
address public constant new_FuturesMarketLINK_contract = 0x1228c7D8BBc5bC53DB181bD7B1fcE765aa83bF8A;
address public constant new_FuturesMarketLINK_contract = 0x1228c7D8BBc5bC53DB181bD7B1fcE765aa83bF8A;
22,575
8
// cannot be settled
require( id != 0 && gameMatch[id].settled == false , "INVALID_GAME_ID"); gameMatch[id] = GameMatch({ settled: false, date: block.timestamp, visitorTeam: visitorTeamId, homeTeam: teamId, venue: venueId
require( id != 0 && gameMatch[id].settled == false , "INVALID_GAME_ID"); gameMatch[id] = GameMatch({ settled: false, date: block.timestamp, visitorTeam: visitorTeamId, homeTeam: teamId, venue: venueId
9,281
31
// Set that we have revealed the final base token URI, and lock the reveal so that the token URI is permanent
function freezeMetadata() public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Only an admin can finalize the metadata"); require(metadataIsFrozen != true, "Can no longer set the metadata once it has been frozen"); metadataIsFrozen = true; }
function freezeMetadata() public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Only an admin can finalize the metadata"); require(metadataIsFrozen != true, "Can no longer set the metadata once it has been frozen"); metadataIsFrozen = true; }
5,523
306
// try to do transfer and mint a heart
uint256 heartId = GameDataLib.transferButterfly(data, tokenId, from, to, currentTimestamp); ERC721Manager.mint(erc721Data, from, heartId);
uint256 heartId = GameDataLib.transferButterfly(data, tokenId, from, to, currentTimestamp); ERC721Manager.mint(erc721Data, from, heartId);
32,105
26
// Call to the signed zone controller to update the zone API endpoint.
_SIGNED_ZONE_CONTROLLER.updateAPIEndpoint(zone, newApiEndpoint);
_SIGNED_ZONE_CONTROLLER.updateAPIEndpoint(zone, newApiEndpoint);
19,301
242
// Order details are exposed through directly accessing this mapping, or through the getter functions below for each of the order&39;s fields.
mapping(bytes32 => Order) public orders; event LogFeeUpdated(uint256 previousFee, uint256 nextFee); event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
mapping(bytes32 => Order) public orders; event LogFeeUpdated(uint256 previousFee, uint256 nextFee); event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
32,819
126
// Standard transferFrom overridden to have a chance to thaw sender's tokens._from address the address which you want to send tokens from _to address the address which you want to transfer to _value uint256 the amount of tokens to be transferred return true iff operation was successfully completed /
function transferFrom(address _from, address _to, uint256 _value) public payloadSizeIs(3 * 32) returns (bool)
function transferFrom(address _from, address _to, uint256 _value) public payloadSizeIs(3 * 32) returns (bool)
35,843
24
// external NFT: copy token info from externSeqIdMap
info1 = externSeqIdMap[wd.seqId];
info1 = externSeqIdMap[wd.seqId];
35,860
19
// Increases the level of the item by one. This function will revert if the player does not have enough tokens. _itemId The item which should be upgraded. /
function upgradeItem(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId)
function upgradeItem(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId)
52,546
23
// calculate the transaction fee - 1/40 = 2.5% fee
uint256 fee = SafeMath.div(previousHolderShare, 40); owner.transfer(fee);
uint256 fee = SafeMath.div(previousHolderShare, 40); owner.transfer(fee);
59,256
41
// Checks if a list of modules are registered. _modules The list of modules address.return true if all the modules are registered. /
function isRegisteredModule(address[] _modules) external view returns (bool) { for(uint i = 0; i < _modules.length; i++) { if (!modules[_modules[i]].exists) { return false; } } return true; }
function isRegisteredModule(address[] _modules) external view returns (bool) { for(uint i = 0; i < _modules.length; i++) { if (!modules[_modules[i]].exists) { return false; } } return true; }
2,378
47
// BurnableStandard ERC20 token /
contract Burnable is StandardToken { using SafeMath for uint; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Burn(_from, _value); emit Transfer(_from, address(0), _value); return true; } function transfer(address _to, uint _value) public returns (bool success) { require(_to != 0x0); //use burn return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(_to != 0x0); //use burn return super.transferFrom(_from, _to, _value); } }
contract Burnable is StandardToken { using SafeMath for uint; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Burn(_from, _value); emit Transfer(_from, address(0), _value); return true; } function transfer(address _to, uint _value) public returns (bool success) { require(_to != 0x0); //use burn return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(_to != 0x0); //use burn return super.transferFrom(_from, _to, _value); } }
42,006
4
// get product id from underlying, strike and collateral address function will still return even if some of the assets are not registered engineIdengine id underlyingIdunderlying id strikeIdstrike id collateralIdcollateral id /
function getProductId(uint8 engineId, uint8 underlyingId, uint8 strikeId, uint8 collateralId) internal pure returns (uint32 id)
function getProductId(uint8 engineId, uint8 underlyingId, uint8 strikeId, uint8 collateralId) internal pure returns (uint32 id)
25,732
87
// funder info
if(orders[msg.sender].paymentEther == 0) { indexedFunders[funderCount] = msg.sender; funderCount = funderCount.add(1); orders[msg.sender].state = eOrderstate.NONE; }
if(orders[msg.sender].paymentEther == 0) { indexedFunders[funderCount] = msg.sender; funderCount = funderCount.add(1); orders[msg.sender].state = eOrderstate.NONE; }
29,851
178
// HIPPO tokens created per block.
uint256 public hippoPerBlock;
uint256 public hippoPerBlock;
33,793
142
// the id of nft token
uint256 nftTokenId;
uint256 nftTokenId;
23,421
101
// BurgerToken with Governance.
contract BurgerToken is ERC20("burger.money", "BURGER"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } }
contract BurgerToken is ERC20("burger.money", "BURGER"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } }
85,173
104
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
cooAddress = msg.sender;
30,786
24
// Withdraws from an account's balance, sending it back to the caller.Relay Managers call this to retrieve their revenue, and `Paymasters` can also use it to reduce their funding.Emits a `Withdrawn` event. /
function withdraw(address payable dest, uint256 amount) external;
function withdraw(address payable dest, uint256 amount) external;
11,752
6
// Custom data types
struct TriggeredLimit{ address first; address[] sameBlock; uint block; } struct TriggeredLimitId{ address trader; uint pairIndex; uint index; StorageInterfaceV5.LimitOrder order; } enum OpenLimitOrderType{ LEGACY, REVERSAL, MOMENTUM } // State uint public currentOrder; // current order in round uint public currentRound; // current round (1 round = 50 orders) mapping(uint => uint) public roundTokens; // total token rewards for a round mapping(address => mapping(uint => uint)) public roundOrdersToClaim; // orders to claim from a round (out of 50) mapping(address => uint) public tokensToClaim; // rewards other than pool (first & same block) mapping( address => mapping( uint => mapping( uint => mapping( StorageInterfaceV5.LimitOrder => TriggeredLimit ) ) ) ) public triggeredLimits; // limits being triggered mapping(address => mapping(uint => mapping(uint => OpenLimitOrderType))) public openLimitOrderTypes; // Statistics mapping(address => uint) public tokensClaimed; // 1e18 uint public tokensClaimedTotal; // 1e18 // Events event NumberUpdated(string name, uint value); event PercentagesUpdated(uint firstP, uint sameBlockP, uint poolP); event TriggeredFirst(TriggeredLimitId id, address bot); event TriggeredSameBlock(TriggeredLimitId id, address bot); event TriggerUnregistered(TriggeredLimitId id); event TriggerRewarded(TriggeredLimitId id, address first, uint sameBlockCount, uint reward); event PoolTokensClaimed(address bot, uint fromRound, uint toRound, uint tokens); event TokensClaimed(address bot, uint tokens); function initialize( StorageInterfaceV5 _storageT, uint _triggerTimeout, uint _sameBlockLimit, uint _firstP, uint _sameBlockP, uint _poolP ) external initializer { require(address(_storageT) != address(0) && _triggerTimeout >= MIN_TRIGGER_TIMEOUT && _sameBlockLimit >= MIN_SAME_BLOCK_LIMIT && _firstP + _sameBlockP + _poolP == 100, "WRONG_PARAMS"); storageT = _storageT; triggerTimeout = _triggerTimeout; sameBlockLimit = _sameBlockLimit; firstP = _firstP; sameBlockP = _sameBlockP; poolP = _poolP; currentOrder = 1; }
struct TriggeredLimit{ address first; address[] sameBlock; uint block; } struct TriggeredLimitId{ address trader; uint pairIndex; uint index; StorageInterfaceV5.LimitOrder order; } enum OpenLimitOrderType{ LEGACY, REVERSAL, MOMENTUM } // State uint public currentOrder; // current order in round uint public currentRound; // current round (1 round = 50 orders) mapping(uint => uint) public roundTokens; // total token rewards for a round mapping(address => mapping(uint => uint)) public roundOrdersToClaim; // orders to claim from a round (out of 50) mapping(address => uint) public tokensToClaim; // rewards other than pool (first & same block) mapping( address => mapping( uint => mapping( uint => mapping( StorageInterfaceV5.LimitOrder => TriggeredLimit ) ) ) ) public triggeredLimits; // limits being triggered mapping(address => mapping(uint => mapping(uint => OpenLimitOrderType))) public openLimitOrderTypes; // Statistics mapping(address => uint) public tokensClaimed; // 1e18 uint public tokensClaimedTotal; // 1e18 // Events event NumberUpdated(string name, uint value); event PercentagesUpdated(uint firstP, uint sameBlockP, uint poolP); event TriggeredFirst(TriggeredLimitId id, address bot); event TriggeredSameBlock(TriggeredLimitId id, address bot); event TriggerUnregistered(TriggeredLimitId id); event TriggerRewarded(TriggeredLimitId id, address first, uint sameBlockCount, uint reward); event PoolTokensClaimed(address bot, uint fromRound, uint toRound, uint tokens); event TokensClaimed(address bot, uint tokens); function initialize( StorageInterfaceV5 _storageT, uint _triggerTimeout, uint _sameBlockLimit, uint _firstP, uint _sameBlockP, uint _poolP ) external initializer { require(address(_storageT) != address(0) && _triggerTimeout >= MIN_TRIGGER_TIMEOUT && _sameBlockLimit >= MIN_SAME_BLOCK_LIMIT && _firstP + _sameBlockP + _poolP == 100, "WRONG_PARAMS"); storageT = _storageT; triggerTimeout = _triggerTimeout; sameBlockLimit = _sameBlockLimit; firstP = _firstP; sameBlockP = _sameBlockP; poolP = _poolP; currentOrder = 1; }
16,963
5
// @custom:salt EndPoint
contract EndPoint { address public immutable factory_; address public owner; uint256 public i; event addedOne(uint256 indexed i); event addedTwo(uint256 indexed i); event UpgradeLock(bool indexed lock); constructor(address f) { factory_ = f; } function addOne() public { i++; emit addedOne(i); } function addTwo() public { i = i + 2; emit addedTwo(i); } }
contract EndPoint { address public immutable factory_; address public owner; uint256 public i; event addedOne(uint256 indexed i); event addedTwo(uint256 indexed i); event UpgradeLock(bool indexed lock); constructor(address f) { factory_ = f; } function addOne() public { i++; emit addedOne(i); } function addTwo() public { i = i + 2; emit addedTwo(i); } }
2,745
60
// Max, min and sum of debt per underlying and collateral.
function debt(bytes6 baseId, bytes6 ilkId) external view returns (DataTypes.Debt memory);
function debt(bytes6 baseId, bytes6 ilkId) external view returns (DataTypes.Debt memory);
16,311
2
// with rounding of last digit
uint256 _quotient = (( _numerator.div(denominator)) + 5) / 10; return ( _quotient);
uint256 _quotient = (( _numerator.div(denominator)) + 5) / 10; return ( _quotient);
40,719
85
// Project's owner can widthdraw contract's balance
function widthdraw(address to, uint amount) public onlyOwner { to.transfer(amount); }
function widthdraw(address to, uint amount) public onlyOwner { to.transfer(amount); }
36,641
61
// Function called by _adjustPosition()/guessedBorrow First guess to the borrow amount to maximise revenue/It computes the optimal collateral ratio and adjusts deposits/borrows accordingly
function _adjustPosition(uint256 guessedBorrow) internal override { uint256 _debtOutstanding = poolManager.debtOutstanding(); uint256 wantBalance = _balanceOfWant(); // deposit available want as collateral if (wantBalance > _debtOutstanding && wantBalance - _debtOutstanding > minWant) { _depositCollateral(wantBalance - _debtOutstanding); // Updating the `wantBalance` value wantBalance = _balanceOfWant(); } (uint256 deposits, uint256 borrows) = getCurrentPosition(); guessedBorrow = (guessedBorrow == type(uint256).max) ? borrows : guessedBorrow; uint256 _targetCollatRatio; if (boolParams.automaticallyComputeCollatRatio) { _targetCollatRatio = _computeOptimalCollatRatio( wantBalance + deposits - borrows, deposits, borrows, guessedBorrow ); } else { _targetCollatRatio = targetCollatRatio; } // check current position uint256 currentCollatRatio = _getCollatRatio(deposits, borrows); // Either we need to free some funds OR we want to be max levered if (_debtOutstanding > wantBalance) { // we should free funds uint256 amountRequired = _debtOutstanding - wantBalance; // NOTE: vault will take free funds during the next harvest _freeFunds(amountRequired, deposits, borrows); } else if (currentCollatRatio < _targetCollatRatio) { // we should lever up if (_targetCollatRatio - currentCollatRatio > minRatio) { // we only act on relevant differences _leverMax(deposits, borrows); } } else if (currentCollatRatio > _targetCollatRatio) { if (currentCollatRatio - _targetCollatRatio > minRatio) { uint256 newBorrow = _getBorrowFromSupply(deposits - borrows, _targetCollatRatio); _leverDownTo(newBorrow, deposits, borrows); } } }
function _adjustPosition(uint256 guessedBorrow) internal override { uint256 _debtOutstanding = poolManager.debtOutstanding(); uint256 wantBalance = _balanceOfWant(); // deposit available want as collateral if (wantBalance > _debtOutstanding && wantBalance - _debtOutstanding > minWant) { _depositCollateral(wantBalance - _debtOutstanding); // Updating the `wantBalance` value wantBalance = _balanceOfWant(); } (uint256 deposits, uint256 borrows) = getCurrentPosition(); guessedBorrow = (guessedBorrow == type(uint256).max) ? borrows : guessedBorrow; uint256 _targetCollatRatio; if (boolParams.automaticallyComputeCollatRatio) { _targetCollatRatio = _computeOptimalCollatRatio( wantBalance + deposits - borrows, deposits, borrows, guessedBorrow ); } else { _targetCollatRatio = targetCollatRatio; } // check current position uint256 currentCollatRatio = _getCollatRatio(deposits, borrows); // Either we need to free some funds OR we want to be max levered if (_debtOutstanding > wantBalance) { // we should free funds uint256 amountRequired = _debtOutstanding - wantBalance; // NOTE: vault will take free funds during the next harvest _freeFunds(amountRequired, deposits, borrows); } else if (currentCollatRatio < _targetCollatRatio) { // we should lever up if (_targetCollatRatio - currentCollatRatio > minRatio) { // we only act on relevant differences _leverMax(deposits, borrows); } } else if (currentCollatRatio > _targetCollatRatio) { if (currentCollatRatio - _targetCollatRatio > minRatio) { uint256 newBorrow = _getBorrowFromSupply(deposits - borrows, _targetCollatRatio); _leverDownTo(newBorrow, deposits, borrows); } } }
19,807
12
// allows the requester to cancel their adoption request /
function cancelAdoptionRequest(bytes5 catId) { AdoptionRequest storage existingRequest = adoptionRequests[catId]; require(existingRequest.exists); require(existingRequest.requester == msg.sender); uint price = existingRequest.price; adoptionRequests[catId] = AdoptionRequest(false, catId, 0x0, 0); msg.sender.transfer(price); AdoptionRequestCancelled(catId); }
function cancelAdoptionRequest(bytes5 catId) { AdoptionRequest storage existingRequest = adoptionRequests[catId]; require(existingRequest.exists); require(existingRequest.requester == msg.sender); uint price = existingRequest.price; adoptionRequests[catId] = AdoptionRequest(false, catId, 0x0, 0); msg.sender.transfer(price); AdoptionRequestCancelled(catId); }
35,688
40
// find amount to buy.
uint256 loopIndex = 1; uint256 actualBuyAmtFinal = 0; for (uint256 actualBuyAmt = buyAmt; actualBuyAmt <= maxSpent; actualBuyAmt += buyAmt){ if (actualBuyAmt > bal){ break; }
uint256 loopIndex = 1; uint256 actualBuyAmtFinal = 0; for (uint256 actualBuyAmt = buyAmt; actualBuyAmt <= maxSpent; actualBuyAmt += buyAmt){ if (actualBuyAmt > bal){ break; }
26,336
82
// if the account is blacklisted from transacting
mapping (address => bool) public isBlacklisted;
mapping (address => bool) public isBlacklisted;
16,496
20
// Buyer withdraws offer. IPFS hash contains reason for withdrawl.
function withdrawOffer(uint listingID, uint offerID, bytes32 _ipfsHash) public { Offer storage offer = offers[listingID][offerID]; require( msg.sender == offer.buyer, "Restricted to buyer" ); require(offer.status == 1, "status != created"); refundBuyer(listingID, offerID); if (offer.commission > 0) { refundCommission(listingID, offerID); } emit OfferWithdrawn(msg.sender, listingID, offerID, _ipfsHash); delete offers[listingID][offerID]; }
function withdrawOffer(uint listingID, uint offerID, bytes32 _ipfsHash) public { Offer storage offer = offers[listingID][offerID]; require( msg.sender == offer.buyer, "Restricted to buyer" ); require(offer.status == 1, "status != created"); refundBuyer(listingID, offerID); if (offer.commission > 0) { refundCommission(listingID, offerID); } emit OfferWithdrawn(msg.sender, listingID, offerID, _ipfsHash); delete offers[listingID][offerID]; }
35,652
332
// Get the current value of the linear growth limiter.// return The current value.
function get(LinearGrowthLimiter storage self) internal view returns (uint256) { uint256 elapsed = block.number - self.lastBlock; if (elapsed == 0) { return self.lastValue; } uint256 delta = elapsed * self.rate / FIXED_POINT_SCALAR; uint256 value = self.lastValue + delta; return value > self.maximum ? self.maximum : value; }
function get(LinearGrowthLimiter storage self) internal view returns (uint256) { uint256 elapsed = block.number - self.lastBlock; if (elapsed == 0) { return self.lastValue; } uint256 delta = elapsed * self.rate / FIXED_POINT_SCALAR; uint256 value = self.lastValue + delta; return value > self.maximum ? self.maximum : value; }
69,087
123
// owner of booster can set reward hook
require(IDeposit(operator).owner() == msg.sender, "!owner"); rewardHook = _hook;
require(IDeposit(operator).owner() == msg.sender, "!owner"); rewardHook = _hook;
66,689
24
// Events /
event BidSubmission(address indexed sender, uint256 amount);
event BidSubmission(address indexed sender, uint256 amount);
2,543
135
// sets approval for contracts that require access to assets held by this contract /
function setApprovals() external { (address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18); for (uint256 i; i < tokenAddresses.length; i++) { IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken; CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool; YearnVault yearnVault = YearnVault(tokenAddresses[i]); _maxApprove(curveLpToken, address(curveMetapool)); _maxApprove(curveLpToken, address(yearnVault)); _maxApprove(threeCrv, address(curveMetapool)); } _maxApprove(IERC20(address(setToken)), address(staking)); }
function setApprovals() external { (address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18); for (uint256 i; i < tokenAddresses.length; i++) { IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken; CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool; YearnVault yearnVault = YearnVault(tokenAddresses[i]); _maxApprove(curveLpToken, address(curveMetapool)); _maxApprove(curveLpToken, address(yearnVault)); _maxApprove(threeCrv, address(curveMetapool)); } _maxApprove(IERC20(address(setToken)), address(staking)); }
19,372
46
// 管理员冻结发布者和商品
function setauctionother(uint auctids) public onlyOwner{ auctionlist storage c = auctionlisting[auctids]; btyc.freezeAccount(c.adduser, true); c.ifend = true; c.ifsend = 3; }
function setauctionother(uint auctids) public onlyOwner{ auctionlist storage c = auctionlisting[auctids]; btyc.freezeAccount(c.adduser, true); c.ifend = true; c.ifsend = 3; }
20,530
41
// called by any participants /
function getSecretSharingDatas( bytes32 taskId, uint64 round, address[] calldata senders, address receiver ) public view roundExists(taskId, round) roundcmmtExists(taskId, round)
function getSecretSharingDatas( bytes32 taskId, uint64 round, address[] calldata senders, address receiver ) public view roundExists(taskId, round) roundcmmtExists(taskId, round)
41,671
30
// Treasury Config, provided at setup, for finding the treasury address.
address treasuryConfig;
address treasuryConfig;
38,091
55
// conversion ratio for token1 and token2 1:10 ratio will be:ratio1 = 1ratio2 = 10
uint256 public ratio1; uint256 public ratio2; mapping(address => Record[]) public ledger; event StakeStart(address indexed user, uint256 value, uint256 index); event StakeEnd(address indexed user, uint256 value, uint256 penalty, uint256 interest, uint256 index); constructor(
uint256 public ratio1; uint256 public ratio2; mapping(address => Record[]) public ledger; event StakeStart(address indexed user, uint256 value, uint256 index); event StakeEnd(address indexed user, uint256 value, uint256 penalty, uint256 interest, uint256 index); constructor(
30,894
21
// Cannot withdraw more than currently staked This condition can happen if while tokens are locked for withdrawal a slash condition happens In that case the total staked tokens could be below the amount to be withdrawn
if (stake.tokensLocked > stake.tokensStaked) { return stake.tokensStaked; }
if (stake.tokensLocked > stake.tokensStaked) { return stake.tokensStaked; }
42,447
0
// Last maxWeightPerSecond setting of PowerIndexPool. //Last wrapperMode setting of PowerIndexPool. //Timestamp, when possible to call finishReplace. /
) public PowerIndexPoolController(_pool, _poolWrapper, _wrapperFactory, _weightsStrategy) {} function _bindNewToken( address _piToken, uint256 _balance, uint256 _denormalizedWeight ) internal override { _initiateReplace(_denormalizedWeight); pool.bind(address(_piToken), _balance, _denormalizedWeight, block.timestamp + 1, replaceFinishTimestamp); }
) public PowerIndexPoolController(_pool, _poolWrapper, _wrapperFactory, _weightsStrategy) {} function _bindNewToken( address _piToken, uint256 _balance, uint256 _denormalizedWeight ) internal override { _initiateReplace(_denormalizedWeight); pool.bind(address(_piToken), _balance, _denormalizedWeight, block.timestamp + 1, replaceFinishTimestamp); }
43,224
47
// ========== MUTATIVE FUNCTIONS ========== //Claims rewards from the locker and notify an amount to the LGV4/_amount amount to notify after the claim
function claimAndNotify(uint256 _amount) external { require(locker != address(0), "locker not set"); ILocker(locker).claimRewards(tokenReward, address(this)); _notifyReward(tokenReward, _amount); }
function claimAndNotify(uint256 _amount) external { require(locker != address(0), "locker not set"); ILocker(locker).claimRewards(tokenReward, address(this)); _notifyReward(tokenReward, _amount); }
38,174
311
// Returns the protocolFeeMultiplier
function protocolFeeMultiplier() external view returns (uint256);
function protocolFeeMultiplier() external view returns (uint256);
9,340
133
// Value is returned in ray (1027)
return spotter.par();
return spotter.par();
76,922
73
// Converts an unsigned uint256 into a signed int256. Requirements: - input must be less than or equal to maxInt256. _Available since v3.0._ /
function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); }
function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); }
26,516
65
// NOTE: It is an intended substraction separation to correctly round dates
uint _daysLong = (_date / 1 days) - (_lastTransferDate / 1 days); uint _bmcDays = _transferPeriod.user2bmcDays[_userKey]; return _bmcDays.add(_transferPeriod.user2balance[_userKey] * _daysLong);
uint _daysLong = (_date / 1 days) - (_lastTransferDate / 1 days); uint _bmcDays = _transferPeriod.user2bmcDays[_userKey]; return _bmcDays.add(_transferPeriod.user2balance[_userKey] * _daysLong);
76,326
18
// StableSwap strategy for Gondola DAIe/USDTe /
contract GondolaStrategyForPoolDAIeUSDTe is YakStrategy { using SafeMath for uint; IGondolaChef public stakingContract; IGondolaPool public poolContract; address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; address private constant USDTe = 0xc7198437980c041c805A1EDcbA50c1Ce5db95118; address private constant DAIe = 0xd586E7F844cEa2F87f50152665BCbc2C279D8d70; IRouter private constant ROUTER = IRouter(0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106); uint public PID; constructor( string memory _name, address _depositToken, address _rewardToken, address _stakingContract, address _poolContract, address _timelock, uint _pid, uint _minTokensToReinvest, uint _adminFeeBips, uint _devFeeBips, uint _reinvestRewardBips ) { name = _name; depositToken = IPair(_depositToken); rewardToken = IERC20(_rewardToken); stakingContract = IGondolaChef(_stakingContract); poolContract = IGondolaPool(_poolContract); PID = _pid; devAddr = msg.sender; setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } /** * @notice Approve tokens for use in Strategy * @dev Restricted to avoid griefing attacks */ function setAllowances() public override onlyOwner { depositToken.approve(address(stakingContract), MAX_UINT); rewardToken.approve(address(ROUTER), MAX_UINT); IERC20(USDTe).approve(address(poolContract), MAX_UINT); IERC20(DAIe).approve(address(poolContract), MAX_UINT); } /** * @notice Deposit tokens to receive receipt tokens * @param amount Amount of tokens to deposit */ function deposit(uint amount) external override { _deposit(msg.sender, amount); } /** * @notice Deposit using Permit * @param amount Amount of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function depositFor(address account, uint amount) external override { _deposit(account, amount); } function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "GondolaStrategyForStableSwap::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); } function withdraw(uint amount) external override { uint depositTokenAmount = getDepositTokensForShares(amount); if (depositTokenAmount > 0) { _withdrawDepositTokens(depositTokenAmount); require(depositToken.transfer(msg.sender, depositTokenAmount), "GondolaStrategyForStableSwap::withdraw"); _burn(msg.sender, amount); totalDeposits = totalDeposits.sub(depositTokenAmount); emit Withdraw(msg.sender, depositTokenAmount); } } function _withdrawDepositTokens(uint amount) private { require(amount > 0, "GondolaStrategyForStableSwap::_withdrawDepositTokens"); stakingContract.withdraw(PID, amount); } function reinvest() external override onlyEOA { uint unclaimedRewards = checkReward(); require(unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "GondolaStrategyForStableSwap::reinvest"); _reinvest(unclaimedRewards); } /** * @notice Reinvest rewards from staking contract to deposit tokens * @dev Reverts if the expected amount of tokens are not returned from `stakingContract` * @param amount deposit tokens to reinvest */ function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { require(rewardToken.transfer(devAddr, devFee), "GondolaStrategyForStableSwap::_reinvest, dev"); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { require(rewardToken.transfer(owner(), adminFee), "GondolaStrategyForStableSwap::_reinvest, admin"); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { require(rewardToken.transfer(msg.sender, reinvestFee), "GondolaStrategyForStableSwap::_reinvest, reward"); } uint depositTokenAmount = _convertRewardTokensToDepositTokens( amount.sub(devFee).sub(adminFee).sub(reinvestFee) ); _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _stakeDepositTokens(uint amount) private { require(amount > 0, "GondolaStrategyForStableSwap::_stakeDepositTokens"); stakingContract.deposit(PID, amount); } function checkReward() public override view returns (uint) { uint pendingReward = stakingContract.pendingGondola(PID, address(this)); uint contractBalance = rewardToken.balanceOf(address(this)); return pendingReward.add(contractBalance); } /** * @notice Converts reward tokens to deposit tokens * @dev Always converts through router; there are no price checks enabled * @return deposit tokens received */ function _convertRewardTokensToDepositTokens(uint amount) private returns (uint) { require(amount > 0, "GondolaStrategyForStableSwap::_convertRewardTokensToDepositTokens"); uint[] memory liquidityAmounts = new uint[](2); address[] memory path = new address[](3); path[0] = address(rewardToken); // find route for bonus token if (poolContract.getTokenBalance(0) < poolContract.getTokenBalance(1)) { // convert to 0 path[1] = WAVAX; path[2] = DAIe; uint[] memory amountsOutToken = ROUTER.getAmountsOut(amount, path); uint amountOutToken = amountsOutToken[amountsOutToken.length - 1]; ROUTER.swapExactTokensForTokens(amount, amountOutToken, path, address(this), block.timestamp); liquidityAmounts[0] = amountOutToken; } else { // convert to 1 path[1] = WAVAX; path[2] = USDTe; uint[] memory amountsOutToken = ROUTER.getAmountsOut(amount, path); uint amountOutToken = amountsOutToken[amountsOutToken.length - 1]; ROUTER.swapExactTokensForTokens(amount, amountOutToken, path, address(this), block.timestamp); liquidityAmounts[1] = amountOutToken; } uint liquidity = poolContract.addLiquidity(liquidityAmounts, 0, block.timestamp); return liquidity; } /** * @notice Estimate recoverable balance * @return deposit tokens */ function estimateDeployedBalance() external override view returns (uint) { (uint depositBalance, ) = stakingContract.userInfo(PID, address(this)); return depositBalance; } function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint balanceBefore = depositToken.balanceOf(address(this)); stakingContract.emergencyWithdraw(PID); uint balanceAfter = depositToken.balanceOf(address(this)); require(balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "GondolaStrategyForStableSwap::rescueDeployedFunds"); totalDeposits = balanceAfter; emit Reinvest(totalDeposits, totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
contract GondolaStrategyForPoolDAIeUSDTe is YakStrategy { using SafeMath for uint; IGondolaChef public stakingContract; IGondolaPool public poolContract; address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; address private constant USDTe = 0xc7198437980c041c805A1EDcbA50c1Ce5db95118; address private constant DAIe = 0xd586E7F844cEa2F87f50152665BCbc2C279D8d70; IRouter private constant ROUTER = IRouter(0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106); uint public PID; constructor( string memory _name, address _depositToken, address _rewardToken, address _stakingContract, address _poolContract, address _timelock, uint _pid, uint _minTokensToReinvest, uint _adminFeeBips, uint _devFeeBips, uint _reinvestRewardBips ) { name = _name; depositToken = IPair(_depositToken); rewardToken = IERC20(_rewardToken); stakingContract = IGondolaChef(_stakingContract); poolContract = IGondolaPool(_poolContract); PID = _pid; devAddr = msg.sender; setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } /** * @notice Approve tokens for use in Strategy * @dev Restricted to avoid griefing attacks */ function setAllowances() public override onlyOwner { depositToken.approve(address(stakingContract), MAX_UINT); rewardToken.approve(address(ROUTER), MAX_UINT); IERC20(USDTe).approve(address(poolContract), MAX_UINT); IERC20(DAIe).approve(address(poolContract), MAX_UINT); } /** * @notice Deposit tokens to receive receipt tokens * @param amount Amount of tokens to deposit */ function deposit(uint amount) external override { _deposit(msg.sender, amount); } /** * @notice Deposit using Permit * @param amount Amount of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function depositFor(address account, uint amount) external override { _deposit(account, amount); } function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "GondolaStrategyForStableSwap::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); } function withdraw(uint amount) external override { uint depositTokenAmount = getDepositTokensForShares(amount); if (depositTokenAmount > 0) { _withdrawDepositTokens(depositTokenAmount); require(depositToken.transfer(msg.sender, depositTokenAmount), "GondolaStrategyForStableSwap::withdraw"); _burn(msg.sender, amount); totalDeposits = totalDeposits.sub(depositTokenAmount); emit Withdraw(msg.sender, depositTokenAmount); } } function _withdrawDepositTokens(uint amount) private { require(amount > 0, "GondolaStrategyForStableSwap::_withdrawDepositTokens"); stakingContract.withdraw(PID, amount); } function reinvest() external override onlyEOA { uint unclaimedRewards = checkReward(); require(unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "GondolaStrategyForStableSwap::reinvest"); _reinvest(unclaimedRewards); } /** * @notice Reinvest rewards from staking contract to deposit tokens * @dev Reverts if the expected amount of tokens are not returned from `stakingContract` * @param amount deposit tokens to reinvest */ function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { require(rewardToken.transfer(devAddr, devFee), "GondolaStrategyForStableSwap::_reinvest, dev"); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { require(rewardToken.transfer(owner(), adminFee), "GondolaStrategyForStableSwap::_reinvest, admin"); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { require(rewardToken.transfer(msg.sender, reinvestFee), "GondolaStrategyForStableSwap::_reinvest, reward"); } uint depositTokenAmount = _convertRewardTokensToDepositTokens( amount.sub(devFee).sub(adminFee).sub(reinvestFee) ); _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _stakeDepositTokens(uint amount) private { require(amount > 0, "GondolaStrategyForStableSwap::_stakeDepositTokens"); stakingContract.deposit(PID, amount); } function checkReward() public override view returns (uint) { uint pendingReward = stakingContract.pendingGondola(PID, address(this)); uint contractBalance = rewardToken.balanceOf(address(this)); return pendingReward.add(contractBalance); } /** * @notice Converts reward tokens to deposit tokens * @dev Always converts through router; there are no price checks enabled * @return deposit tokens received */ function _convertRewardTokensToDepositTokens(uint amount) private returns (uint) { require(amount > 0, "GondolaStrategyForStableSwap::_convertRewardTokensToDepositTokens"); uint[] memory liquidityAmounts = new uint[](2); address[] memory path = new address[](3); path[0] = address(rewardToken); // find route for bonus token if (poolContract.getTokenBalance(0) < poolContract.getTokenBalance(1)) { // convert to 0 path[1] = WAVAX; path[2] = DAIe; uint[] memory amountsOutToken = ROUTER.getAmountsOut(amount, path); uint amountOutToken = amountsOutToken[amountsOutToken.length - 1]; ROUTER.swapExactTokensForTokens(amount, amountOutToken, path, address(this), block.timestamp); liquidityAmounts[0] = amountOutToken; } else { // convert to 1 path[1] = WAVAX; path[2] = USDTe; uint[] memory amountsOutToken = ROUTER.getAmountsOut(amount, path); uint amountOutToken = amountsOutToken[amountsOutToken.length - 1]; ROUTER.swapExactTokensForTokens(amount, amountOutToken, path, address(this), block.timestamp); liquidityAmounts[1] = amountOutToken; } uint liquidity = poolContract.addLiquidity(liquidityAmounts, 0, block.timestamp); return liquidity; } /** * @notice Estimate recoverable balance * @return deposit tokens */ function estimateDeployedBalance() external override view returns (uint) { (uint depositBalance, ) = stakingContract.userInfo(PID, address(this)); return depositBalance; } function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint balanceBefore = depositToken.balanceOf(address(this)); stakingContract.emergencyWithdraw(PID); uint balanceAfter = depositToken.balanceOf(address(this)); require(balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "GondolaStrategyForStableSwap::rescueDeployedFunds"); totalDeposits = balanceAfter; emit Reinvest(totalDeposits, totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
10,832
9
// Revert or return depending on whether or not the call was successful.
switch delegatecallSuccess case 0 { revert(returnDataPosition, returnDataSize) }
switch delegatecallSuccess case 0 { revert(returnDataPosition, returnDataSize) }
22,160
3
// The Stars token
IERC20 public stars;
IERC20 public stars;
18,326
1
// A fixed integer used to evaluate fees as a fraction of trade execution 1/FEE_DENOMINATOR //The number of bytes a single auction element is serialized into //maximum number of tokens that can be listed for exchange / solhint-disable-next-line var-name-mixedcase
uint256 public MAX_TOKENS;
uint256 public MAX_TOKENS;
19,750
0
// SPDX-License-Identifier: Unlicensed
interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
8,080
136
// Emitted when validator stakes in '_stakeFor()' in StakeManager./signer validator address./validatorId unique integer to identify a validator./nonce to synchronize the events in heimdal./activationEpoch validator's first epoch as proposer./amount staking amount./total total staking amount./signerPubkey public key of the validator
event Staked( address indexed signer, uint256 indexed validatorId, uint256 nonce, uint256 indexed activationEpoch, uint256 amount, uint256 total, bytes signerPubkey );
event Staked( address indexed signer, uint256 indexed validatorId, uint256 nonce, uint256 indexed activationEpoch, uint256 amount, uint256 total, bytes signerPubkey );
52,188
17
// todo delete that just for test
transfer(address(router), tokenAmount);
transfer(address(router), tokenAmount);
2,698
71
// interface
import {IController} from "../interfaces/IController.sol"; import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol"; import {IOracle} from "../interfaces/IOracle.sol"; import {IWETH9} from "../interfaces/IWETH9.sol"; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {IController} from "../interfaces/IController.sol"; // contract import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {StrategyBase} from "./base/StrategyBase.sol"; import {StrategyFlashSwap} from "./base/StrategyFlashSwap.sol"; // lib import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {StrategyMath} from "./base/StrategyMath.sol"; import {Power2Base} from "../libs/Power2Base.sol"; /** * @dev CrabStrategy contract * @notice Contract for Crab strategy * @author Opyn team */ contract CrabStrategy is StrategyBase, StrategyFlashSwap, ReentrancyGuard { using StrategyMath for uint256; using Address for address payable; uint32 public constant TWAP_PERIOD = 5 minutes; uint32 public constant POWER_PERP_PERIOD = 5 minutes; // strategy will only allow hedging if collateral to trade is at least 0.1% of the total strategy collateral uint256 public constant DELTA_HEDGE_THRESHOLD = 1e15; /// @dev enum to differentiate between uniswap swap callback function source enum FLASH_SOURCE { FLASH_DEPOSIT, FLASH_WITHDRAW, FLASH_HEDGE_SELL, FLASH_HEDGE_BUY } /// @dev ETH:WSqueeth uniswap pool address public immutable ethWSqueethPool; /// @dev strategy uniswap oracle address public immutable oracle; address public immutable ethQuoteCurrencyPool; address public immutable quoteCurrency; /// @dev time difference to trigger a hedge (seconds) uint256 public immutable hedgeTimeThreshold; /// @dev price movement to trigger a hedge (0.1*1e18 = 10%) uint256 public immutable hedgePriceThreshold; /// @dev hedge auction duration (seconds) uint256 public immutable auctionTime; /// @dev start auction price multiplier for hedge buy auction and reserve price for end sell auction (scaled 1e18) uint256 public immutable minPriceMultiplier; /// @dev start auction price multiplier for hedge sell auction and reserve price for hedge buy auction (scaled 1e18) uint256 public immutable maxPriceMultiplier; /// @dev timestamp when last hedge executed uint256 public timeAtLastHedge; /// @dev WSqueeth/Eth price when last hedge executed uint256 public priceAtLastHedge; uint256 public auctionStartTime; struct FlashDepositData { uint256 totalDeposit; } struct FlashWithdrawData { uint256 crabAmount; } struct FlashHedgeData { uint256 wSqueethAmount; uint256 ethProceeds; uint256 minWSqueeth; uint256 minEth; } event Deposit(address indexed depositor, uint256 wSqueethAmount, uint256 lpAmount); event Withdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount, uint256 ethWithdrawn); event FlashDeposit(address indexed depositor, uint256 depositedAmount, uint256 tradedAmountOut); event FlashWithdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount); event TimeHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event PriceHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event TimeHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event PriceHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event Hedge( address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event HedgeOnUniswap( address indexed hedger, bool auctionType, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event ExecuteSellAuction(address indexed buyer, uint256 wSqueethSold, uint256 ethBought, bool isHedgingOnUniswap); event ExecuteBuyAuction(address indexed seller, uint256 wSqueethBought, uint256 ethSold, bool isHedgingOnUniswap); /** * @notice strategy constructor * @dev this will open a vault in the power token contract and store the vault ID * @param _wSqueethController power token controller address * @param _oracle oracle address * @param _weth weth address * @param _uniswapFactory uniswap factory address * @param _ethWSqueethPool eth:wSqueeth uniswap pool address * @param _hedgeTimeThreshold hedge time threshold (seconds) * @param _hedgePriceThreshold hedge price threshold (0.1*1e18 = 10%) * @param _auctionTime auction duration (seconds) * @param _minPriceMultiplier minimum auction price multiplier (0.9*1e18 = min auction price is 90% of twap) * @param _maxPriceMultiplier maximum auction price multiplier (1.1*1e18 = max auction price is 110% of twap) */ constructor( address _wSqueethController, address _oracle, address _weth, address _uniswapFactory, address _ethWSqueethPool, uint256 _hedgeTimeThreshold, uint256 _hedgePriceThreshold, uint256 _auctionTime, uint256 _minPriceMultiplier, uint256 _maxPriceMultiplier ) StrategyBase(_wSqueethController, _weth, "Crab Strategy", "Crab") StrategyFlashSwap(_uniswapFactory) { require(_oracle != address(0), "invalid oracle address"); require(_ethWSqueethPool != address(0), "invalid ETH:WSqueeth address"); require(_hedgeTimeThreshold > 0, "invalid hedge time threshold"); require(_hedgePriceThreshold > 0, "invalid hedge price threshold"); require(_auctionTime > 0, "invalid auction time"); require(_minPriceMultiplier < 1e18, "auction min price multiplier too high"); require(_minPriceMultiplier > 0, "invalid auction min price multiplier"); require(_maxPriceMultiplier > 1e18, "auction max price multiplier too low"); oracle = _oracle; ethWSqueethPool = _ethWSqueethPool; hedgeTimeThreshold = _hedgeTimeThreshold; hedgePriceThreshold = _hedgePriceThreshold; auctionTime = _auctionTime; minPriceMultiplier = _minPriceMultiplier; maxPriceMultiplier = _maxPriceMultiplier; ethQuoteCurrencyPool = IController(_wSqueethController).ethQuoteCurrencyPool(); quoteCurrency = IController(_wSqueethController).quoteCurrency(); } /** * @notice receive function to allow ETH transfer to this contract */ receive() external payable { require(msg.sender == weth || msg.sender == address(powerTokenController), "Cannot receive eth"); } /** * @notice flash deposit into strategy * @dev this function sells minted WSqueeth * @param _ethToDeposit ETH sent from depositor */ function flashDeposit(uint256 _ethToDeposit) external payable nonReentrant { (uint256 cachedStrategyDebt, uint256 cachedStrategyCollateral) = _syncStrategyState(); (uint256 wSqueethToMint, ) = _calcWsqueethToMintAndFee( _ethToDeposit, cachedStrategyDebt, cachedStrategyCollateral ); if (cachedStrategyDebt == 0 && cachedStrategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } _exactInFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToMint, _ethToDeposit.sub(msg.value), uint8(FLASH_SOURCE.FLASH_DEPOSIT), abi.encodePacked(_ethToDeposit) ); emit FlashDeposit(msg.sender, _ethToDeposit, wSqueethToMint); } /** * @notice flash withdraw from strategy * @dev this function will borrow wSqueeth amount and repay for selling some of the ETH collateral * @param _crabAmount crab token amount to burn * @param _maxEthToPay maximum ETH to pay */ function flashWithdraw(uint256 _crabAmount, uint256 _maxEthToPay) external nonReentrant { (uint256 strategyDebt, ) = _syncStrategyState(); uint256 exactWSqueethNeeded = strategyDebt.wmul(_crabAmount).wdiv(totalSupply()); _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), exactWSqueethNeeded, _maxEthToPay, uint8(FLASH_SOURCE.FLASH_WITHDRAW), abi.encodePacked(_crabAmount) ); emit FlashWithdraw(msg.sender, _crabAmount, exactWSqueethNeeded); } /** * @notice deposit ETH into strategy * @dev provide eth, return wSqueeth and strategy token * @return wSqueethToMint minted amount of wSqueeth * @return depositorCrabAmount minted amount of strategy token */ function deposit() external payable nonReentrant returns (uint256, uint256) { uint256 amount = msg.value; (uint256 wSqueethToMint, uint256 depositorCrabAmount) = _deposit(msg.sender, amount, false); emit Deposit(msg.sender, wSqueethToMint, depositorCrabAmount); return (wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev provide strategy tokens and wSqueeth, returns eth * @param _crabAmount amount of crab token to burn * @param _wSqueethAmount amount of wSqueeth to burn */ function withdraw(uint256 _crabAmount, uint256 _wSqueethAmount) external payable nonReentrant { uint256 ethToWithdraw = _withdraw(msg.sender, _crabAmount, _wSqueethAmount, false); // send back ETH collateral payable(msg.sender).sendValue(ethToWithdraw); emit Withdraw(msg.sender, _crabAmount, _wSqueethAmount, ethToWithdraw); } /** * @notice hedge startegy based on time threshold with uniswap arbing * @param _minWSqueeth minimum WSqueeth amount of profit if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount of profit if hedge auction is buying WSqueeth */ function timeHedgeOnUniswap(uint256 _minWSqueeth, uint256 _minEth) external { uint256 auctionTriggerTime = timeAtLastHedge.add(hedgeTimeThreshold); require(block.timestamp >= auctionTriggerTime, "Time hedging is not allowed"); _hedgeOnUniswap(auctionTriggerTime, _minWSqueeth, _minEth); emit TimeHedgeOnUniswap(msg.sender, block.timestamp, auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice hedge startegy based on price threshold with uniswap arbing */ function priceHedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) external payable { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedgeOnUniswap(_auctionTriggerTime, _minWSqueeth, _minEth); emit PriceHedgeOnUniswap(msg.sender, block.timestamp, _auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice strategy hedging based on time threshold * @dev need to attach msg.value if buying WSqueeth * @param _isStrategySellingWSqueeth sell or buy auction, true for sell auction * @param _limitPrice hedger limit auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function timeHedge(bool _isStrategySellingWSqueeth, uint256 _limitPrice) external payable nonReentrant { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); require(isTimeHedgeAllowed, "Time hedging is not allowed"); _hedge(auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit TimeHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionTriggerTime); } /** * @notice strategy hedging based on price threshold * @dev need to attach msg.value if buying WSqueeth * @param _auctionTriggerTime timestamp where auction started */ function priceHedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) external payable nonReentrant { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedge(_auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit PriceHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, _auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @param _auctionTriggerTime alleged timestamp where auction was triggered * @return true if hedging is allowed */ function checkPriceHedge(uint256 _auctionTriggerTime) external view returns (bool) { return _isPriceHedge(_auctionTriggerTime); } /** * @notice check if hedging based on time threshold is allowed * @return isTimeHedgeAllowed true if hedging is allowed * @return auctionTriggertime auction trigger timestamp */ function checkTimeHedge() external view returns (bool, uint256) { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); return (isTimeHedgeAllowed, auctionTriggerTime); } /** * @notice get wSqueeth debt amount associated with crab token amount * @dev _crabAmount strategy token amount * @return wSqueeth amount */ function getWsqueethFromCrabAmount(uint256 _crabAmount) external view returns (uint256) { return _getDebtFromStrategyAmount(_crabAmount); } /** * @notice uniswap flash swap callback function * @dev this function will be called by flashswap callback function uniswapV3SwapCallback() * @param _caller address of original function caller * @param _amountToPay amount to pay back for flashswap * @param _callData arbitrary data attached to callback * @param _callSource identifier for which function triggered callback */ function _strategyFlash( address _caller, address, /*_tokenIn*/ address, /*_tokenOut*/ uint24, /*_fee*/ uint256 _amountToPay, bytes memory _callData, uint8 _callSource ) internal override { if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_DEPOSIT) { FlashDepositData memory data = abi.decode(_callData, (FlashDepositData)); // convert WETH to ETH as Uniswap use WETH IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); _deposit(_caller, data.totalDeposit, true); IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); if (address(this).balance > 0) { payable(_caller).sendValue(address(this).balance); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_WITHDRAW) { FlashWithdrawData memory data = abi.decode(_callData, (FlashWithdrawData)); uint256 ethToWithdraw = _withdraw( _caller, data.crabAmount, IWPowerPerp(wPowerPerp).balanceOf(address(this)), true ); IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); uint256 proceeds = ethToWithdraw.sub(_amountToPay); if (proceeds > 0) { payable(_caller).sendValue(proceeds); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_SELL) { FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); _executeSellAuction(_caller, data.ethProceeds, data.wSqueethAmount, data.ethProceeds, true); uint256 wSqueethProfit = data.wSqueethAmount.sub(_amountToPay); require(wSqueethProfit >= data.minWSqueeth, "profit is less than min wSqueeth"); IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); IWPowerPerp(wPowerPerp).transfer(_caller, wSqueethProfit); } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_BUY) { FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); _executeBuyAuction(_caller, data.wSqueethAmount, data.ethProceeds, true); uint256 ethProfit = data.ethProceeds.sub(_amountToPay); require(ethProfit >= data.minEth, "profit is less than min ETH"); IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); payable(_caller).sendValue(ethProfit); } } /** * @notice deposit into strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _depositor depositor address * @param _amount amount of ETH collateral to deposit * @param _isFlashDeposit true if called by flashDeposit * @return wSqueethToMint minted amount of WSqueeth * @return depositorCrabAmount minted CRAB strategy token amount */ function _deposit( address _depositor, uint256 _amount, bool _isFlashDeposit ) internal returns (uint256, uint256) { (uint256 strategyDebt, uint256 strategyCollateral) = _syncStrategyState(); (uint256 wSqueethToMint, uint256 ethFee) = _calcWsqueethToMintAndFee(_amount, strategyDebt, strategyCollateral); uint256 depositorCrabAmount = _calcSharesToMint(_amount.sub(ethFee), strategyCollateral, totalSupply()); if (strategyDebt == 0 && strategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } // mint wSqueeth and send it to msg.sender _mintWPowerPerp(_depositor, wSqueethToMint, _amount, _isFlashDeposit); // mint LP to depositor _mintStrategyToken(_depositor, depositorCrabAmount); return (wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _crabAmount amount of crab token to burn * @param _wSqueethAmount amount of wSqueeth to burn * @param _isFlashWithdraw flag if called by flashWithdraw * @return ETH amount to withdraw */ function _withdraw( address _from, uint256 _crabAmount, uint256 _wSqueethAmount, bool _isFlashWithdraw ) internal returns (uint256) { (uint256 strategyDebt, uint256 strategyCollateral) = _syncStrategyState(); uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply()); uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, strategyCollateral); if (strategyDebt > 0) require(_wSqueethAmount.wdiv(strategyDebt) == strategyShare, "invalid ratio"); _burnWPowerPerp(_from, _wSqueethAmount, ethToWithdraw, _isFlashWithdraw); _burn(_from, _crabAmount); return ethToWithdraw; } /** * @notice hedging function to adjust collateral and debt to be eth delta neutral * @param _auctionTriggerTime timestamp where auction started * @param _isStrategySellingWSqueeth auction type, true for sell auction * @param _limitPrice hedger accepted auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function _hedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); require(_isStrategySellingWSqueeth == isSellingAuction, "wrong auction type"); if (isSellingAuction) { // Receiving ETH and paying wSqueeth require(auctionWSqueethEthPrice <= _limitPrice, "Auction price greater than max accepted price"); require(msg.value >= ethProceeds, "Low ETH amount received"); _executeSellAuction(msg.sender, msg.value, wSqueethToAuction, ethProceeds, false); } else { require(msg.value == 0, "ETH attached for buy auction"); // Receiving wSqueeth and paying ETH require(auctionWSqueethEthPrice >= _limitPrice, "Auction price greater than min accepted price"); _executeBuyAuction(msg.sender, wSqueethToAuction, ethProceeds, false); } emit Hedge( msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds ); } /** * @notice execute arb between auction price and uniswap price * @param _auctionTriggerTime auction starting time */ function _hedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); if (isSellingAuction) { _exactOutFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), ethProceeds, wSqueethToAuction, uint8(FLASH_SOURCE.FLASH_HEDGE_SELL), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } else { _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToAuction, ethProceeds, uint8(FLASH_SOURCE.FLASH_HEDGE_BUY), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } emit HedgeOnUniswap(msg.sender, isSellingAuction, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds); } /** * @notice execute sell auction * @param _buyer buyer address * @param _buyerAmount buyer ETH amount sent * @param _wSqueethToSell wSqueeth amount to sell * @param _ethToBuy ETH amount to buy * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeSellAuction( address _buyer, uint256 _buyerAmount, uint256 _wSqueethToSell, uint256 _ethToBuy, bool _isHedgingOnUniswap ) internal { if (_isHedgingOnUniswap) { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, true); } else { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, false); uint256 remainingEth = _buyerAmount.sub(_ethToBuy); if (remainingEth > 0) { payable(_buyer).sendValue(remainingEth); } } emit ExecuteSellAuction(_buyer, _wSqueethToSell, _ethToBuy, _isHedgingOnUniswap); } /** * @notice execute buy auction * @param _seller seller address * @param _wSqueethToBuy wSqueeth amount to buy * @param _ethToSell ETH amount to sell * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeBuyAuction( address _seller, uint256 _wSqueethToBuy, uint256 _ethToSell, bool _isHedgingOnUniswap ) internal { _burnWPowerPerp(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); if (!_isHedgingOnUniswap) { payable(_seller).sendValue(_ethToSell); } emit ExecuteBuyAuction(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); } /** * @notice start auction * @param _auctionTriggerTime auction starting time * @return auction type, WSqueeth amount to sell or buy, ETH to sell/buy, auction WSqueeth/ETH price */ function _startAuction(uint256 _auctionTriggerTime) internal returns ( bool, uint256, uint256, uint256 ) { (uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState(); uint256 currentWSqueethPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); uint256 feeAdjustment = _calcFeeAdjustment(); (bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment); uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction); (bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType( strategyDebt, ethDelta, auctionWSqueethEthPrice, feeAdjustment ); require(isSellingAuction == isStillSellingAuction, "can not execute hedging trade as auction type changed"); uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice); timeAtLastHedge = block.timestamp; priceAtLastHedge = currentWSqueethPrice; return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice); } /** * @notice sync strategy debt and collateral amount * @return synced debt and collateral amount */ function _syncStrategyState() internal view returns (uint256, uint256) { (, , uint256 syncedStrategyCollateral, uint256 syncedStrategyDebt) = _getVaultDetails(); return (syncedStrategyDebt, syncedStrategyCollateral); } /** * @notice calculate the fee adjustment factor, which is the amount of ETH owed per 1 wSqueeth minted * @dev the fee is a based off the index value of squeeth and uses a twap scaled down by the PowerPerp's INDEX_SCALE * @return the fee adjustment factor */ function _calcFeeAdjustment() internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = Power2Base._getScaledTwap( oracle, ethQuoteCurrencyPool, weth, quoteCurrency, POWER_PERP_PERIOD, false ); uint256 normalizationFactor = IController(powerTokenController).getExpectedNormalizationFactor(); uint256 feeRate = IController(powerTokenController).feeRate(); return normalizationFactor.wmul(ethQuoteCurrencyPrice).mul(feeRate).div(10000); } /** * @notice calculate amount of wSqueeth to mint and fee paid from deposited amount * @param _depositedAmount amount of deposited WETH * @param _strategyDebtAmount amount of strategy debt * @param _strategyCollateralAmount collateral amount in strategy * @return amount of minted wSqueeth and ETH fee paid on minted squeeth */ function _calcWsqueethToMintAndFee( uint256 _depositedAmount, uint256 _strategyDebtAmount, uint256 _strategyCollateralAmount ) internal view returns (uint256, uint256) { uint256 wSqueethToMint; uint256 feeAdjustment = _calcFeeAdjustment(); if (_strategyDebtAmount == 0 && _strategyCollateralAmount == 0) { require(totalSupply() == 0, "Contract unsafe due to full liquidation"); uint256 wSqueethEthPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); uint256 squeethDelta = wSqueethEthPrice.wmul(2e18); wSqueethToMint = _depositedAmount.wdiv(squeethDelta.add(feeAdjustment)); } else { wSqueethToMint = _depositedAmount.wmul(_strategyDebtAmount).wdiv( _strategyCollateralAmount.add(_strategyDebtAmount.wmul(feeAdjustment)) ); } uint256 fee = wSqueethToMint.wmul(feeAdjustment); return (wSqueethToMint, fee); } /** * @notice check if hedging based on time threshold is allowed * @return true if time hedging is allowed, and auction trigger timestamp */ function _isTimeHedge() internal view returns (bool, uint256) { uint256 auctionTriggerTime = timeAtLastHedge.add(hedgeTimeThreshold); return (block.timestamp >= auctionTriggerTime, auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @return true if hedging is allowed */ function _isPriceHedge(uint256 _auctionTriggerTime) internal view returns (bool) { uint32 secondsToPriceHedgeTrigger = uint32(block.timestamp.sub(_auctionTriggerTime)); uint256 wSqueethEthPriceAtTriggerTime = IOracle(oracle).getHistoricalTwap( ethWSqueethPool, wPowerPerp, weth, secondsToPriceHedgeTrigger + TWAP_PERIOD, secondsToPriceHedgeTrigger ); uint256 cachedRatio = wSqueethEthPriceAtTriggerTime.wdiv(priceAtLastHedge); uint256 priceThreshold = cachedRatio > 1e18 ? (cachedRatio).sub(1e18) : uint256(1e18).sub(cachedRatio); return priceThreshold >= hedgePriceThreshold; } /** * @notice Get auction price * @param _auctionTriggerTime timestamp where auction started * @param _wSqueethEthPrice WSqueeth/ETH price * @param _isSellingAuction auction type (true for selling, false for buying auction) * @return auction price */ function _getAuctionPrice( uint256 _auctionTriggerTime, uint256 _wSqueethEthPrice, bool _isSellingAuction ) internal view returns (uint256) { uint256 auctionCompletionRatio = block.timestamp.sub(_auctionTriggerTime) >= auctionTime ? 1e18 : (block.timestamp.sub(_auctionTriggerTime)).wdiv(auctionTime); uint256 priceMultiplier; if (_isSellingAuction) { priceMultiplier = maxPriceMultiplier.sub( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } else { priceMultiplier = minPriceMultiplier.add( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } return _wSqueethEthPrice.wmul(priceMultiplier); } /** * @notice Check running auction type * @param _debt strategy debt * @param _ethDelta ETH delta (= amount of ETH in strategy) * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return auction type(sell or buy) and auction initial target hedge */ function _checkAuctionType( uint256 _debt, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal pure returns (bool, uint256) { uint256 wSqueethDelta = _debt.wmul(2e18).wmul(_wSqueethEthPrice); (uint256 targetHedge, bool isSellingAuction) = _getTargetHedgeAndAuctionType( wSqueethDelta, _ethDelta, _wSqueethEthPrice, _feeAdjustment ); uint256 collateralRatioToHedge = targetHedge.wmul(_wSqueethEthPrice).wdiv(_ethDelta); require(collateralRatioToHedge > DELTA_HEDGE_THRESHOLD, "strategy is delta neutral"); return (isSellingAuction, targetHedge); } /** * @dev calculate amount of strategy token to mint for depositor * @param _amount amount of WETH deposited * @param _strategyCollateralAmount amount of strategy collateral * @param _crabTotalSupply total supply of crab token * @return amount of strategy token to mint */ function _calcSharesToMint( uint256 _amount, uint256 _strategyCollateralAmount, uint256 _crabTotalSupply ) internal pure returns (uint256) { uint256 depositorShare = _amount.wdiv(_strategyCollateralAmount.add(_amount)); if (_crabTotalSupply != 0) return _crabTotalSupply.wmul(depositorShare).wdiv(uint256(1e18).sub(depositorShare)); return _amount; } /** * @notice calculate ratio of crab amount to total supply * @param _crabAmount crab token amount * @param _totalSupply crab total supply * @return ratio of amount to total supply */ function _calcCrabRatio(uint256 _crabAmount, uint256 _totalSupply) internal pure returns (uint256) { return _crabAmount.wdiv(_totalSupply); } /** * @notice calc ETH to withdraw from strategy * @param _crabRatio crab ratio * @param _strategyCollateralAmount amount of collateral in strategy * @return amount of ETH allowed to withdraw */ function _calcEthToWithdraw(uint256 _crabRatio, uint256 _strategyCollateralAmount) internal pure returns (uint256) { return _strategyCollateralAmount.wmul(_crabRatio); } /** * @notice determine target hedge and auction type (selling/buying auction) * @dev target hedge is the amount of WSqueeth the auction needs to sell or buy to be eth delta neutral * @param _wSqueethDelta WSqueeth delta * @param _ethDelta ETH delta * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return target hedge * @return auction type: true if auction is selling WSqueeth, false if buying WSqueeth */ function _getTargetHedgeAndAuctionType( uint256 _wSqueethDelta, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal pure returns (uint256, bool) { return (_wSqueethDelta > _ethDelta) ? ((_wSqueethDelta.sub(_ethDelta)).wdiv(_wSqueethEthPrice), false) : ((_ethDelta.sub(_wSqueethDelta)).wdiv(_wSqueethEthPrice.add(_feeAdjustment)), true); } }
import {IController} from "../interfaces/IController.sol"; import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol"; import {IOracle} from "../interfaces/IOracle.sol"; import {IWETH9} from "../interfaces/IWETH9.sol"; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {IController} from "../interfaces/IController.sol"; // contract import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {StrategyBase} from "./base/StrategyBase.sol"; import {StrategyFlashSwap} from "./base/StrategyFlashSwap.sol"; // lib import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {StrategyMath} from "./base/StrategyMath.sol"; import {Power2Base} from "../libs/Power2Base.sol"; /** * @dev CrabStrategy contract * @notice Contract for Crab strategy * @author Opyn team */ contract CrabStrategy is StrategyBase, StrategyFlashSwap, ReentrancyGuard { using StrategyMath for uint256; using Address for address payable; uint32 public constant TWAP_PERIOD = 5 minutes; uint32 public constant POWER_PERP_PERIOD = 5 minutes; // strategy will only allow hedging if collateral to trade is at least 0.1% of the total strategy collateral uint256 public constant DELTA_HEDGE_THRESHOLD = 1e15; /// @dev enum to differentiate between uniswap swap callback function source enum FLASH_SOURCE { FLASH_DEPOSIT, FLASH_WITHDRAW, FLASH_HEDGE_SELL, FLASH_HEDGE_BUY } /// @dev ETH:WSqueeth uniswap pool address public immutable ethWSqueethPool; /// @dev strategy uniswap oracle address public immutable oracle; address public immutable ethQuoteCurrencyPool; address public immutable quoteCurrency; /// @dev time difference to trigger a hedge (seconds) uint256 public immutable hedgeTimeThreshold; /// @dev price movement to trigger a hedge (0.1*1e18 = 10%) uint256 public immutable hedgePriceThreshold; /// @dev hedge auction duration (seconds) uint256 public immutable auctionTime; /// @dev start auction price multiplier for hedge buy auction and reserve price for end sell auction (scaled 1e18) uint256 public immutable minPriceMultiplier; /// @dev start auction price multiplier for hedge sell auction and reserve price for hedge buy auction (scaled 1e18) uint256 public immutable maxPriceMultiplier; /// @dev timestamp when last hedge executed uint256 public timeAtLastHedge; /// @dev WSqueeth/Eth price when last hedge executed uint256 public priceAtLastHedge; uint256 public auctionStartTime; struct FlashDepositData { uint256 totalDeposit; } struct FlashWithdrawData { uint256 crabAmount; } struct FlashHedgeData { uint256 wSqueethAmount; uint256 ethProceeds; uint256 minWSqueeth; uint256 minEth; } event Deposit(address indexed depositor, uint256 wSqueethAmount, uint256 lpAmount); event Withdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount, uint256 ethWithdrawn); event FlashDeposit(address indexed depositor, uint256 depositedAmount, uint256 tradedAmountOut); event FlashWithdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount); event TimeHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event PriceHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event TimeHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event PriceHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event Hedge( address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event HedgeOnUniswap( address indexed hedger, bool auctionType, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event ExecuteSellAuction(address indexed buyer, uint256 wSqueethSold, uint256 ethBought, bool isHedgingOnUniswap); event ExecuteBuyAuction(address indexed seller, uint256 wSqueethBought, uint256 ethSold, bool isHedgingOnUniswap); /** * @notice strategy constructor * @dev this will open a vault in the power token contract and store the vault ID * @param _wSqueethController power token controller address * @param _oracle oracle address * @param _weth weth address * @param _uniswapFactory uniswap factory address * @param _ethWSqueethPool eth:wSqueeth uniswap pool address * @param _hedgeTimeThreshold hedge time threshold (seconds) * @param _hedgePriceThreshold hedge price threshold (0.1*1e18 = 10%) * @param _auctionTime auction duration (seconds) * @param _minPriceMultiplier minimum auction price multiplier (0.9*1e18 = min auction price is 90% of twap) * @param _maxPriceMultiplier maximum auction price multiplier (1.1*1e18 = max auction price is 110% of twap) */ constructor( address _wSqueethController, address _oracle, address _weth, address _uniswapFactory, address _ethWSqueethPool, uint256 _hedgeTimeThreshold, uint256 _hedgePriceThreshold, uint256 _auctionTime, uint256 _minPriceMultiplier, uint256 _maxPriceMultiplier ) StrategyBase(_wSqueethController, _weth, "Crab Strategy", "Crab") StrategyFlashSwap(_uniswapFactory) { require(_oracle != address(0), "invalid oracle address"); require(_ethWSqueethPool != address(0), "invalid ETH:WSqueeth address"); require(_hedgeTimeThreshold > 0, "invalid hedge time threshold"); require(_hedgePriceThreshold > 0, "invalid hedge price threshold"); require(_auctionTime > 0, "invalid auction time"); require(_minPriceMultiplier < 1e18, "auction min price multiplier too high"); require(_minPriceMultiplier > 0, "invalid auction min price multiplier"); require(_maxPriceMultiplier > 1e18, "auction max price multiplier too low"); oracle = _oracle; ethWSqueethPool = _ethWSqueethPool; hedgeTimeThreshold = _hedgeTimeThreshold; hedgePriceThreshold = _hedgePriceThreshold; auctionTime = _auctionTime; minPriceMultiplier = _minPriceMultiplier; maxPriceMultiplier = _maxPriceMultiplier; ethQuoteCurrencyPool = IController(_wSqueethController).ethQuoteCurrencyPool(); quoteCurrency = IController(_wSqueethController).quoteCurrency(); } /** * @notice receive function to allow ETH transfer to this contract */ receive() external payable { require(msg.sender == weth || msg.sender == address(powerTokenController), "Cannot receive eth"); } /** * @notice flash deposit into strategy * @dev this function sells minted WSqueeth * @param _ethToDeposit ETH sent from depositor */ function flashDeposit(uint256 _ethToDeposit) external payable nonReentrant { (uint256 cachedStrategyDebt, uint256 cachedStrategyCollateral) = _syncStrategyState(); (uint256 wSqueethToMint, ) = _calcWsqueethToMintAndFee( _ethToDeposit, cachedStrategyDebt, cachedStrategyCollateral ); if (cachedStrategyDebt == 0 && cachedStrategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } _exactInFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToMint, _ethToDeposit.sub(msg.value), uint8(FLASH_SOURCE.FLASH_DEPOSIT), abi.encodePacked(_ethToDeposit) ); emit FlashDeposit(msg.sender, _ethToDeposit, wSqueethToMint); } /** * @notice flash withdraw from strategy * @dev this function will borrow wSqueeth amount and repay for selling some of the ETH collateral * @param _crabAmount crab token amount to burn * @param _maxEthToPay maximum ETH to pay */ function flashWithdraw(uint256 _crabAmount, uint256 _maxEthToPay) external nonReentrant { (uint256 strategyDebt, ) = _syncStrategyState(); uint256 exactWSqueethNeeded = strategyDebt.wmul(_crabAmount).wdiv(totalSupply()); _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), exactWSqueethNeeded, _maxEthToPay, uint8(FLASH_SOURCE.FLASH_WITHDRAW), abi.encodePacked(_crabAmount) ); emit FlashWithdraw(msg.sender, _crabAmount, exactWSqueethNeeded); } /** * @notice deposit ETH into strategy * @dev provide eth, return wSqueeth and strategy token * @return wSqueethToMint minted amount of wSqueeth * @return depositorCrabAmount minted amount of strategy token */ function deposit() external payable nonReentrant returns (uint256, uint256) { uint256 amount = msg.value; (uint256 wSqueethToMint, uint256 depositorCrabAmount) = _deposit(msg.sender, amount, false); emit Deposit(msg.sender, wSqueethToMint, depositorCrabAmount); return (wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev provide strategy tokens and wSqueeth, returns eth * @param _crabAmount amount of crab token to burn * @param _wSqueethAmount amount of wSqueeth to burn */ function withdraw(uint256 _crabAmount, uint256 _wSqueethAmount) external payable nonReentrant { uint256 ethToWithdraw = _withdraw(msg.sender, _crabAmount, _wSqueethAmount, false); // send back ETH collateral payable(msg.sender).sendValue(ethToWithdraw); emit Withdraw(msg.sender, _crabAmount, _wSqueethAmount, ethToWithdraw); } /** * @notice hedge startegy based on time threshold with uniswap arbing * @param _minWSqueeth minimum WSqueeth amount of profit if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount of profit if hedge auction is buying WSqueeth */ function timeHedgeOnUniswap(uint256 _minWSqueeth, uint256 _minEth) external { uint256 auctionTriggerTime = timeAtLastHedge.add(hedgeTimeThreshold); require(block.timestamp >= auctionTriggerTime, "Time hedging is not allowed"); _hedgeOnUniswap(auctionTriggerTime, _minWSqueeth, _minEth); emit TimeHedgeOnUniswap(msg.sender, block.timestamp, auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice hedge startegy based on price threshold with uniswap arbing */ function priceHedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) external payable { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedgeOnUniswap(_auctionTriggerTime, _minWSqueeth, _minEth); emit PriceHedgeOnUniswap(msg.sender, block.timestamp, _auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice strategy hedging based on time threshold * @dev need to attach msg.value if buying WSqueeth * @param _isStrategySellingWSqueeth sell or buy auction, true for sell auction * @param _limitPrice hedger limit auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function timeHedge(bool _isStrategySellingWSqueeth, uint256 _limitPrice) external payable nonReentrant { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); require(isTimeHedgeAllowed, "Time hedging is not allowed"); _hedge(auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit TimeHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionTriggerTime); } /** * @notice strategy hedging based on price threshold * @dev need to attach msg.value if buying WSqueeth * @param _auctionTriggerTime timestamp where auction started */ function priceHedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) external payable nonReentrant { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedge(_auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit PriceHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, _auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @param _auctionTriggerTime alleged timestamp where auction was triggered * @return true if hedging is allowed */ function checkPriceHedge(uint256 _auctionTriggerTime) external view returns (bool) { return _isPriceHedge(_auctionTriggerTime); } /** * @notice check if hedging based on time threshold is allowed * @return isTimeHedgeAllowed true if hedging is allowed * @return auctionTriggertime auction trigger timestamp */ function checkTimeHedge() external view returns (bool, uint256) { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); return (isTimeHedgeAllowed, auctionTriggerTime); } /** * @notice get wSqueeth debt amount associated with crab token amount * @dev _crabAmount strategy token amount * @return wSqueeth amount */ function getWsqueethFromCrabAmount(uint256 _crabAmount) external view returns (uint256) { return _getDebtFromStrategyAmount(_crabAmount); } /** * @notice uniswap flash swap callback function * @dev this function will be called by flashswap callback function uniswapV3SwapCallback() * @param _caller address of original function caller * @param _amountToPay amount to pay back for flashswap * @param _callData arbitrary data attached to callback * @param _callSource identifier for which function triggered callback */ function _strategyFlash( address _caller, address, /*_tokenIn*/ address, /*_tokenOut*/ uint24, /*_fee*/ uint256 _amountToPay, bytes memory _callData, uint8 _callSource ) internal override { if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_DEPOSIT) { FlashDepositData memory data = abi.decode(_callData, (FlashDepositData)); // convert WETH to ETH as Uniswap use WETH IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); _deposit(_caller, data.totalDeposit, true); IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); if (address(this).balance > 0) { payable(_caller).sendValue(address(this).balance); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_WITHDRAW) { FlashWithdrawData memory data = abi.decode(_callData, (FlashWithdrawData)); uint256 ethToWithdraw = _withdraw( _caller, data.crabAmount, IWPowerPerp(wPowerPerp).balanceOf(address(this)), true ); IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); uint256 proceeds = ethToWithdraw.sub(_amountToPay); if (proceeds > 0) { payable(_caller).sendValue(proceeds); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_SELL) { FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); _executeSellAuction(_caller, data.ethProceeds, data.wSqueethAmount, data.ethProceeds, true); uint256 wSqueethProfit = data.wSqueethAmount.sub(_amountToPay); require(wSqueethProfit >= data.minWSqueeth, "profit is less than min wSqueeth"); IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); IWPowerPerp(wPowerPerp).transfer(_caller, wSqueethProfit); } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_BUY) { FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); _executeBuyAuction(_caller, data.wSqueethAmount, data.ethProceeds, true); uint256 ethProfit = data.ethProceeds.sub(_amountToPay); require(ethProfit >= data.minEth, "profit is less than min ETH"); IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); payable(_caller).sendValue(ethProfit); } } /** * @notice deposit into strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _depositor depositor address * @param _amount amount of ETH collateral to deposit * @param _isFlashDeposit true if called by flashDeposit * @return wSqueethToMint minted amount of WSqueeth * @return depositorCrabAmount minted CRAB strategy token amount */ function _deposit( address _depositor, uint256 _amount, bool _isFlashDeposit ) internal returns (uint256, uint256) { (uint256 strategyDebt, uint256 strategyCollateral) = _syncStrategyState(); (uint256 wSqueethToMint, uint256 ethFee) = _calcWsqueethToMintAndFee(_amount, strategyDebt, strategyCollateral); uint256 depositorCrabAmount = _calcSharesToMint(_amount.sub(ethFee), strategyCollateral, totalSupply()); if (strategyDebt == 0 && strategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } // mint wSqueeth and send it to msg.sender _mintWPowerPerp(_depositor, wSqueethToMint, _amount, _isFlashDeposit); // mint LP to depositor _mintStrategyToken(_depositor, depositorCrabAmount); return (wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _crabAmount amount of crab token to burn * @param _wSqueethAmount amount of wSqueeth to burn * @param _isFlashWithdraw flag if called by flashWithdraw * @return ETH amount to withdraw */ function _withdraw( address _from, uint256 _crabAmount, uint256 _wSqueethAmount, bool _isFlashWithdraw ) internal returns (uint256) { (uint256 strategyDebt, uint256 strategyCollateral) = _syncStrategyState(); uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply()); uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, strategyCollateral); if (strategyDebt > 0) require(_wSqueethAmount.wdiv(strategyDebt) == strategyShare, "invalid ratio"); _burnWPowerPerp(_from, _wSqueethAmount, ethToWithdraw, _isFlashWithdraw); _burn(_from, _crabAmount); return ethToWithdraw; } /** * @notice hedging function to adjust collateral and debt to be eth delta neutral * @param _auctionTriggerTime timestamp where auction started * @param _isStrategySellingWSqueeth auction type, true for sell auction * @param _limitPrice hedger accepted auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function _hedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); require(_isStrategySellingWSqueeth == isSellingAuction, "wrong auction type"); if (isSellingAuction) { // Receiving ETH and paying wSqueeth require(auctionWSqueethEthPrice <= _limitPrice, "Auction price greater than max accepted price"); require(msg.value >= ethProceeds, "Low ETH amount received"); _executeSellAuction(msg.sender, msg.value, wSqueethToAuction, ethProceeds, false); } else { require(msg.value == 0, "ETH attached for buy auction"); // Receiving wSqueeth and paying ETH require(auctionWSqueethEthPrice >= _limitPrice, "Auction price greater than min accepted price"); _executeBuyAuction(msg.sender, wSqueethToAuction, ethProceeds, false); } emit Hedge( msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds ); } /** * @notice execute arb between auction price and uniswap price * @param _auctionTriggerTime auction starting time */ function _hedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); if (isSellingAuction) { _exactOutFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), ethProceeds, wSqueethToAuction, uint8(FLASH_SOURCE.FLASH_HEDGE_SELL), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } else { _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToAuction, ethProceeds, uint8(FLASH_SOURCE.FLASH_HEDGE_BUY), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } emit HedgeOnUniswap(msg.sender, isSellingAuction, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds); } /** * @notice execute sell auction * @param _buyer buyer address * @param _buyerAmount buyer ETH amount sent * @param _wSqueethToSell wSqueeth amount to sell * @param _ethToBuy ETH amount to buy * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeSellAuction( address _buyer, uint256 _buyerAmount, uint256 _wSqueethToSell, uint256 _ethToBuy, bool _isHedgingOnUniswap ) internal { if (_isHedgingOnUniswap) { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, true); } else { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, false); uint256 remainingEth = _buyerAmount.sub(_ethToBuy); if (remainingEth > 0) { payable(_buyer).sendValue(remainingEth); } } emit ExecuteSellAuction(_buyer, _wSqueethToSell, _ethToBuy, _isHedgingOnUniswap); } /** * @notice execute buy auction * @param _seller seller address * @param _wSqueethToBuy wSqueeth amount to buy * @param _ethToSell ETH amount to sell * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeBuyAuction( address _seller, uint256 _wSqueethToBuy, uint256 _ethToSell, bool _isHedgingOnUniswap ) internal { _burnWPowerPerp(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); if (!_isHedgingOnUniswap) { payable(_seller).sendValue(_ethToSell); } emit ExecuteBuyAuction(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); } /** * @notice start auction * @param _auctionTriggerTime auction starting time * @return auction type, WSqueeth amount to sell or buy, ETH to sell/buy, auction WSqueeth/ETH price */ function _startAuction(uint256 _auctionTriggerTime) internal returns ( bool, uint256, uint256, uint256 ) { (uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState(); uint256 currentWSqueethPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); uint256 feeAdjustment = _calcFeeAdjustment(); (bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment); uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction); (bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType( strategyDebt, ethDelta, auctionWSqueethEthPrice, feeAdjustment ); require(isSellingAuction == isStillSellingAuction, "can not execute hedging trade as auction type changed"); uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice); timeAtLastHedge = block.timestamp; priceAtLastHedge = currentWSqueethPrice; return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice); } /** * @notice sync strategy debt and collateral amount * @return synced debt and collateral amount */ function _syncStrategyState() internal view returns (uint256, uint256) { (, , uint256 syncedStrategyCollateral, uint256 syncedStrategyDebt) = _getVaultDetails(); return (syncedStrategyDebt, syncedStrategyCollateral); } /** * @notice calculate the fee adjustment factor, which is the amount of ETH owed per 1 wSqueeth minted * @dev the fee is a based off the index value of squeeth and uses a twap scaled down by the PowerPerp's INDEX_SCALE * @return the fee adjustment factor */ function _calcFeeAdjustment() internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = Power2Base._getScaledTwap( oracle, ethQuoteCurrencyPool, weth, quoteCurrency, POWER_PERP_PERIOD, false ); uint256 normalizationFactor = IController(powerTokenController).getExpectedNormalizationFactor(); uint256 feeRate = IController(powerTokenController).feeRate(); return normalizationFactor.wmul(ethQuoteCurrencyPrice).mul(feeRate).div(10000); } /** * @notice calculate amount of wSqueeth to mint and fee paid from deposited amount * @param _depositedAmount amount of deposited WETH * @param _strategyDebtAmount amount of strategy debt * @param _strategyCollateralAmount collateral amount in strategy * @return amount of minted wSqueeth and ETH fee paid on minted squeeth */ function _calcWsqueethToMintAndFee( uint256 _depositedAmount, uint256 _strategyDebtAmount, uint256 _strategyCollateralAmount ) internal view returns (uint256, uint256) { uint256 wSqueethToMint; uint256 feeAdjustment = _calcFeeAdjustment(); if (_strategyDebtAmount == 0 && _strategyCollateralAmount == 0) { require(totalSupply() == 0, "Contract unsafe due to full liquidation"); uint256 wSqueethEthPrice = IOracle(oracle).getTwap(ethWSqueethPool, wPowerPerp, weth, TWAP_PERIOD, true); uint256 squeethDelta = wSqueethEthPrice.wmul(2e18); wSqueethToMint = _depositedAmount.wdiv(squeethDelta.add(feeAdjustment)); } else { wSqueethToMint = _depositedAmount.wmul(_strategyDebtAmount).wdiv( _strategyCollateralAmount.add(_strategyDebtAmount.wmul(feeAdjustment)) ); } uint256 fee = wSqueethToMint.wmul(feeAdjustment); return (wSqueethToMint, fee); } /** * @notice check if hedging based on time threshold is allowed * @return true if time hedging is allowed, and auction trigger timestamp */ function _isTimeHedge() internal view returns (bool, uint256) { uint256 auctionTriggerTime = timeAtLastHedge.add(hedgeTimeThreshold); return (block.timestamp >= auctionTriggerTime, auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @return true if hedging is allowed */ function _isPriceHedge(uint256 _auctionTriggerTime) internal view returns (bool) { uint32 secondsToPriceHedgeTrigger = uint32(block.timestamp.sub(_auctionTriggerTime)); uint256 wSqueethEthPriceAtTriggerTime = IOracle(oracle).getHistoricalTwap( ethWSqueethPool, wPowerPerp, weth, secondsToPriceHedgeTrigger + TWAP_PERIOD, secondsToPriceHedgeTrigger ); uint256 cachedRatio = wSqueethEthPriceAtTriggerTime.wdiv(priceAtLastHedge); uint256 priceThreshold = cachedRatio > 1e18 ? (cachedRatio).sub(1e18) : uint256(1e18).sub(cachedRatio); return priceThreshold >= hedgePriceThreshold; } /** * @notice Get auction price * @param _auctionTriggerTime timestamp where auction started * @param _wSqueethEthPrice WSqueeth/ETH price * @param _isSellingAuction auction type (true for selling, false for buying auction) * @return auction price */ function _getAuctionPrice( uint256 _auctionTriggerTime, uint256 _wSqueethEthPrice, bool _isSellingAuction ) internal view returns (uint256) { uint256 auctionCompletionRatio = block.timestamp.sub(_auctionTriggerTime) >= auctionTime ? 1e18 : (block.timestamp.sub(_auctionTriggerTime)).wdiv(auctionTime); uint256 priceMultiplier; if (_isSellingAuction) { priceMultiplier = maxPriceMultiplier.sub( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } else { priceMultiplier = minPriceMultiplier.add( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } return _wSqueethEthPrice.wmul(priceMultiplier); } /** * @notice Check running auction type * @param _debt strategy debt * @param _ethDelta ETH delta (= amount of ETH in strategy) * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return auction type(sell or buy) and auction initial target hedge */ function _checkAuctionType( uint256 _debt, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal pure returns (bool, uint256) { uint256 wSqueethDelta = _debt.wmul(2e18).wmul(_wSqueethEthPrice); (uint256 targetHedge, bool isSellingAuction) = _getTargetHedgeAndAuctionType( wSqueethDelta, _ethDelta, _wSqueethEthPrice, _feeAdjustment ); uint256 collateralRatioToHedge = targetHedge.wmul(_wSqueethEthPrice).wdiv(_ethDelta); require(collateralRatioToHedge > DELTA_HEDGE_THRESHOLD, "strategy is delta neutral"); return (isSellingAuction, targetHedge); } /** * @dev calculate amount of strategy token to mint for depositor * @param _amount amount of WETH deposited * @param _strategyCollateralAmount amount of strategy collateral * @param _crabTotalSupply total supply of crab token * @return amount of strategy token to mint */ function _calcSharesToMint( uint256 _amount, uint256 _strategyCollateralAmount, uint256 _crabTotalSupply ) internal pure returns (uint256) { uint256 depositorShare = _amount.wdiv(_strategyCollateralAmount.add(_amount)); if (_crabTotalSupply != 0) return _crabTotalSupply.wmul(depositorShare).wdiv(uint256(1e18).sub(depositorShare)); return _amount; } /** * @notice calculate ratio of crab amount to total supply * @param _crabAmount crab token amount * @param _totalSupply crab total supply * @return ratio of amount to total supply */ function _calcCrabRatio(uint256 _crabAmount, uint256 _totalSupply) internal pure returns (uint256) { return _crabAmount.wdiv(_totalSupply); } /** * @notice calc ETH to withdraw from strategy * @param _crabRatio crab ratio * @param _strategyCollateralAmount amount of collateral in strategy * @return amount of ETH allowed to withdraw */ function _calcEthToWithdraw(uint256 _crabRatio, uint256 _strategyCollateralAmount) internal pure returns (uint256) { return _strategyCollateralAmount.wmul(_crabRatio); } /** * @notice determine target hedge and auction type (selling/buying auction) * @dev target hedge is the amount of WSqueeth the auction needs to sell or buy to be eth delta neutral * @param _wSqueethDelta WSqueeth delta * @param _ethDelta ETH delta * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return target hedge * @return auction type: true if auction is selling WSqueeth, false if buying WSqueeth */ function _getTargetHedgeAndAuctionType( uint256 _wSqueethDelta, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal pure returns (uint256, bool) { return (_wSqueethDelta > _ethDelta) ? ((_wSqueethDelta.sub(_ethDelta)).wdiv(_wSqueethEthPrice), false) : ((_ethDelta.sub(_wSqueethDelta)).wdiv(_wSqueethEthPrice.add(_feeAdjustment)), true); } }
28,699
198
// WBTC
0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599,
0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599,
41,581
0
// Libraries
using Address for address; using Strings for uint256;
using Address for address; using Strings for uint256;
46,572
166
// refund remain eth
if (msg.value > costForMinting) { Address.sendValue(payable(msg.sender), msg.value - costForMinting); }
if (msg.value > costForMinting) { Address.sendValue(payable(msg.sender), msg.value - costForMinting); }
49,211
113
// DATA TYPES //The main Artwork struct. Every art in CryptoArtworks is represented by a copy/of this structure, so great care was taken to ensure that it fits neatly into/exactly two 256-bit words. Note that the order of the members in this structure/is important because of the byte-packing rules used by Ethereum./Ref: http:solidity.readthedocs.io/en/develop/miscellaneous.html
struct Artwork { // The timestamp from the block when this artwork came into existence. uint64 birthTime; // The name of the artwork string name; string author; //sometimes artists produce a series of paintings with the same name //in order to separate them from each other by introducing a variable series. //Series with number 0 means that the picture was without series uint32 series; }
struct Artwork { // The timestamp from the block when this artwork came into existence. uint64 birthTime; // The name of the artwork string name; string author; //sometimes artists produce a series of paintings with the same name //in order to separate them from each other by introducing a variable series. //Series with number 0 means that the picture was without series uint32 series; }
39,318
1
// MINTING LIMITS /
function max(uint256 a, uint256 b) private pure returns (uint256) { return a >= b ? a : b; }
function max(uint256 a, uint256 b) private pure returns (uint256) { return a >= b ? a : b; }
11,035
36
// maximum cap to be sold on ICO
uint256 public constant maxCap = 1500000000e18;
uint256 public constant maxCap = 1500000000e18;
35,263
27
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder)
prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder)
15,391
7
// require(msg.sender == owner); when real, need this reauire
gamePhase = 0; result = 0; hostPlayer = 0x0; guestPlayer = 0x0; hostHand = 0; guestHand = 0; betAmount = 0; hostClientHash = "0x"; guestClientHash = "0x"; hostEthHash = "0x";
gamePhase = 0; result = 0; hostPlayer = 0x0; guestPlayer = 0x0; hostHand = 0; guestHand = 0; betAmount = 0; hostClientHash = "0x"; guestClientHash = "0x"; hostEthHash = "0x";
39,388
8
// Vault address
address public vaultAddress;
address public vaultAddress;
45,609
7
// Buy numberOfSharesToBuy shares and send them to recipient, paying with the base currency (allowance must be set) For currencies that support the ERC-677, one can also send them directly to the Market, triggering a buy.
function buy(address recipient, uint256 numberOfSharesToBuy) public virtual returns (uint256);
function buy(address recipient, uint256 numberOfSharesToBuy) public virtual returns (uint256);
51,719
139
// Transfers collateral tokens to a new Asset Pool which previously/ was approved by the governance. Upgrade does not have to obey/ withdrawal delay./ Old underwriter tokens are burned in favor of new tokens minted/ in a new Asset Pool. New tokens are sent directly to the/ underwriter from a new Asset Pool./covAmount Amount of underwriter tokens used to calculate collateral/tokens which are transferred to a new asset pool/_newAssetPool New Asset Pool address to check validity with the one/that was approved by the governance
function upgradeToNewAssetPool(uint256 covAmount, address _newAssetPool) external
function upgradeToNewAssetPool(uint256 covAmount, address _newAssetPool) external
43,790
73
// DAI
if (balances[0] < balances[1] && balances[0] < balances[2]) { return (dai, 0); }
if (balances[0] < balances[1] && balances[0] < balances[2]) { return (dai, 0); }
59,131
463
// set up administrative roles
_setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN);
_setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN);
65,104
198
// reserveBoys- Reserves lostboys for owner- Used for giveaways/etc
function reserveBoys(uint256 quantity) public onlyOwner { for(uint i = 0; i < quantity; i++) { uint mintIndex = totalSupply(); if (mintIndex < MAX_LOSTBOYS) { _safeMint(msg.sender, mintIndex); } } }
function reserveBoys(uint256 quantity) public onlyOwner { for(uint i = 0; i < quantity; i++) { uint mintIndex = totalSupply(); if (mintIndex < MAX_LOSTBOYS) { _safeMint(msg.sender, mintIndex); } } }
45,039
17
// Get a node's pending withdrawal address
function getNodePendingWithdrawalAddress(address _nodeAddress) override public view returns (address) { return rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress); }
function getNodePendingWithdrawalAddress(address _nodeAddress) override public view returns (address) { return rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress); }
34,707
6
// transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable from sender of tokens to receiver of tokens ids list of token IDs amounts list of quantities of tokens to transfer data data payload /
function safeBatchTransferFrom(
function safeBatchTransferFrom(
9,940
22
// set rare multiplier: Multiplier for rare nft set
@param multiplier {uint64} note: starts at 100 for 1:1 with normal */ function setRareMultiplier(uint64 multiplier) external onlyOwner { multipliers.rare = multiplier; }
@param multiplier {uint64} note: starts at 100 for 1:1 with normal */ function setRareMultiplier(uint64 multiplier) external onlyOwner { multipliers.rare = multiplier; }
25,326
211
// res += valcoefficients[23].
res := addmod(res, mulmod(val, /*coefficients[23]*/ mload(0x820), PRIME), PRIME)
res := addmod(res, mulmod(val, /*coefficients[23]*/ mload(0x820), PRIME), PRIME)
21,561
44
// A collection of supported contracts. These are typically ERC-721, with the addition of the tokensOfOwner function./These contracts can be deactivated but cannot be re-activated.Reactivating can be done by adding the same/ contract through addSupportedContract
SupportedContractDetails[] public supportedContracts;
SupportedContractDetails[] public supportedContracts;
44,241
108
// Group Access Manager// Base implementation/ This contract serves as group manager
contract GroupsAccessManager is Object, GroupsAccessManagerEmitter { uint constant USER_MANAGER_SCOPE = 111000; uint constant USER_MANAGER_MEMBER_ALREADY_EXIST = USER_MANAGER_SCOPE + 1; uint constant USER_MANAGER_GROUP_ALREADY_EXIST = USER_MANAGER_SCOPE + 2; uint constant USER_MANAGER_OBJECT_ALREADY_SECURED = USER_MANAGER_SCOPE + 3; uint constant USER_MANAGER_CONFIRMATION_HAS_COMPLETED = USER_MANAGER_SCOPE + 4; uint constant USER_MANAGER_USER_HAS_CONFIRMED = USER_MANAGER_SCOPE + 5; uint constant USER_MANAGER_NOT_ENOUGH_GAS = USER_MANAGER_SCOPE + 6; uint constant USER_MANAGER_INVALID_INVOCATION = USER_MANAGER_SCOPE + 7; uint constant USER_MANAGER_DONE = USER_MANAGER_SCOPE + 11; uint constant USER_MANAGER_CANCELLED = USER_MANAGER_SCOPE + 12; using SafeMath for uint; struct Member { address addr; uint groupsCount; mapping(bytes32 => uint) groupName2index; mapping(uint => uint) index2globalIndex; } struct Group { bytes32 name; uint priority; uint membersCount; mapping(address => uint) memberAddress2index; mapping(uint => uint) index2globalIndex; } uint public membersCount; mapping(uint => address) index2memberAddress; mapping(address => uint) memberAddress2index; mapping(address => Member) address2member; uint public groupsCount; mapping(uint => bytes32) index2groupName; mapping(bytes32 => uint) groupName2index; mapping(bytes32 => Group) groupName2group; mapping(bytes32 => bool) public groupsBlocked; // if groupName => true, then couldn't be used for confirmation function() payable public { revert(); } /// @notice Register user /// Can be called only by contract owner /// /// @param _user user address /// /// @return code function registerUser(address _user) external onlyContractOwner returns (uint) { require(_user != 0x0); if (isRegisteredUser(_user)) { return USER_MANAGER_MEMBER_ALREADY_EXIST; } uint _membersCount = membersCount.add(1); membersCount = _membersCount; memberAddress2index[_user] = _membersCount; index2memberAddress[_membersCount] = _user; address2member[_user] = Member(_user, 0); UserCreated(_user); return OK; } /// @notice Discard user registration /// Can be called only by contract owner /// /// @param _user user address /// /// @return code function unregisterUser(address _user) external onlyContractOwner returns (uint) { require(_user != 0x0); uint _memberIndex = memberAddress2index[_user]; if (_memberIndex == 0 || address2member[_user].groupsCount != 0) { return USER_MANAGER_INVALID_INVOCATION; } uint _membersCount = membersCount; delete memberAddress2index[_user]; if (_memberIndex != _membersCount) { address _lastUser = index2memberAddress[_membersCount]; index2memberAddress[_memberIndex] = _lastUser; memberAddress2index[_lastUser] = _memberIndex; } delete address2member[_user]; delete index2memberAddress[_membersCount]; delete memberAddress2index[_user]; membersCount = _membersCount.sub(1); UserDeleted(_user); return OK; } /// @notice Create group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _priority group priority /// /// @return code function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) { require(_groupName != bytes32(0)); if (isGroupExists(_groupName)) { return USER_MANAGER_GROUP_ALREADY_EXIST; } uint _groupsCount = groupsCount.add(1); groupName2index[_groupName] = _groupsCount; index2groupName[_groupsCount] = _groupName; groupName2group[_groupName] = Group(_groupName, _priority, 0); groupsCount = _groupsCount; GroupCreated(_groupName); return OK; } /// @notice Change group status /// Can be called only by contract owner /// /// @param _groupName group name /// @param _blocked block status /// /// @return code function changeGroupActiveStatus(bytes32 _groupName, bool _blocked) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); groupsBlocked[_groupName] = _blocked; return OK; } /// @notice Add users in group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _users user array /// /// @return code function addUsersToGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); Group storage _group = groupName2group[_groupName]; uint _groupMembersCount = _group.membersCount; for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) { address _user = _users[_userIdx]; uint _memberIndex = memberAddress2index[_user]; require(_memberIndex != 0); if (_group.memberAddress2index[_user] != 0) { continue; } _groupMembersCount = _groupMembersCount.add(1); _group.memberAddress2index[_user] = _groupMembersCount; _group.index2globalIndex[_groupMembersCount] = _memberIndex; _addGroupToMember(_user, _groupName); UserToGroupAdded(_user, _groupName); } _group.membersCount = _groupMembersCount; return OK; } /// @notice Remove users in group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _users user array /// /// @return code function removeUsersFromGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); Group storage _group = groupName2group[_groupName]; uint _groupMembersCount = _group.membersCount; for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) { address _user = _users[_userIdx]; uint _memberIndex = memberAddress2index[_user]; uint _groupMemberIndex = _group.memberAddress2index[_user]; if (_memberIndex == 0 || _groupMemberIndex == 0) { continue; } if (_groupMemberIndex != _groupMembersCount) { uint _lastUserGlobalIndex = _group.index2globalIndex[_groupMembersCount]; address _lastUser = index2memberAddress[_lastUserGlobalIndex]; _group.index2globalIndex[_groupMemberIndex] = _lastUserGlobalIndex; _group.memberAddress2index[_lastUser] = _groupMemberIndex; } delete _group.memberAddress2index[_user]; delete _group.index2globalIndex[_groupMembersCount]; _groupMembersCount = _groupMembersCount.sub(1); _removeGroupFromMember(_user, _groupName); UserFromGroupRemoved(_user, _groupName); } _group.membersCount = _groupMembersCount; return OK; } /// @notice Check is user registered /// /// @param _user user address /// /// @return status function isRegisteredUser(address _user) public view returns (bool) { return memberAddress2index[_user] != 0; } /// @notice Check is user in group /// /// @param _groupName user array /// @param _user user array /// /// @return status function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) { return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0; } /// @notice Check is group exist /// /// @param _groupName group name /// /// @return status function isGroupExists(bytes32 _groupName) public view returns (bool) { return groupName2index[_groupName] != 0; } /// @notice Get current group names /// /// @return group names function getGroups() public view returns (bytes32[] _groups) { uint _groupsCount = groupsCount; _groups = new bytes32[](_groupsCount); for (uint _groupIdx = 0; _groupIdx < _groupsCount; ++_groupIdx) { _groups[_groupIdx] = index2groupName[_groupIdx + 1]; } } // PRIVATE function _removeGroupFromMember(address _user, bytes32 _groupName) private { Member storage _member = address2member[_user]; uint _memberGroupsCount = _member.groupsCount; uint _memberGroupIndex = _member.groupName2index[_groupName]; if (_memberGroupIndex != _memberGroupsCount) { uint _lastGroupGlobalIndex = _member.index2globalIndex[_memberGroupsCount]; bytes32 _lastGroupName = index2groupName[_lastGroupGlobalIndex]; _member.index2globalIndex[_memberGroupIndex] = _lastGroupGlobalIndex; _member.groupName2index[_lastGroupName] = _memberGroupIndex; } delete _member.groupName2index[_groupName]; delete _member.index2globalIndex[_memberGroupsCount]; _member.groupsCount = _memberGroupsCount.sub(1); } function _addGroupToMember(address _user, bytes32 _groupName) private { Member storage _member = address2member[_user]; uint _memberGroupsCount = _member.groupsCount.add(1); _member.groupName2index[_groupName] = _memberGroupsCount; _member.index2globalIndex[_memberGroupsCount] = groupName2index[_groupName]; _member.groupsCount = _memberGroupsCount; } }
contract GroupsAccessManager is Object, GroupsAccessManagerEmitter { uint constant USER_MANAGER_SCOPE = 111000; uint constant USER_MANAGER_MEMBER_ALREADY_EXIST = USER_MANAGER_SCOPE + 1; uint constant USER_MANAGER_GROUP_ALREADY_EXIST = USER_MANAGER_SCOPE + 2; uint constant USER_MANAGER_OBJECT_ALREADY_SECURED = USER_MANAGER_SCOPE + 3; uint constant USER_MANAGER_CONFIRMATION_HAS_COMPLETED = USER_MANAGER_SCOPE + 4; uint constant USER_MANAGER_USER_HAS_CONFIRMED = USER_MANAGER_SCOPE + 5; uint constant USER_MANAGER_NOT_ENOUGH_GAS = USER_MANAGER_SCOPE + 6; uint constant USER_MANAGER_INVALID_INVOCATION = USER_MANAGER_SCOPE + 7; uint constant USER_MANAGER_DONE = USER_MANAGER_SCOPE + 11; uint constant USER_MANAGER_CANCELLED = USER_MANAGER_SCOPE + 12; using SafeMath for uint; struct Member { address addr; uint groupsCount; mapping(bytes32 => uint) groupName2index; mapping(uint => uint) index2globalIndex; } struct Group { bytes32 name; uint priority; uint membersCount; mapping(address => uint) memberAddress2index; mapping(uint => uint) index2globalIndex; } uint public membersCount; mapping(uint => address) index2memberAddress; mapping(address => uint) memberAddress2index; mapping(address => Member) address2member; uint public groupsCount; mapping(uint => bytes32) index2groupName; mapping(bytes32 => uint) groupName2index; mapping(bytes32 => Group) groupName2group; mapping(bytes32 => bool) public groupsBlocked; // if groupName => true, then couldn't be used for confirmation function() payable public { revert(); } /// @notice Register user /// Can be called only by contract owner /// /// @param _user user address /// /// @return code function registerUser(address _user) external onlyContractOwner returns (uint) { require(_user != 0x0); if (isRegisteredUser(_user)) { return USER_MANAGER_MEMBER_ALREADY_EXIST; } uint _membersCount = membersCount.add(1); membersCount = _membersCount; memberAddress2index[_user] = _membersCount; index2memberAddress[_membersCount] = _user; address2member[_user] = Member(_user, 0); UserCreated(_user); return OK; } /// @notice Discard user registration /// Can be called only by contract owner /// /// @param _user user address /// /// @return code function unregisterUser(address _user) external onlyContractOwner returns (uint) { require(_user != 0x0); uint _memberIndex = memberAddress2index[_user]; if (_memberIndex == 0 || address2member[_user].groupsCount != 0) { return USER_MANAGER_INVALID_INVOCATION; } uint _membersCount = membersCount; delete memberAddress2index[_user]; if (_memberIndex != _membersCount) { address _lastUser = index2memberAddress[_membersCount]; index2memberAddress[_memberIndex] = _lastUser; memberAddress2index[_lastUser] = _memberIndex; } delete address2member[_user]; delete index2memberAddress[_membersCount]; delete memberAddress2index[_user]; membersCount = _membersCount.sub(1); UserDeleted(_user); return OK; } /// @notice Create group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _priority group priority /// /// @return code function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) { require(_groupName != bytes32(0)); if (isGroupExists(_groupName)) { return USER_MANAGER_GROUP_ALREADY_EXIST; } uint _groupsCount = groupsCount.add(1); groupName2index[_groupName] = _groupsCount; index2groupName[_groupsCount] = _groupName; groupName2group[_groupName] = Group(_groupName, _priority, 0); groupsCount = _groupsCount; GroupCreated(_groupName); return OK; } /// @notice Change group status /// Can be called only by contract owner /// /// @param _groupName group name /// @param _blocked block status /// /// @return code function changeGroupActiveStatus(bytes32 _groupName, bool _blocked) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); groupsBlocked[_groupName] = _blocked; return OK; } /// @notice Add users in group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _users user array /// /// @return code function addUsersToGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); Group storage _group = groupName2group[_groupName]; uint _groupMembersCount = _group.membersCount; for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) { address _user = _users[_userIdx]; uint _memberIndex = memberAddress2index[_user]; require(_memberIndex != 0); if (_group.memberAddress2index[_user] != 0) { continue; } _groupMembersCount = _groupMembersCount.add(1); _group.memberAddress2index[_user] = _groupMembersCount; _group.index2globalIndex[_groupMembersCount] = _memberIndex; _addGroupToMember(_user, _groupName); UserToGroupAdded(_user, _groupName); } _group.membersCount = _groupMembersCount; return OK; } /// @notice Remove users in group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _users user array /// /// @return code function removeUsersFromGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); Group storage _group = groupName2group[_groupName]; uint _groupMembersCount = _group.membersCount; for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) { address _user = _users[_userIdx]; uint _memberIndex = memberAddress2index[_user]; uint _groupMemberIndex = _group.memberAddress2index[_user]; if (_memberIndex == 0 || _groupMemberIndex == 0) { continue; } if (_groupMemberIndex != _groupMembersCount) { uint _lastUserGlobalIndex = _group.index2globalIndex[_groupMembersCount]; address _lastUser = index2memberAddress[_lastUserGlobalIndex]; _group.index2globalIndex[_groupMemberIndex] = _lastUserGlobalIndex; _group.memberAddress2index[_lastUser] = _groupMemberIndex; } delete _group.memberAddress2index[_user]; delete _group.index2globalIndex[_groupMembersCount]; _groupMembersCount = _groupMembersCount.sub(1); _removeGroupFromMember(_user, _groupName); UserFromGroupRemoved(_user, _groupName); } _group.membersCount = _groupMembersCount; return OK; } /// @notice Check is user registered /// /// @param _user user address /// /// @return status function isRegisteredUser(address _user) public view returns (bool) { return memberAddress2index[_user] != 0; } /// @notice Check is user in group /// /// @param _groupName user array /// @param _user user array /// /// @return status function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) { return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0; } /// @notice Check is group exist /// /// @param _groupName group name /// /// @return status function isGroupExists(bytes32 _groupName) public view returns (bool) { return groupName2index[_groupName] != 0; } /// @notice Get current group names /// /// @return group names function getGroups() public view returns (bytes32[] _groups) { uint _groupsCount = groupsCount; _groups = new bytes32[](_groupsCount); for (uint _groupIdx = 0; _groupIdx < _groupsCount; ++_groupIdx) { _groups[_groupIdx] = index2groupName[_groupIdx + 1]; } } // PRIVATE function _removeGroupFromMember(address _user, bytes32 _groupName) private { Member storage _member = address2member[_user]; uint _memberGroupsCount = _member.groupsCount; uint _memberGroupIndex = _member.groupName2index[_groupName]; if (_memberGroupIndex != _memberGroupsCount) { uint _lastGroupGlobalIndex = _member.index2globalIndex[_memberGroupsCount]; bytes32 _lastGroupName = index2groupName[_lastGroupGlobalIndex]; _member.index2globalIndex[_memberGroupIndex] = _lastGroupGlobalIndex; _member.groupName2index[_lastGroupName] = _memberGroupIndex; } delete _member.groupName2index[_groupName]; delete _member.index2globalIndex[_memberGroupsCount]; _member.groupsCount = _memberGroupsCount.sub(1); } function _addGroupToMember(address _user, bytes32 _groupName) private { Member storage _member = address2member[_user]; uint _memberGroupsCount = _member.groupsCount.add(1); _member.groupName2index[_groupName] = _memberGroupsCount; _member.index2globalIndex[_memberGroupsCount] = groupName2index[_groupName]; _member.groupsCount = _memberGroupsCount; } }
19,299
2
// withdraws available balance to WalllaW DAO.
function withdrawToWallaW() external returns (bool) { uint256 units = (block.timestamp - lastCall); uint256 amt = units * perSec; lastCall = block.timestamp; unitsLeft -= units; emit WalllaWWithdrew(msg.sender, amt); return Wtoken.transfer(WalllaWDAO, amt); }
function withdrawToWallaW() external returns (bool) { uint256 units = (block.timestamp - lastCall); uint256 amt = units * perSec; lastCall = block.timestamp; unitsLeft -= units; emit WalllaWWithdrew(msg.sender, amt); return Wtoken.transfer(WalllaWDAO, amt); }
14,813
148
// Perform a call to invoke {IERC721Receiver-onERC721Received} on `to`./ Reverts if the target does not support the function correctly.
function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data) private {
function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data) private {
24,624
6
// get event name by tokenID
function getEventName(uint256 tokenId) public view returns (string memory) { return _eventName[tokenId]; }
function getEventName(uint256 tokenId) public view returns (string memory) { return _eventName[tokenId]; }
21,263
168
// IRariGovernanceTokenDistributor IRariGovernanceTokenDistributor is a simple interface for RariGovernanceTokenDistributor used by RariFundManager and RariFundToken. /
interface IRariGovernanceTokenDistributor { /** * @notice Enum for the Rari pools to which distributions are rewarded. */ enum RariPool { Stable, Yield, Ethereum } /** * @notice Boolean indicating if this contract is disabled. */ function disabled() external returns (bool); /** * @notice Starting block number of the distribution. */ function distributionStartBlock() external returns (uint256); /** * @notice Ending block number of the distribution. */ function distributionEndBlock() external returns (uint256); /** * @dev Updates RGT distribution speeds for each pool given one `pool` and its `newBalance` (only accessible by the RariFundManager corresponding to `pool`). * @param pool The pool whose balance should be refreshed. * @param newBalance The new balance of the pool to be refreshed. */ function refreshDistributionSpeeds(RariPool pool, uint256 newBalance) external; /** * @notice Updates RGT distribution speeds for each pool given one `pool` whose balance should be refreshed. * @param pool The pool whose balance should be refreshed. */ function refreshDistributionSpeeds(RariPool pool) external; /** * @dev Distributes all undistributed RGT earned by `holder` in `pool` (without reverting if no RGT is available to distribute). * @param holder The holder of RSPT, RYPT, or REPT whose RGT is to be distributed. * @param pool The Rari pool for which to distribute RGT. * @return The quantity of RGT distributed. */ function distributeRgt(address holder, RariPool pool) external returns (uint256); /** * @dev Stores the RGT distributed per RSPT/RYPT/REPT right before `holder`'s first incoming RSPT/RYPT/REPT transfer since having a zero balance. * @param holder The holder of RSPT, RYPT, and/or REPT. * @param pool The Rari pool of the pool token. */ function beforeFirstPoolTokenTransferIn(address holder, RariPool pool) external; }
interface IRariGovernanceTokenDistributor { /** * @notice Enum for the Rari pools to which distributions are rewarded. */ enum RariPool { Stable, Yield, Ethereum } /** * @notice Boolean indicating if this contract is disabled. */ function disabled() external returns (bool); /** * @notice Starting block number of the distribution. */ function distributionStartBlock() external returns (uint256); /** * @notice Ending block number of the distribution. */ function distributionEndBlock() external returns (uint256); /** * @dev Updates RGT distribution speeds for each pool given one `pool` and its `newBalance` (only accessible by the RariFundManager corresponding to `pool`). * @param pool The pool whose balance should be refreshed. * @param newBalance The new balance of the pool to be refreshed. */ function refreshDistributionSpeeds(RariPool pool, uint256 newBalance) external; /** * @notice Updates RGT distribution speeds for each pool given one `pool` whose balance should be refreshed. * @param pool The pool whose balance should be refreshed. */ function refreshDistributionSpeeds(RariPool pool) external; /** * @dev Distributes all undistributed RGT earned by `holder` in `pool` (without reverting if no RGT is available to distribute). * @param holder The holder of RSPT, RYPT, or REPT whose RGT is to be distributed. * @param pool The Rari pool for which to distribute RGT. * @return The quantity of RGT distributed. */ function distributeRgt(address holder, RariPool pool) external returns (uint256); /** * @dev Stores the RGT distributed per RSPT/RYPT/REPT right before `holder`'s first incoming RSPT/RYPT/REPT transfer since having a zero balance. * @param holder The holder of RSPT, RYPT, and/or REPT. * @param pool The Rari pool of the pool token. */ function beforeFirstPoolTokenTransferIn(address holder, RariPool pool) external; }
35,695
11
// Withdraw ether to owner account
function withdrawAll() onlyOwner public { owner.transfer(address(this).balance); }
function withdrawAll() onlyOwner public { owner.transfer(address(this).balance); }
43,411
1
// Total staked tokens
uint256 public totalStakedTokens;
uint256 public totalStakedTokens;
44,404
11
// =========================================================..._ | _ _|_|` __ _ __| _ _|_ _. |_)|(_| |~|~(_)| | | |(_|(_| | (_| . platform data=|=======================================================
mapping (address => FMAPDatasets.Player) public players_; mapping (address => mapping (uint256 => FMAPDatasets.OfferInfo)) public playerOfferOrders_; // player => player offer count => offerInfo. mapping (address => mapping (uint256 => uint256)) public playerAcceptOrders_; // player => count => orderId. player orders to accept; uint256 private restOfferAmount_ = 0; // offered amount that not been accepted; FMAPDatasets.AcceptOrder private currentOrder_; // unmatched current order; mapping (uint256 => FMAPDatasets.AcceptOrder) public acceptOrders_; // accept orders; address private teamXWallet; uint256 public _totalFee; uint256 public _totalXT;
mapping (address => FMAPDatasets.Player) public players_; mapping (address => mapping (uint256 => FMAPDatasets.OfferInfo)) public playerOfferOrders_; // player => player offer count => offerInfo. mapping (address => mapping (uint256 => uint256)) public playerAcceptOrders_; // player => count => orderId. player orders to accept; uint256 private restOfferAmount_ = 0; // offered amount that not been accepted; FMAPDatasets.AcceptOrder private currentOrder_; // unmatched current order; mapping (uint256 => FMAPDatasets.AcceptOrder) public acceptOrders_; // accept orders; address private teamXWallet; uint256 public _totalFee; uint256 public _totalXT;
2,608
100
// When you stake say 1000 TUSD for a day that will be your maximum if you stake the next time 300 TUSD your maximum will stay the same if you stake 2000 at once it will increase to 2000 TUSD
mapping(bytes32 => uint256) public numberOfParticipants; mapping(address => uint256) public depositBlockStarts; uint256 public constant oneDayInBlocks = 6500; uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility uint256 public constant oneMillion = 1e6;
mapping(bytes32 => uint256) public numberOfParticipants; mapping(address => uint256) public depositBlockStarts; uint256 public constant oneDayInBlocks = 6500; uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility uint256 public constant oneMillion = 1e6;
20,400
170
// transfers LP from the owners wallet to holdersmust approve this contract, on pair contract before calling
function ManualLiquidityDistribution(uint256 amount) public onlyOwner { bool success = IERC20(pair).transferFrom( msg.sender, address(dividendTracker), amount ); if (success) { dividendTracker.distributeLPDividends(amount); } }
function ManualLiquidityDistribution(uint256 amount) public onlyOwner { bool success = IERC20(pair).transferFrom( msg.sender, address(dividendTracker), amount ); if (success) { dividendTracker.distributeLPDividends(amount); } }
26,654
317
// Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. Reverts if minting these tokens would put the position's collateralization ratio below theglobal collateralization ratio. This contract must be approved to spend at least `collateralAmount` of`collateralCurrency`. collateralAmount is the number of collateral tokens to collateralize the position with numTokens is the number of tokens to mint from the position. /
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant()
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant()
8,091