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
49
// rewardHandler is the instance which finally stores the reward tokenand distributes them to the different recipients_addressRegistry IAdressRegistry to get system addresses _previousController The previous controller /
constructor(IAddressRegistry _addressRegistry, address _previousController) { // Initialize state previousController = _previousController; // Proxied booster address / immutable _booster = IBooster( _addressRegistry.getRegistryEntry(AddressBook.WOWS_BOOSTER_PROXY) ); // Initialize {Ownable} address _marketingWallet = _addressRegistry.getRegistryEntry( AddressBook.MARKETING_WALLET ); transferOwnership(_marketingWallet); }
constructor(IAddressRegistry _addressRegistry, address _previousController) { // Initialize state previousController = _previousController; // Proxied booster address / immutable _booster = IBooster( _addressRegistry.getRegistryEntry(AddressBook.WOWS_BOOSTER_PROXY) ); // Initialize {Ownable} address _marketingWallet = _addressRegistry.getRegistryEntry( AddressBook.MARKETING_WALLET ); transferOwnership(_marketingWallet); }
21,323
56
// Mint tokens given a minter contract and minter arguments/minter The minter contract to use/tokenId The token ID to mint/quantity The quantity of tokens to mint/minterArguments The arguments to pass to the minter
function mint(IMinter1155 minter, uint256 tokenId, uint256 quantity, bytes calldata minterArguments) external payable nonReentrant { // Require admin from the minter to mint _requireAdminOrRole(address(minter), tokenId, PERMISSION_BIT_MINTER); // Get value sent and handle mint fee uint256 ethValueSent = _handleFeeAndGetValueSent(quantity); // Execute commands returned from minter _executeCommands(minter.requestMint(msg.sender, tokenId, quantity, ethValueSent, minterArguments).commands, ethValueSent, tokenId); emit Purchased(msg.sender, address(minter), tokenId, quantity, msg.value); }
function mint(IMinter1155 minter, uint256 tokenId, uint256 quantity, bytes calldata minterArguments) external payable nonReentrant { // Require admin from the minter to mint _requireAdminOrRole(address(minter), tokenId, PERMISSION_BIT_MINTER); // Get value sent and handle mint fee uint256 ethValueSent = _handleFeeAndGetValueSent(quantity); // Execute commands returned from minter _executeCommands(minter.requestMint(msg.sender, tokenId, quantity, ethValueSent, minterArguments).commands, ethValueSent, tokenId); emit Purchased(msg.sender, address(minter), tokenId, quantity, msg.value); }
6,366
103
// no previous update block number -- use 0 instead
0 );
0 );
34,122
61
// i.e. supplied = supplied / 10(18 - decimals)
return (supplied, borrowed);
return (supplied, borrowed);
457
14
// throw if empty
require(index.size>0); if(last_node_id == 0x0)last_node_id = index.children[index.root].root; else last_node_id = index.children[getParent(last_node_id)].children[last_node_id].right; bytes32 section_id = getParent(last_node_id); TreeLib.Section storage sector = index.children[section_id]; uint r = 0;
require(index.size>0); if(last_node_id == 0x0)last_node_id = index.children[index.root].root; else last_node_id = index.children[getParent(last_node_id)].children[last_node_id].right; bytes32 section_id = getParent(last_node_id); TreeLib.Section storage sector = index.children[section_id]; uint r = 0;
51,031
18
// Transfers eligible payout funds to insuree/
function pay(address insuree) external { uint256 payout = insurees[insuree].payout; delete(insurees[insuree]); insuree.transfer(payout); emit InsurancePaid(insuree, payout); }
function pay(address insuree) external { uint256 payout = insurees[insuree].payout; delete(insurees[insuree]); insuree.transfer(payout); emit InsurancePaid(insuree, payout); }
9,531
83
// Plasma Bridge
interface IDepositManager { function depositERC20ForUser( address _token, address _user, uint256 _amount ) external; }
interface IDepositManager { function depositERC20ForUser( address _token, address _user, uint256 _amount ) external; }
25,602
4
// Emitted when pendingGuardian is accepted, which means gaurdian is updated
event NewGuardian(address oldGuardian, address newGuardian);
event NewGuardian(address oldGuardian, address newGuardian);
25,862
7
// send a LayerZero message to the specified address at a LayerZero endpoint._dstChainId - the destination chain identifier_destination - the address on destination chain (in bytes). address length/format may vary by chains_payload - a custom bytes payload to send to the destination contract_refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address_zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction_adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
2,902
225
// See {ERC20-decreaseAllowance}./
function decreaseAllowance(address _spender, uint256 _subtractedValue) external virtual returns (bool) { _approve(msg.sender, _spender, _allowances[msg.sender][_spender].sub(_subtractedValue, "ERC20: decreased allowance below zero")); return true; }
function decreaseAllowance(address _spender, uint256 _subtractedValue) external virtual returns (bool) { _approve(msg.sender, _spender, _allowances[msg.sender][_spender].sub(_subtractedValue, "ERC20: decreased allowance below zero")); return true; }
15,235
139
// CarbonDollar whitelisted users burn CUSD into a WhitelistedToken. Unlike PermissionedTokenwhitelisted users, CarbonDollar whitelisted users cannot burn ordinary CUSD without converting into WT
function _setWhitelistedUser(address _who) internal { require(isPermission(CONVERT_CARBON_DOLLAR_SIG), "Converting CUSD not supported"); require(isPermission(BURN_CARBON_DOLLAR_SIG), "Burning CUSD not supported"); require(isPermission(BLACKLISTED_SIG), "Blacklisting not supported"); setUserPermission(_who, CONVERT_CARBON_DOLLAR_SIG); setUserPermission(_who, BURN_CARBON_DOLLAR_SIG); removeUserPermission(_who, BLACKLISTED_SIG); emit LogWhitelistedUser(_who); }
function _setWhitelistedUser(address _who) internal { require(isPermission(CONVERT_CARBON_DOLLAR_SIG), "Converting CUSD not supported"); require(isPermission(BURN_CARBON_DOLLAR_SIG), "Burning CUSD not supported"); require(isPermission(BLACKLISTED_SIG), "Blacklisting not supported"); setUserPermission(_who, CONVERT_CARBON_DOLLAR_SIG); setUserPermission(_who, BURN_CARBON_DOLLAR_SIG); removeUserPermission(_who, BLACKLISTED_SIG); emit LogWhitelistedUser(_who); }
24,874
33
// We are in phase 1 of the sale
require(whitelistedPhase == 1); uint256 accountBalance = tokenContract.balanceOf(msg.sender);
require(whitelistedPhase == 1); uint256 accountBalance = tokenContract.balanceOf(msg.sender);
32,361
42
// Buy accesory to the MON
function buyAccesory(uint256 nftId, uint256 itemId) external notPaused { require(itemExists(itemId), "This item doesn't exist"); uint256 amount = itemPrice[itemId]; require( ownerOf(nftId) == msg.sender || careTaker[nftId][ownerOf(nftId)] == msg.sender, "You must own the MON or be a care taker to buy items" ); // require(isMONAlive(nftId), "Your MON is dead"); uint256 amountToBurn = amount.mul(burnPercentage).div(100); if (!isMONAlive(nftId)) { MONScore[nftId] = itemPoints[itemId]; timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); } else { //recalculate timeUntilStarving. timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); MONScore[nftId] = MONScore[nftId].add(itemPoints[itemId]); } // burn 90% so they go back to community mining and staking, and send 10% to devs if (devAllocation <= maxDevAllocation) { devAllocation = devAllocation.add(amount.sub(amountToBurn)); SMON.transferFrom(msg.sender, address(this), amount); // burn 90% of token, 10% stay for dev and community fund SMON.burn(amountToBurn); } else { SMON.burnFrom(msg.sender, amount); } emit MONConsumed(nftId, msg.sender, itemId); }
function buyAccesory(uint256 nftId, uint256 itemId) external notPaused { require(itemExists(itemId), "This item doesn't exist"); uint256 amount = itemPrice[itemId]; require( ownerOf(nftId) == msg.sender || careTaker[nftId][ownerOf(nftId)] == msg.sender, "You must own the MON or be a care taker to buy items" ); // require(isMONAlive(nftId), "Your MON is dead"); uint256 amountToBurn = amount.mul(burnPercentage).div(100); if (!isMONAlive(nftId)) { MONScore[nftId] = itemPoints[itemId]; timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); } else { //recalculate timeUntilStarving. timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); MONScore[nftId] = MONScore[nftId].add(itemPoints[itemId]); } // burn 90% so they go back to community mining and staking, and send 10% to devs if (devAllocation <= maxDevAllocation) { devAllocation = devAllocation.add(amount.sub(amountToBurn)); SMON.transferFrom(msg.sender, address(this), amount); // burn 90% of token, 10% stay for dev and community fund SMON.burn(amountToBurn); } else { SMON.burnFrom(msg.sender, amount); } emit MONConsumed(nftId, msg.sender, itemId); }
5,242
263
// last time we ran harvest
uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare);
uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare);
13,149
287
// only way a democ admin can deploy a ballot
function dDeployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint256 packed) onlyDemocEditor(democHash)
function dDeployBallot(bytes32 democHash, bytes32 specHash, bytes32 extraData, uint256 packed) onlyDemocEditor(democHash)
47,174
79
// Emitted when an aToken is initialized underlyingAsset The address of the underlying asset pool The address of the associated lending pool treasury The address of the treasury incentivesController The address of the incentives controller for this aToken aTokenDecimals the decimals of the underlying aTokenName the name of the aToken aTokenSymbol the symbol of the aToken params A set of encoded parameters for additional initialization // Initializes the aToken pool The address of the lending pool where this aToken will be used treasury The address of the Aave treasury, receiving the fees on this aToken underlyingAsset The address of the underlying
function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external;
function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external;
50,904
53
// transfer commission to owner
owner.transfer(commissionSumToTransfer);
owner.transfer(commissionSumToTransfer);
86,621
79
// Store an identifier that can be used to prove that the given message was relayed by some user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256(abi.encodePacked(xDomainCalldata, msg.sender, block.number)); relayedMessages[relayId] = true;
bytes32 relayId = keccak256(abi.encodePacked(xDomainCalldata, msg.sender, block.number)); relayedMessages[relayId] = true;
71,532
67
// IVotingSessionStorage IVotingSessionStorage interface Cyril Lapinte - <cyril.lapinte@openfiz.com> Error messages /
abstract contract IVotingSessionStorage is IVotingDefinitions { event SessionRuleUpdated( uint64 campaignPeriod, uint64 votingPeriod, uint64 executionPeriod, uint64 gracePeriod, uint64 periodOffset, uint8 openProposals, uint8 maxProposals, uint8 maxProposalsOperator, uint256 newProposalThreshold, address[] nonVotingAddresses); event ResolutionRequirementUpdated( address target, bytes4 methodSignature, uint128 majority, uint128 quorum, uint256 executionThreshold ); event TokenDefined(address token, address core); event DelegateDefined(address delegate); event SponsorDefined(address indexed voter, address address_, uint64 until); event SessionScheduled(uint256 indexed sessionId, uint64 voteAt); event SessionArchived(uint256 indexed sessionId); event ProposalDefined(uint256 indexed sessionId, uint8 proposalId); event ProposalUpdated(uint256 indexed sessionId, uint8 proposalId); event ProposalCancelled(uint256 indexed sessionId, uint8 proposalId); event ResolutionExecuted(uint256 indexed sessionId, uint8 proposalId); event Vote(uint256 indexed sessionId, address voter, uint256 weight); }
abstract contract IVotingSessionStorage is IVotingDefinitions { event SessionRuleUpdated( uint64 campaignPeriod, uint64 votingPeriod, uint64 executionPeriod, uint64 gracePeriod, uint64 periodOffset, uint8 openProposals, uint8 maxProposals, uint8 maxProposalsOperator, uint256 newProposalThreshold, address[] nonVotingAddresses); event ResolutionRequirementUpdated( address target, bytes4 methodSignature, uint128 majority, uint128 quorum, uint256 executionThreshold ); event TokenDefined(address token, address core); event DelegateDefined(address delegate); event SponsorDefined(address indexed voter, address address_, uint64 until); event SessionScheduled(uint256 indexed sessionId, uint64 voteAt); event SessionArchived(uint256 indexed sessionId); event ProposalDefined(uint256 indexed sessionId, uint8 proposalId); event ProposalUpdated(uint256 indexed sessionId, uint8 proposalId); event ProposalCancelled(uint256 indexed sessionId, uint8 proposalId); event ResolutionExecuted(uint256 indexed sessionId, uint8 proposalId); event Vote(uint256 indexed sessionId, address voter, uint256 weight); }
47,353
110
// Get the total asset value held in the platform. This includes any interest that was generated since depositing. _assetAddress of the assetreturn balanceTotal value of the asset in the platform /
function checkBalance(address _asset)
function checkBalance(address _asset)
39,572
20
// Write the _preBytes data into the tempBytes memory 32 bytes at a time.
mstore(mc, mload(cc))
mstore(mc, mload(cc))
24,336
29
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
mapping (address => Counters.Counter) private _ownedTokensCount;
39,609
5
// constructor is given number of sigs required to do protected "multiOwner" transactions
function MultiOwnable (address[] _multiOwners, uint _multiRequires) public { require(0 < _multiRequires && _multiRequires <= _multiOwners.length); m_numOwners = _multiOwners.length; require(m_numOwners <= 8); // Bigger then 8 co-owners, not support ! for (uint i = 0; i < _multiOwners.length; ++i) { m_owners[i] = _multiOwners[i]; require(m_owners[i] != address(0)); } m_multiRequires = _multiRequires; }
function MultiOwnable (address[] _multiOwners, uint _multiRequires) public { require(0 < _multiRequires && _multiRequires <= _multiOwners.length); m_numOwners = _multiOwners.length; require(m_numOwners <= 8); // Bigger then 8 co-owners, not support ! for (uint i = 0; i < _multiOwners.length; ++i) { m_owners[i] = _multiOwners[i]; require(m_owners[i] != address(0)); } m_multiRequires = _multiRequires; }
30,460
119
// keccak256("fallback_manager.handler.address")
bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
8,302
18
// sets up the immutable vars: signers and required confirmations.
constructor( address signer1_, address signer2_, address signer3_, address signer4_, address signer5_, address signer6_, uint256 requiredConfirmations_
constructor( address signer1_, address signer2_, address signer3_, address signer4_, address signer5_, address signer6_, uint256 requiredConfirmations_
40,777
43
// Calculates the amount that has already vested but hasn't been released yet. token ERC20 token which is being vested /
function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[address(token)]); }
function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[address(token)]); }
17,462
16
// Increase nonce and execute transaction.
nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures);
nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures);
280
137
// ``` As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)and `uint256` (`UintSet`) are supported. /
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
22,996
58
// 剩下全部分給 junior
accounting.juniorPoolValue = accounting.juniorPoolValue.add(incomeToday); incomeToday = ud(0);
accounting.juniorPoolValue = accounting.juniorPoolValue.add(incomeToday); incomeToday = ud(0);
16,708
198
// Possibly change the sale state based on factors
if (SaleState == 1 && block.timestamp > 1651194061) // Arbor Day 2022, public sale! SaleState = 2; else if (SaleState == 2 && block.timestamp > lastSaleTime + 1209600) { // 2 weeks after last sale, start fire sale SaleState = 3; FireSaleStartTime = block.timestamp; }
if (SaleState == 1 && block.timestamp > 1651194061) // Arbor Day 2022, public sale! SaleState = 2; else if (SaleState == 2 && block.timestamp > lastSaleTime + 1209600) { // 2 weeks after last sale, start fire sale SaleState = 3; FireSaleStartTime = block.timestamp; }
13,821
73
// To air drop
function airDropMultiple(address[] memory recipients,uint[] memory tokenAmount) public returns (bool) { require(saleMode == 0 || saleMode == 2,"airdrop not allowed"); uint reciversLength = recipients.length; require(reciversLength <= 150, "Too many address"); for(uint i = 0; i < reciversLength; i++) { _airDrop(recipients[i],tokenAmount[i]); } return true; }
function airDropMultiple(address[] memory recipients,uint[] memory tokenAmount) public returns (bool) { require(saleMode == 0 || saleMode == 2,"airdrop not allowed"); uint reciversLength = recipients.length; require(reciversLength <= 150, "Too many address"); for(uint i = 0; i < reciversLength; i++) { _airDrop(recipients[i],tokenAmount[i]); } return true; }
8,891
271
// Sale status
bool public hasSaleStarted = false;
bool public hasSaleStarted = false;
10,476
88
// calculating the timestamp that will used as an index of the next bucket i.e buckets period will be look like this T1 to T2-1, T2 to T3-1 .... where T1,T2,T3 are timestamps having 24 hrs difference
_fromTime = _fromTime.add(_diffDays.mul(1 days)); return (sumOfLastPeriod, _fromTime, counter);
_fromTime = _fromTime.add(_diffDays.mul(1 days)); return (sumOfLastPeriod, _fromTime, counter);
43,542
12
// Only the MevEth contract can call this function
if (msg.sender != mevEth) { revert MevEthErrors.UnAuthorizedCaller(); }
if (msg.sender != mevEth) { revert MevEthErrors.UnAuthorizedCaller(); }
44,851
0
// 4 rounds : 0 = not open, 1 = guaranty round, 2 = First come first serve, 3 = sale finisheduint256 public roundNumber;
uint256 public round1BeganAt; // must be init before deployment uint256 public claimUnlockedTimestamp; // init timestamp of claim begins
uint256 public round1BeganAt; // must be init before deployment uint256 public claimUnlockedTimestamp; // init timestamp of claim begins
55,012
1
// White List Token Data
uint256 public MAX_PRE_MINTS; uint256 public MAX_OG_MINTS;
uint256 public MAX_PRE_MINTS; uint256 public MAX_OG_MINTS;
4,386
7
// Returns the address of the pending Governor. /
function _pendingGovernor() internal view returns (address pendingGovernor)
function _pendingGovernor() internal view returns (address pendingGovernor)
27,193
19
// ------------------------------------------------------------------------ Transfer the balance from token owner's account to to account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
3,206
137
// swap half amount for other
address other = _from == token0 ? token1 : token0; _approveTokenIfNeeded(other); uint sellAmount = amount.div(2); uint otherAmount = _swap(_from, sellAmount, other); UNIC_ROUTER.addLiquidity(_from, other, amount.sub(sellAmount), otherAmount, 0, 0, address(this), block.timestamp);
address other = _from == token0 ? token1 : token0; _approveTokenIfNeeded(other); uint sellAmount = amount.div(2); uint otherAmount = _swap(_from, sellAmount, other); UNIC_ROUTER.addLiquidity(_from, other, amount.sub(sellAmount), otherAmount, 0, 0, address(this), block.timestamp);
28,691
291
// The asset lent out for the loan
address lendingToken;
address lendingToken;
44,345
20
// this allows the contract to send adb to multiple wallets within on transaction, saving gas costs /
function transferMultiple(address payable[] memory _addrs, uint256[] memory _amounts) public payable notSuspended onlyOwner { // addresses and amount array must be the same size require(_addrs.length == _amounts.length, "Arrays are not the same size"); // check that the array length of _addrs is <= the batchLimit require(_addrs.length <= batchLimit, "Too many addresses"); // check that the contract has enough adb balance to send the transactions uint totalAmounts = sum(_amounts); uint contractBalance = adbank.balanceOf(address(this)); // check that the contract has enough adb funds to cover the transfer require(totalAmounts <= contractBalance, "Not enough tokens in contract to cover transfer"); // loop trough each array and send the corresponding amount for(uint i = 0; i < _addrs.length; i++){ // subtract the transfer amount from the tokensInContract contractBalance -= _amounts[i]; // initiate the transfer to the specified address and the amount of tokens going to it adbank.transfer(_addrs[i], _amounts[i]); } }
function transferMultiple(address payable[] memory _addrs, uint256[] memory _amounts) public payable notSuspended onlyOwner { // addresses and amount array must be the same size require(_addrs.length == _amounts.length, "Arrays are not the same size"); // check that the array length of _addrs is <= the batchLimit require(_addrs.length <= batchLimit, "Too many addresses"); // check that the contract has enough adb balance to send the transactions uint totalAmounts = sum(_amounts); uint contractBalance = adbank.balanceOf(address(this)); // check that the contract has enough adb funds to cover the transfer require(totalAmounts <= contractBalance, "Not enough tokens in contract to cover transfer"); // loop trough each array and send the corresponding amount for(uint i = 0; i < _addrs.length; i++){ // subtract the transfer amount from the tokensInContract contractBalance -= _amounts[i]; // initiate the transfer to the specified address and the amount of tokens going to it adbank.transfer(_addrs[i], _amounts[i]); } }
35,467
25
// Emitted after a successful raffle entry/user Address of raffle participant/entries Number of entries from participant
event RaffleEntered(address indexed user, uint256 entries);
event RaffleEntered(address indexed user, uint256 entries);
44,512
40
// get whether value exists. /
function has(Set storage _obj, bytes32 _value) internal view returns (bool)
function has(Set storage _obj, bytes32 _value) internal view returns (bool)
41,761
124
// Swap `amount` of `fromToken` to `toToken` and send them to the `recipient`.The `fromToken` and `toToken` arguments can be AMM pairs.Reverts if the `recipient` received less tokens than `minReceived`.Requires approval.fromToken The token to take from `msg.sender` and exchange for `toToken`.toToken The token that will be bought and sent to the `recipient`.recipient The destination address to receive the `toToken`.amount The amount that the zapper should take from the `msg.sender` and swap.minReceived The minimum amount of `toToken` the `recipient` should receive. Otherwise the transaction reverts./
function swapERC20(IERC20 fromToken, IERC20 toToken, address recipient, uint256 amount, uint256 minReceived) external returns (uint256 received);
function swapERC20(IERC20 fromToken, IERC20 toToken, address recipient, uint256 amount, uint256 minReceived) external returns (uint256 received);
4,497
12
// Emitted when a new COMP speed is set for a contributor
event ContributorCompSpeedUpdated( address indexed contributor, uint256 newSpeed );
event ContributorCompSpeedUpdated( address indexed contributor, uint256 newSpeed );
4,026
99
// Returns whether an account is excluded from reward./
function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedFromReward[account]; }
function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedFromReward[account]; }
33,478
6
// Returns the number of tokens unlocked per second in the current cycle.return (uint256) number of tokens per second. /
function getCurrentRewardRate() external view returns (uint256);
function getCurrentRewardRate() external view returns (uint256);
98
63
// Average blocks per max rebase duration (48hrs), assume 12 seconds per block initially
_averageBlocks = MAX_REBASE_SECS.div(12);
_averageBlocks = MAX_REBASE_SECS.div(12);
7,615
65
// Retrieve the dividends owned by the caller. If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. The reason for this, is that in the frontend, we will want to get the total divs (global + ref) But in the internal calculations, we want them separate. /
function myDividends(bool _includeReferralBonus) public view returns (uint) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; }
function myDividends(bool _includeReferralBonus) public view returns (uint) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; }
15,565
320
// utility function that converts an token to an ERC20 /
function toERC20(Token token) internal pure returns (ERC20) { return ERC20(address(token)); }
function toERC20(Token token) internal pure returns (ERC20) { return ERC20(address(token)); }
35,182
11
// Get all the JSON metadata in place and base64 encode it.
string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "',
string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "',
35,099
1
// That structure describes current user Account moneyNew - invested money in currentRound moneyHidden - invested in previous round and not profit yet profitTotal - total profit of user account (it never decreases) profitTaken - profit taken by user lastUserUpdateRound - last round when account was updated
struct Account { uint moneyNew; uint moneyHidden; uint profitTotal; uint profitTaken; uint lastUserUpdateRound; }
struct Account { uint moneyNew; uint moneyHidden; uint profitTotal; uint profitTaken; uint lastUserUpdateRound; }
21,715
100
// and now shift left the number of bytes to leave space for the length in the slot
exp(0x100, sub(32, newlength)) ),
exp(0x100, sub(32, newlength)) ),
79,160
266
// 134
entry "autoacetylated" : ENG_ADJECTIVE
entry "autoacetylated" : ENG_ADJECTIVE
16,746
187
// ECDSA library supports both 64 and 65-byte long signatures. we only "require" it here so that the revert reason on invalid signature will be of "VerifyingPaymaster", and not "ECDSA"
require(signature.length == 64 || signature.length == 65, "VerifyingPaymaster: invalid signature length in paymasterAndData"); bytes32 hash = ECDSA.toEthSignedMessageHash(getHash(userOp, validUntil, validAfter)); senderNonce[userOp.getSender()]++;
require(signature.length == 64 || signature.length == 65, "VerifyingPaymaster: invalid signature length in paymasterAndData"); bytes32 hash = ECDSA.toEthSignedMessageHash(getHash(userOp, validUntil, validAfter)); senderNonce[userOp.getSender()]++;
10,372
3
// Copyright 2022 Max Flow O2Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License. You may obtain a copy of the License atUnless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions andlimitations under the License./
abstract contract TimeCop is MaxAccess { uint internal startSale; event SaleSet(uint start); function setStartTime( uint time ) external onlyDev() { startSale = time; emit SaleSet(time); } function showStart() external view virtual returns (uint) { return startSale; } modifier onlySale() { if (block.timestamp < startSale) { revert TooSoonJunior({ yourTime: block.timestamp , hitTime: startSale }); } if (startSale == 0) { revert MaxSplaining({ reason: "TC:E1" }); } _; } }
abstract contract TimeCop is MaxAccess { uint internal startSale; event SaleSet(uint start); function setStartTime( uint time ) external onlyDev() { startSale = time; emit SaleSet(time); } function showStart() external view virtual returns (uint) { return startSale; } modifier onlySale() { if (block.timestamp < startSale) { revert TooSoonJunior({ yourTime: block.timestamp , hitTime: startSale }); } if (startSale == 0) { revert MaxSplaining({ reason: "TC:E1" }); } _; } }
15,404
58
// Restore
mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3)
mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3)
20,194
4
// if not last element, switch with last
if (pos < admins.length - 1) { admins[pos] = admins[admins.length - 1]; }
if (pos < admins.length - 1) { admins[pos] = admins[admins.length - 1]; }
41,879
111
// Returns number of canvases owned by the given address./
function balanceOf(address _owner) external view returns (uint) { return addressToCount[_owner]; }
function balanceOf(address _owner) external view returns (uint) { return addressToCount[_owner]; }
36,429
7
// Set list of random numbers on Scratch Card /
function fillScratchCard(uint _id) external { ScratchCard storage _scratchCard = scratchCards[_id]; require(_scratchCard.isScratch == false, "You already use this Scratch Card"); _scratchCard.isScratch = true; getRandomNumber(); for(uint i = 0; i < 9; i++){ uint256 _randomNumber = uint256(keccak256(abi.encode(randomResult, i))) % 8 + 1; // 0 - 9 _scratchCard.numbers.push(_randomNumber); } }
function fillScratchCard(uint _id) external { ScratchCard storage _scratchCard = scratchCards[_id]; require(_scratchCard.isScratch == false, "You already use this Scratch Card"); _scratchCard.isScratch = true; getRandomNumber(); for(uint i = 0; i < 9; i++){ uint256 _randomNumber = uint256(keccak256(abi.encode(randomResult, i))) % 8 + 1; // 0 - 9 _scratchCard.numbers.push(_randomNumber); } }
12,644
7
// CheckReceiptProof param: _id (bytes32) Unique id of chain submitting block from param: _blockHash (bytes32) Block hash of block being submitted param: _parentNodes (bytes) RLP-encoded array of all relevant nodes from root node to node to prove param: _path (bytes) Byte array of the path to the node to be proved emits: VerifiedTxProof(chainId, blockHash, proofType)chainId: (bytes32) hash of the chain verifying proof againstblockHash: (bytes32) hash of the block verifying proof againstproofType: (uint) enum of proof type All data associated with the proof must be constructed and paddChainrovided to this function. Modifiers restrict execution of this function to only allow if the
function CheckReceiptProof( bytes32 _id, bytes32 _blockHash, bytes _value, bytes _parentNodes, bytes _path ) onlyRegisteredChains(_id) onlyExistingBlocks(_blockHash) public
function CheckReceiptProof( bytes32 _id, bytes32 _blockHash, bytes _value, bytes _parentNodes, bytes _path ) onlyRegisteredChains(_id) onlyExistingBlocks(_blockHash) public
2,041
93
// Period: from June 15, 2018 @ UTC 0:00 to June 21, 2018 @ UTC 23:59; Price: 1 ETH = 1680 TKP
if (now >= startDate + 1209480 && now < startDate + 1814280) return 1680;
if (now >= startDate + 1209480 && now < startDate + 1814280) return 1680;
45,894
20
// Set the cost to yoink, takes effect on the next round
function setYoinkCost(uint256 _yoinkCost) external onlyOwner { nextRoundYoinkCost = _yoinkCost; }
function setYoinkCost(uint256 _yoinkCost) external onlyOwner { nextRoundYoinkCost = _yoinkCost; }
18,401
9
// Max mint per tx
uint256 public constant MAX_MINT_AMOUNT = 30;
uint256 public constant MAX_MINT_AMOUNT = 30;
24,788
121
// StableSwap alUSD + 3CRV (meta pool)
StableSwapAlUsd3Crv private constant CURVE_POOL = StableSwapAlUsd3Crv(0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c);
StableSwapAlUsd3Crv private constant CURVE_POOL = StableSwapAlUsd3Crv(0x43b4FdFD4Ff969587185cDB6f0BD875c5Fc83f8c);
12,102
17
// Remove UniswapRouters from the whitelist so that they cannot be used to swap tokens./_addr The addresses to remove the whitelist
function removeWhitelistedRouter(address[] memory _addr) external onlyOwner { for (uint256 i=0; i < _addr.length; i++) { _whitelistedRouters.remove(_addr[i]); } }
function removeWhitelistedRouter(address[] memory _addr) external onlyOwner { for (uint256 i=0; i < _addr.length; i++) { _whitelistedRouters.remove(_addr[i]); } }
16,666
10
// 0
(uint256 reserveOut, uint256 reserveIn,) = p.getReserves(); inputAmount = inputAmount * 997; // Calculate after fee inputAmount = (inputAmount * reserveOut)/(reserveIn * 1000 + inputAmount); // Calculate outputNeeded p.swap(inputAmount, 0, address(pairs[i+1]), "");
(uint256 reserveOut, uint256 reserveIn,) = p.getReserves(); inputAmount = inputAmount * 997; // Calculate after fee inputAmount = (inputAmount * reserveOut)/(reserveIn * 1000 + inputAmount); // Calculate outputNeeded p.swap(inputAmount, 0, address(pairs[i+1]), "");
9,723
26
// Sets the paused state of the contract /
function flipPausedState() external onlyOwner { isPaused = !isPaused; }
function flipPausedState() external onlyOwner { isPaused = !isPaused; }
80,187
43
// IMPORTANT: Assume this contract has already received `flashLoanQuantity` of redeemTokens. We are flash swapping from an underlying <> shortOptionToken pair, paying back a portion using underlyingTokens received from closing options. In the flash open, we did redeemTokens to underlyingTokens. In the flash close (this function), we are doing underlyingTokens to redeemTokens and keeping the remainder.
address underlyingToken = IOption(optionAddress) .getUnderlyingTokenAddress(); address redeemToken = IOption(optionAddress).redeemToken(); require(path[1] == redeemToken, "ERR_END_PATH_NOT_REDEEM");
address underlyingToken = IOption(optionAddress) .getUnderlyingTokenAddress(); address redeemToken = IOption(optionAddress).redeemToken(); require(path[1] == redeemToken, "ERR_END_PATH_NOT_REDEEM");
4,624
16
// Force end of game if server does not respond. Only possible after a time periodto give the server a chance to respond. _gameType Game type. _betNum Bet number. _betValue Value of bet. _balance Current balance. _endInitiatedTime Time server initiated end.return New game session balance. /
function playerForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view
function playerForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view
38,208
2
// Withdraws tokens from the lending pool. _reserve The token to withdraw. _amount The total amount of tokens to withdraw. /
function withdraw(address _reserve, uint256 _amount) external;
function withdraw(address _reserve, uint256 _amount) external;
27,855
498
// Move values from spender to recipient
_moveTokens(_spender, _recipient, _amount);
_moveTokens(_spender, _recipient, _amount);
35,003
16
// Reserve allocations // How many tokens each reserve wallet has claimed /
modifier onlyReserveWallets { require(allocations[msg.sender] > 0); _; }
modifier onlyReserveWallets { require(allocations[msg.sender] > 0); _; }
73,106
521
// Mapping from tokenId => URI
mapping(uint256 => string) private uri;
mapping(uint256 => string) private uri;
39,554
51
// Updates metadata. _metadata Seed contract metadata, that is IPFS Hash /
function updateMetadata(bytes memory _metadata) external { require(initialized != true || msg.sender == admin, "Seed: Error 321"); metadata = _metadata; emit MetadataUpdated(_metadata); }
function updateMetadata(bytes memory _metadata) external { require(initialized != true || msg.sender == admin, "Seed: Error 321"); metadata = _metadata; emit MetadataUpdated(_metadata); }
25,838
47
// AlloyxVault Alloyx Vault holds the logic for stakers and investors to interact with different protocols AlloyX /
contract AlloyxVault is IAlloyxVault, AdminUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using ConfigHelper for AlloyxConfig; using SafeMath for uint256; uint256 internal constant DURA_MANTISSA = uint256(10)**uint256(18); uint256 internal constant USDC_MANTISSA = uint256(10)**uint256(6); uint256 internal constant ONE_YEAR_IN_SECONDS = 365.25 days; bool internal locked; uint256 totalAlyxClaimable; uint256 snapshotIdForLiquidation; uint256 preTotalUsdcValue; uint256 preTotalInvestorUsdcValue; uint256 prePermanentStakerGain; uint256 preRegularStakerGain; uint256 lastProtocolFeeTimestamp; State public state; AlloyxConfig public config; IAlloyxVaultToken public vaultToken; Component[] public components; // snapshot=>(investor=>claimed) mapping(uint256 => mapping(address => bool)) internal hasClaimedLiquidationCompensation; event AlloyxConfigUpdated(address indexed who, address configAddress); event SetComponent(address indexed creatorAddress, address poolAddress, uint256 proportion, uint256 tranche, Source source); event SetState(State _state); /** * @notice Ensure there is no reentrant */ modifier nonReentrant() { require(!locked); locked = true; _; locked = false; } /** * @notice If user operation is paused */ modifier isPaused() { require(config.isPaused(), "operations paused"); _; } /** * @notice If operation is not paused */ modifier notPaused() { require(!config.isPaused(), "pause first"); _; } /** * @notice If address is whitelisted */ modifier isWhitelisted() { require(config.getWhitelist().isUserWhitelisted(msg.sender), "not whitelisted"); _; } /** * @notice If the vault is at the right state */ modifier atState(State _state) { require(state == _state, "wrong state"); _; } /** * @notice If the transaction is triggered from manager contract */ modifier onlyManager() { require(msg.sender == config.managerAddress(), "only manager"); _; } /** * @notice Initialize the contract * @param _configAddress the address of configuration contract * @param _vaultTokenAddress the address of vault token contract */ function initialize(address _configAddress, address _vaultTokenAddress) external initializer { __AdminUpgradeable_init(msg.sender); config = AlloyxConfig(_configAddress); vaultToken = IAlloyxVaultToken(_vaultTokenAddress); } /** * @notice Set the state of the vault * @param _state the state of the contract */ function setState(State _state) internal { state = _state; emit SetState(_state); } /** * @notice Get address of the vault token */ function getTokenAddress() external view override returns (address) { return address(vaultToken); } /** * @notice Check if the vault is at certain state * @param _state the state to check */ function isAtState(State _state) internal view returns (bool) { return state == _state; } /** * @notice Update configuration contract address */ function updateConfig() external onlyAdmin isPaused { config = AlloyxConfig(config.configAddress()); emit AlloyxConfigUpdated(msg.sender, address(config)); } /** * @notice Start the vault by setting up the portfolio of the vault and initial depositors' info * @param _components the initial setup of the portfolio for this vault * @param _usdcDepositorArray the array of DepositAmount containing the amount and address of the USDC depositors * @param _alyxDepositorArray the array of DepositAmount containing the amount and address of the ALYX depositors * @param _totalUsdc total amount of USDC to start the vault with */ function startVault( Component[] calldata _components, DepositAmount[] memory _usdcDepositorArray, DepositAmount[] memory _alyxDepositorArray, uint256 _totalUsdc ) external override onlyManager atState(State.INIT) { for (uint256 i = 0; i < _usdcDepositorArray.length; i++) { vaultToken.mint(usdcToAlloyxDura(_usdcDepositorArray[i].amount), _usdcDepositorArray[i].depositor); } for (uint256 i = 0; i < _alyxDepositorArray.length; i++) { permanentlyStake(_alyxDepositorArray[i].depositor, _alyxDepositorArray[i].amount); } preTotalInvestorUsdcValue = _totalUsdc; preTotalUsdcValue = _totalUsdc; lastProtocolFeeTimestamp = block.timestamp; setComponents(_components); setState(State.STARTED); } /** * @notice Reinstate governance called by manager contract only * @param _alyxDepositorArray the array of DepositAmount containing the amount and address of the ALYX depositors */ function reinstateGovernance(DepositAmount[] memory _alyxDepositorArray) external override onlyManager atState(State.NON_GOVERNANCE) { for (uint256 i = 0; i < _alyxDepositorArray.length; i++) { permanentlyStake(_alyxDepositorArray[i].depositor, _alyxDepositorArray[i].amount); } setState(State.STARTED); } /** * @notice Accrue the protocol fee by minting vault tokens to the treasury */ function accrueProtocolFee() external override onlyManager { uint256 totalSupply = vaultToken.totalSupply(); uint256 timeSinceLastFee = block.timestamp.sub(lastProtocolFeeTimestamp); uint256 totalTokenToMint = totalSupply.mul(timeSinceLastFee).mul(config.getInflationPerYearForProtocolFee()).div(10000).div(ONE_YEAR_IN_SECONDS); vaultToken.mint(totalTokenToMint, config.treasuryAddress()); lastProtocolFeeTimestamp = block.timestamp; } /** * @notice Stake certain amount of ALYX as permanent staker, this can only be called internally during starting vault or reinstating governance */ function permanentlyStake(address _account, uint256 _amount) internal { config.getStakeDesk().addPermanentStakeInfo(_account, _amount); } /** * @notice Stake certain amount of ALYX as regular staker, user needs to approve ALYX before calling this */ function stake(uint256 _amount) external isWhitelisted notPaused nonReentrant { _transferERC20From(msg.sender, config.alyxAddress(), address(this), _amount); config.getStakeDesk().addRegularStakeInfo(msg.sender, _amount); } /** * @notice Unstake certain amount of ALYX as regular staker, user needs to approve ALYX before calling this */ function unstake(uint256 _amount) external isWhitelisted notPaused nonReentrant { config.getStakeDesk().subRegularStakeInfo(msg.sender, _amount); _transferERC20(config.alyxAddress(), msg.sender, _amount); } /** * @notice Claim the available USDC and update the checkpoints */ function claim() external isWhitelisted notPaused nonReentrant { updateUsdcValuesAndGains(0, 0); (uint256 regularGain, uint256 permanentGain) = claimable(); _transferERC20(config.usdcAddress(), msg.sender, regularGain.add(permanentGain)); preRegularStakerGain = preRegularStakerGain.sub(regularGain); prePermanentStakerGain = prePermanentStakerGain.sub(permanentGain); preTotalInvestorUsdcValue = preTotalInvestorUsdcValue.sub(regularGain.add(permanentGain)); preTotalUsdcValue = preTotalUsdcValue.sub(regularGain.add(permanentGain)); config.getStakeDesk().clearStakeInfoAfterClaiming(msg.sender); } /** * @notice Claimable USDC for ALYX stakers * @return the claimable USDC for regular staked ALYX * @return the claimable USDC for permanent staked ALYX */ function claimable() public view returns (uint256, uint256) { uint256 totalRegularGain = getRegularStakerGainInVault(); uint256 totalPermanentGain = getPermanentStakerGainInVault(); uint256 regularGain = config.getStakeDesk().getRegularStakerProrataGain(msg.sender, totalRegularGain); uint256 permanentGain = config.getStakeDesk().getPermanentStakerProrataGain(msg.sender, totalPermanentGain); return (regularGain, permanentGain); } /** * @notice Liquidate the vault by unstaking from all permanent and regular stakers and burn all the governance tokens issued */ function liquidate() external override onlyManager atState(State.STARTED) { config.getStakeDesk().unstakeAllStakersAndBurnAllGovTokens(); totalAlyxClaimable = config.getAlyx().balanceOf(address(this)); snapshotIdForLiquidation = vaultToken.snapshot(); setState(State.NON_GOVERNANCE); } /** * @notice Claim liquidation compensation by user who has active investment at the time of liquidation */ function claimLiquidationCompensation() external notPaused { require(snapshotIdForLiquidation > 0, "invalid snapshot id"); uint256 balance = vaultToken.balanceOfAt(msg.sender, snapshotIdForLiquidation); require(balance > 0, "no balance at liquidation"); require(!hasClaimedLiquidationCompensation[snapshotIdForLiquidation][msg.sender], "already claimed"); uint256 supply = vaultToken.totalSupplyAt(snapshotIdForLiquidation); uint256 reward = totalAlyxClaimable.mul(balance).div(supply); _transferERC20(config.alyxAddress(), msg.sender, reward); hasClaimedLiquidationCompensation[snapshotIdForLiquidation][msg.sender] = true; } /** * @notice Update the internal checkpoint of total asset value, asset value for investors, the gains for permanent and regular stakers, and protocol fee * @param _increaseAmount the increase of amount for USDC by deposit * @param _decreaseAmount the decrease of amount for USDC by withdrawal */ function updateUsdcValuesAndGains(uint256 _increaseAmount, uint256 _decreaseAmount) internal { (uint256 totalInvestorUsdcValue, uint256 permanentStakerGain, uint256 regularStakerGain) = getTotalInvestorUsdcValueAndAdditionalGains(); preTotalUsdcValue = config.getOperator().getTotalBalanceInUsdc(address(this)).add(_increaseAmount).sub(_decreaseAmount); preTotalInvestorUsdcValue = totalInvestorUsdcValue.add(_increaseAmount).sub(_decreaseAmount); prePermanentStakerGain = prePermanentStakerGain.add(permanentStakerGain); preRegularStakerGain = preRegularStakerGain.add(regularStakerGain); } /** * @notice A Liquidity Provider can deposit USDC for Alloy Tokens * @param _tokenAmount Number of stable coin */ function deposit(uint256 _tokenAmount) external isWhitelisted notPaused nonReentrant { uint256 amountToMint = usdcToAlloyxDura(_tokenAmount); updateUsdcValuesAndGains(_tokenAmount, 0); _transferERC20From(msg.sender, config.usdcAddress(), address(this), _tokenAmount); vaultToken.mint(amountToMint, msg.sender); } /** * @notice An Alloy token holder can deposit their tokens and redeem them for USDC * @param _tokenAmount Number of Alloy Tokens */ function withdraw(uint256 _tokenAmount) external override isWhitelisted notPaused nonReentrant { uint256 amountToWithdraw = alloyxDuraToUsdc(_tokenAmount); vaultToken.burn(_tokenAmount, msg.sender); updateUsdcValuesAndGains(0, amountToWithdraw); _transferERC20(config.usdcAddress(), msg.sender, amountToWithdraw); } /** * @notice Rebalance the vault by performing deposits to different third party protocols based on the proportion defined */ function rebalance() external onlyAdmin { updateUsdcValuesAndGains(0, 0); uint256 usdcValue = config.getUSDC().balanceOf(address(this)); require(usdcValue > preRegularStakerGain.add(prePermanentStakerGain), "not enough usdc"); uint256 amountToInvest = usdcValue.sub(preRegularStakerGain).sub(prePermanentStakerGain); for (uint256 i = 0; i < components.length; i++) { uint256 additionalInvestment = config.getOperator().getAdditionalDepositAmount( components[i].source, components[i].poolAddress, components[i].tranche, components[i].proportion, preTotalInvestorUsdcValue ); if (additionalInvestment > 0 && amountToInvest > 0) { if (additionalInvestment > amountToInvest) { additionalInvestment = amountToInvest; } performDeposit(components[i].source, components[i].poolAddress, components[i].tranche, additionalInvestment); amountToInvest = amountToInvest.sub(additionalInvestment); if (amountToInvest == 0) { break; } } } } /** * @notice Get the total investor value aka the vault asset value, the additional gain from the last checkpoint for protocol, permanent staker, regular staker * @return the total investor value aka the vault asset value * @return the additional gain from last checkpoint for permanent stakers * @return the additional gain from last checkpoint for regular stakers */ function getTotalInvestorUsdcValueAndAdditionalGains() private view returns ( uint256, uint256, uint256 ) { uint256 totalValue = config.getOperator().getTotalBalanceInUsdc(address(this)); if (totalValue > preTotalUsdcValue) { uint256 interest = totalValue.sub(preTotalUsdcValue); uint256 permanentStakerGain = config.getPermanentStakerProportion().mul(interest).div(10000); uint256 regularStakerGain = config.getRegularStakerProportion().mul(interest).div(10000); uint256 investorGain = interest.sub(permanentStakerGain).sub(regularStakerGain); uint256 totalInvestorUsdcValue = investorGain.add(preTotalInvestorUsdcValue); return (totalInvestorUsdcValue, permanentStakerGain, regularStakerGain); } else { uint256 loss = preTotalUsdcValue.sub(totalValue); uint256 totalInvestorUsdcValue = preTotalInvestorUsdcValue.sub(loss); return (totalInvestorUsdcValue, 0, 0); } } /** * @notice Get the USDC value of the total supply of DURA in this Vault */ function getTotalUsdcValueForDuraInVault() public view returns (uint256) { (uint256 totalInvestorValue, , ) = getTotalInvestorUsdcValueAndAdditionalGains(); return totalInvestorValue; } /** * @notice Get total the regular staker gain */ function getRegularStakerGainInVault() public view returns (uint256) { (, , uint256 regularStakerGain) = getTotalInvestorUsdcValueAndAdditionalGains(); return regularStakerGain.add(preRegularStakerGain); } /** * @notice Get total the permanent staker gain */ function getPermanentStakerGainInVault() public view returns (uint256) { (, uint256 permanentStakerGain, ) = getTotalInvestorUsdcValueAndAdditionalGains(); return permanentStakerGain.add(prePermanentStakerGain); } /** * @notice Set components of the vault * @param _components the components of this vault, including the address of the vault to invest */ function setComponents(Component[] memory _components) public { require(msg.sender == config.managerAddress() || isAdmin(msg.sender), "only manager or admin"); uint256 sumOfProportion = 0; for (uint256 i = 0; i < _components.length; i++) { sumOfProportion += _components[i].proportion; } require(sumOfProportion == 10000, "not equal to 100%"); delete components; for (uint256 i = 0; i < _components.length; i++) { components.push(Component(_components[i].proportion, _components[i].poolAddress, _components[i].tranche, _components[i].source)); emit SetComponent(msg.sender, _components[i].poolAddress, _components[i].proportion, _components[i].tranche, _components[i].source); } } function getComponents() public view returns (Component[] memory) { return components; } /** * @notice Transfer certain amount token of certain address to some other account * @param _account the address to transfer * @param _tokenId the token ID to transfer * @param _tokenAddress the token address to transfer */ function transferERC721( address _tokenAddress, address _account, uint256 _tokenId ) public onlyAdmin { IERC721(_tokenAddress).safeTransferFrom(address(this), _account, _tokenId); } /** * @notice Migrate certain ERC20 to an address * @param _tokenAddress the token address to migrate * @param _to the address to transfer tokens to */ function migrateERC20(address _tokenAddress, address _to) external onlyAdmin { uint256 balance = IERC20Upgradeable(_tokenAddress).balanceOf(address(this)); IERC20Upgradeable(_tokenAddress).safeTransfer(_to, balance); } /** * @notice Convert USDC Amount to Alloyx DURA * @param _amount the amount of usdc to convert to DURA token */ function usdcToAlloyxDura(uint256 _amount) public view returns (uint256) { if (isAtState(State.INIT)) { return _amount.mul(DURA_MANTISSA).div(USDC_MANTISSA); } return _amount.mul(vaultToken.totalSupply()).div(getTotalUsdcValueForDuraInVault()); } /** * @notice Convert Alloyx DURA to USDC amount * @param _amount the amount of DURA token to convert to usdc */ function alloyxDuraToUsdc(uint256 _amount) public view returns (uint256) { if (isAtState(State.INIT)) { return _amount.mul(USDC_MANTISSA).div(DURA_MANTISSA); } return _amount.mul(getTotalUsdcValueForDuraInVault()).div(vaultToken.totalSupply()); } /** * @notice Perform deposit operation to different source * @param _source the source of the third party protocol * @param _poolAddress the pool address of the third party protocol * @param _tranche the tranche to deposit * @param _amount the amount to deposit */ function performDeposit( Source _source, address _poolAddress, uint256 _tranche, uint256 _amount ) public onlyAdmin nonReentrant { _transferERC20(config.usdcAddress(), config.operatorAddress(), _amount); config.getOperator().performDeposit(_source, _poolAddress, _tranche, _amount); } /** * @notice Perform withdrawal operation for different source * @param _source the source of the third party protocol * @param _poolAddress the pool address of the third party protocol * @param _tokenId the token ID * @param _amount the amount to withdraw */ function performWithdraw( Source _source, address _poolAddress, uint256 _tokenId, uint256 _amount, WithdrawalStep _step ) public onlyAdmin nonReentrant { config.getOperator().performWithdraw(_source, _poolAddress, _tokenId, _amount, _step); } /** * @notice Transfer certain amount token of certain address to some other account * @param _account the address to transfer * @param _amount the amount to transfer * @param _tokenAddress the token address to transfer */ function _transferERC20( address _tokenAddress, address _account, uint256 _amount ) internal { IERC20Upgradeable(_tokenAddress).safeTransfer(_account, _amount); } /** * @notice Transfer certain amount token of certain address to some other account * @param _from the address to transfer from * @param _account the address to transfer * @param _amount the amount to transfer * @param _tokenAddress the token address to transfer */ function _transferERC20From( address _from, address _tokenAddress, address _account, uint256 _amount ) internal { IERC20Upgradeable(_tokenAddress).safeTransferFrom(_from, _account, _amount); } }
contract AlloyxVault is IAlloyxVault, AdminUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using ConfigHelper for AlloyxConfig; using SafeMath for uint256; uint256 internal constant DURA_MANTISSA = uint256(10)**uint256(18); uint256 internal constant USDC_MANTISSA = uint256(10)**uint256(6); uint256 internal constant ONE_YEAR_IN_SECONDS = 365.25 days; bool internal locked; uint256 totalAlyxClaimable; uint256 snapshotIdForLiquidation; uint256 preTotalUsdcValue; uint256 preTotalInvestorUsdcValue; uint256 prePermanentStakerGain; uint256 preRegularStakerGain; uint256 lastProtocolFeeTimestamp; State public state; AlloyxConfig public config; IAlloyxVaultToken public vaultToken; Component[] public components; // snapshot=>(investor=>claimed) mapping(uint256 => mapping(address => bool)) internal hasClaimedLiquidationCompensation; event AlloyxConfigUpdated(address indexed who, address configAddress); event SetComponent(address indexed creatorAddress, address poolAddress, uint256 proportion, uint256 tranche, Source source); event SetState(State _state); /** * @notice Ensure there is no reentrant */ modifier nonReentrant() { require(!locked); locked = true; _; locked = false; } /** * @notice If user operation is paused */ modifier isPaused() { require(config.isPaused(), "operations paused"); _; } /** * @notice If operation is not paused */ modifier notPaused() { require(!config.isPaused(), "pause first"); _; } /** * @notice If address is whitelisted */ modifier isWhitelisted() { require(config.getWhitelist().isUserWhitelisted(msg.sender), "not whitelisted"); _; } /** * @notice If the vault is at the right state */ modifier atState(State _state) { require(state == _state, "wrong state"); _; } /** * @notice If the transaction is triggered from manager contract */ modifier onlyManager() { require(msg.sender == config.managerAddress(), "only manager"); _; } /** * @notice Initialize the contract * @param _configAddress the address of configuration contract * @param _vaultTokenAddress the address of vault token contract */ function initialize(address _configAddress, address _vaultTokenAddress) external initializer { __AdminUpgradeable_init(msg.sender); config = AlloyxConfig(_configAddress); vaultToken = IAlloyxVaultToken(_vaultTokenAddress); } /** * @notice Set the state of the vault * @param _state the state of the contract */ function setState(State _state) internal { state = _state; emit SetState(_state); } /** * @notice Get address of the vault token */ function getTokenAddress() external view override returns (address) { return address(vaultToken); } /** * @notice Check if the vault is at certain state * @param _state the state to check */ function isAtState(State _state) internal view returns (bool) { return state == _state; } /** * @notice Update configuration contract address */ function updateConfig() external onlyAdmin isPaused { config = AlloyxConfig(config.configAddress()); emit AlloyxConfigUpdated(msg.sender, address(config)); } /** * @notice Start the vault by setting up the portfolio of the vault and initial depositors' info * @param _components the initial setup of the portfolio for this vault * @param _usdcDepositorArray the array of DepositAmount containing the amount and address of the USDC depositors * @param _alyxDepositorArray the array of DepositAmount containing the amount and address of the ALYX depositors * @param _totalUsdc total amount of USDC to start the vault with */ function startVault( Component[] calldata _components, DepositAmount[] memory _usdcDepositorArray, DepositAmount[] memory _alyxDepositorArray, uint256 _totalUsdc ) external override onlyManager atState(State.INIT) { for (uint256 i = 0; i < _usdcDepositorArray.length; i++) { vaultToken.mint(usdcToAlloyxDura(_usdcDepositorArray[i].amount), _usdcDepositorArray[i].depositor); } for (uint256 i = 0; i < _alyxDepositorArray.length; i++) { permanentlyStake(_alyxDepositorArray[i].depositor, _alyxDepositorArray[i].amount); } preTotalInvestorUsdcValue = _totalUsdc; preTotalUsdcValue = _totalUsdc; lastProtocolFeeTimestamp = block.timestamp; setComponents(_components); setState(State.STARTED); } /** * @notice Reinstate governance called by manager contract only * @param _alyxDepositorArray the array of DepositAmount containing the amount and address of the ALYX depositors */ function reinstateGovernance(DepositAmount[] memory _alyxDepositorArray) external override onlyManager atState(State.NON_GOVERNANCE) { for (uint256 i = 0; i < _alyxDepositorArray.length; i++) { permanentlyStake(_alyxDepositorArray[i].depositor, _alyxDepositorArray[i].amount); } setState(State.STARTED); } /** * @notice Accrue the protocol fee by minting vault tokens to the treasury */ function accrueProtocolFee() external override onlyManager { uint256 totalSupply = vaultToken.totalSupply(); uint256 timeSinceLastFee = block.timestamp.sub(lastProtocolFeeTimestamp); uint256 totalTokenToMint = totalSupply.mul(timeSinceLastFee).mul(config.getInflationPerYearForProtocolFee()).div(10000).div(ONE_YEAR_IN_SECONDS); vaultToken.mint(totalTokenToMint, config.treasuryAddress()); lastProtocolFeeTimestamp = block.timestamp; } /** * @notice Stake certain amount of ALYX as permanent staker, this can only be called internally during starting vault or reinstating governance */ function permanentlyStake(address _account, uint256 _amount) internal { config.getStakeDesk().addPermanentStakeInfo(_account, _amount); } /** * @notice Stake certain amount of ALYX as regular staker, user needs to approve ALYX before calling this */ function stake(uint256 _amount) external isWhitelisted notPaused nonReentrant { _transferERC20From(msg.sender, config.alyxAddress(), address(this), _amount); config.getStakeDesk().addRegularStakeInfo(msg.sender, _amount); } /** * @notice Unstake certain amount of ALYX as regular staker, user needs to approve ALYX before calling this */ function unstake(uint256 _amount) external isWhitelisted notPaused nonReentrant { config.getStakeDesk().subRegularStakeInfo(msg.sender, _amount); _transferERC20(config.alyxAddress(), msg.sender, _amount); } /** * @notice Claim the available USDC and update the checkpoints */ function claim() external isWhitelisted notPaused nonReentrant { updateUsdcValuesAndGains(0, 0); (uint256 regularGain, uint256 permanentGain) = claimable(); _transferERC20(config.usdcAddress(), msg.sender, regularGain.add(permanentGain)); preRegularStakerGain = preRegularStakerGain.sub(regularGain); prePermanentStakerGain = prePermanentStakerGain.sub(permanentGain); preTotalInvestorUsdcValue = preTotalInvestorUsdcValue.sub(regularGain.add(permanentGain)); preTotalUsdcValue = preTotalUsdcValue.sub(regularGain.add(permanentGain)); config.getStakeDesk().clearStakeInfoAfterClaiming(msg.sender); } /** * @notice Claimable USDC for ALYX stakers * @return the claimable USDC for regular staked ALYX * @return the claimable USDC for permanent staked ALYX */ function claimable() public view returns (uint256, uint256) { uint256 totalRegularGain = getRegularStakerGainInVault(); uint256 totalPermanentGain = getPermanentStakerGainInVault(); uint256 regularGain = config.getStakeDesk().getRegularStakerProrataGain(msg.sender, totalRegularGain); uint256 permanentGain = config.getStakeDesk().getPermanentStakerProrataGain(msg.sender, totalPermanentGain); return (regularGain, permanentGain); } /** * @notice Liquidate the vault by unstaking from all permanent and regular stakers and burn all the governance tokens issued */ function liquidate() external override onlyManager atState(State.STARTED) { config.getStakeDesk().unstakeAllStakersAndBurnAllGovTokens(); totalAlyxClaimable = config.getAlyx().balanceOf(address(this)); snapshotIdForLiquidation = vaultToken.snapshot(); setState(State.NON_GOVERNANCE); } /** * @notice Claim liquidation compensation by user who has active investment at the time of liquidation */ function claimLiquidationCompensation() external notPaused { require(snapshotIdForLiquidation > 0, "invalid snapshot id"); uint256 balance = vaultToken.balanceOfAt(msg.sender, snapshotIdForLiquidation); require(balance > 0, "no balance at liquidation"); require(!hasClaimedLiquidationCompensation[snapshotIdForLiquidation][msg.sender], "already claimed"); uint256 supply = vaultToken.totalSupplyAt(snapshotIdForLiquidation); uint256 reward = totalAlyxClaimable.mul(balance).div(supply); _transferERC20(config.alyxAddress(), msg.sender, reward); hasClaimedLiquidationCompensation[snapshotIdForLiquidation][msg.sender] = true; } /** * @notice Update the internal checkpoint of total asset value, asset value for investors, the gains for permanent and regular stakers, and protocol fee * @param _increaseAmount the increase of amount for USDC by deposit * @param _decreaseAmount the decrease of amount for USDC by withdrawal */ function updateUsdcValuesAndGains(uint256 _increaseAmount, uint256 _decreaseAmount) internal { (uint256 totalInvestorUsdcValue, uint256 permanentStakerGain, uint256 regularStakerGain) = getTotalInvestorUsdcValueAndAdditionalGains(); preTotalUsdcValue = config.getOperator().getTotalBalanceInUsdc(address(this)).add(_increaseAmount).sub(_decreaseAmount); preTotalInvestorUsdcValue = totalInvestorUsdcValue.add(_increaseAmount).sub(_decreaseAmount); prePermanentStakerGain = prePermanentStakerGain.add(permanentStakerGain); preRegularStakerGain = preRegularStakerGain.add(regularStakerGain); } /** * @notice A Liquidity Provider can deposit USDC for Alloy Tokens * @param _tokenAmount Number of stable coin */ function deposit(uint256 _tokenAmount) external isWhitelisted notPaused nonReentrant { uint256 amountToMint = usdcToAlloyxDura(_tokenAmount); updateUsdcValuesAndGains(_tokenAmount, 0); _transferERC20From(msg.sender, config.usdcAddress(), address(this), _tokenAmount); vaultToken.mint(amountToMint, msg.sender); } /** * @notice An Alloy token holder can deposit their tokens and redeem them for USDC * @param _tokenAmount Number of Alloy Tokens */ function withdraw(uint256 _tokenAmount) external override isWhitelisted notPaused nonReentrant { uint256 amountToWithdraw = alloyxDuraToUsdc(_tokenAmount); vaultToken.burn(_tokenAmount, msg.sender); updateUsdcValuesAndGains(0, amountToWithdraw); _transferERC20(config.usdcAddress(), msg.sender, amountToWithdraw); } /** * @notice Rebalance the vault by performing deposits to different third party protocols based on the proportion defined */ function rebalance() external onlyAdmin { updateUsdcValuesAndGains(0, 0); uint256 usdcValue = config.getUSDC().balanceOf(address(this)); require(usdcValue > preRegularStakerGain.add(prePermanentStakerGain), "not enough usdc"); uint256 amountToInvest = usdcValue.sub(preRegularStakerGain).sub(prePermanentStakerGain); for (uint256 i = 0; i < components.length; i++) { uint256 additionalInvestment = config.getOperator().getAdditionalDepositAmount( components[i].source, components[i].poolAddress, components[i].tranche, components[i].proportion, preTotalInvestorUsdcValue ); if (additionalInvestment > 0 && amountToInvest > 0) { if (additionalInvestment > amountToInvest) { additionalInvestment = amountToInvest; } performDeposit(components[i].source, components[i].poolAddress, components[i].tranche, additionalInvestment); amountToInvest = amountToInvest.sub(additionalInvestment); if (amountToInvest == 0) { break; } } } } /** * @notice Get the total investor value aka the vault asset value, the additional gain from the last checkpoint for protocol, permanent staker, regular staker * @return the total investor value aka the vault asset value * @return the additional gain from last checkpoint for permanent stakers * @return the additional gain from last checkpoint for regular stakers */ function getTotalInvestorUsdcValueAndAdditionalGains() private view returns ( uint256, uint256, uint256 ) { uint256 totalValue = config.getOperator().getTotalBalanceInUsdc(address(this)); if (totalValue > preTotalUsdcValue) { uint256 interest = totalValue.sub(preTotalUsdcValue); uint256 permanentStakerGain = config.getPermanentStakerProportion().mul(interest).div(10000); uint256 regularStakerGain = config.getRegularStakerProportion().mul(interest).div(10000); uint256 investorGain = interest.sub(permanentStakerGain).sub(regularStakerGain); uint256 totalInvestorUsdcValue = investorGain.add(preTotalInvestorUsdcValue); return (totalInvestorUsdcValue, permanentStakerGain, regularStakerGain); } else { uint256 loss = preTotalUsdcValue.sub(totalValue); uint256 totalInvestorUsdcValue = preTotalInvestorUsdcValue.sub(loss); return (totalInvestorUsdcValue, 0, 0); } } /** * @notice Get the USDC value of the total supply of DURA in this Vault */ function getTotalUsdcValueForDuraInVault() public view returns (uint256) { (uint256 totalInvestorValue, , ) = getTotalInvestorUsdcValueAndAdditionalGains(); return totalInvestorValue; } /** * @notice Get total the regular staker gain */ function getRegularStakerGainInVault() public view returns (uint256) { (, , uint256 regularStakerGain) = getTotalInvestorUsdcValueAndAdditionalGains(); return regularStakerGain.add(preRegularStakerGain); } /** * @notice Get total the permanent staker gain */ function getPermanentStakerGainInVault() public view returns (uint256) { (, uint256 permanentStakerGain, ) = getTotalInvestorUsdcValueAndAdditionalGains(); return permanentStakerGain.add(prePermanentStakerGain); } /** * @notice Set components of the vault * @param _components the components of this vault, including the address of the vault to invest */ function setComponents(Component[] memory _components) public { require(msg.sender == config.managerAddress() || isAdmin(msg.sender), "only manager or admin"); uint256 sumOfProportion = 0; for (uint256 i = 0; i < _components.length; i++) { sumOfProportion += _components[i].proportion; } require(sumOfProportion == 10000, "not equal to 100%"); delete components; for (uint256 i = 0; i < _components.length; i++) { components.push(Component(_components[i].proportion, _components[i].poolAddress, _components[i].tranche, _components[i].source)); emit SetComponent(msg.sender, _components[i].poolAddress, _components[i].proportion, _components[i].tranche, _components[i].source); } } function getComponents() public view returns (Component[] memory) { return components; } /** * @notice Transfer certain amount token of certain address to some other account * @param _account the address to transfer * @param _tokenId the token ID to transfer * @param _tokenAddress the token address to transfer */ function transferERC721( address _tokenAddress, address _account, uint256 _tokenId ) public onlyAdmin { IERC721(_tokenAddress).safeTransferFrom(address(this), _account, _tokenId); } /** * @notice Migrate certain ERC20 to an address * @param _tokenAddress the token address to migrate * @param _to the address to transfer tokens to */ function migrateERC20(address _tokenAddress, address _to) external onlyAdmin { uint256 balance = IERC20Upgradeable(_tokenAddress).balanceOf(address(this)); IERC20Upgradeable(_tokenAddress).safeTransfer(_to, balance); } /** * @notice Convert USDC Amount to Alloyx DURA * @param _amount the amount of usdc to convert to DURA token */ function usdcToAlloyxDura(uint256 _amount) public view returns (uint256) { if (isAtState(State.INIT)) { return _amount.mul(DURA_MANTISSA).div(USDC_MANTISSA); } return _amount.mul(vaultToken.totalSupply()).div(getTotalUsdcValueForDuraInVault()); } /** * @notice Convert Alloyx DURA to USDC amount * @param _amount the amount of DURA token to convert to usdc */ function alloyxDuraToUsdc(uint256 _amount) public view returns (uint256) { if (isAtState(State.INIT)) { return _amount.mul(USDC_MANTISSA).div(DURA_MANTISSA); } return _amount.mul(getTotalUsdcValueForDuraInVault()).div(vaultToken.totalSupply()); } /** * @notice Perform deposit operation to different source * @param _source the source of the third party protocol * @param _poolAddress the pool address of the third party protocol * @param _tranche the tranche to deposit * @param _amount the amount to deposit */ function performDeposit( Source _source, address _poolAddress, uint256 _tranche, uint256 _amount ) public onlyAdmin nonReentrant { _transferERC20(config.usdcAddress(), config.operatorAddress(), _amount); config.getOperator().performDeposit(_source, _poolAddress, _tranche, _amount); } /** * @notice Perform withdrawal operation for different source * @param _source the source of the third party protocol * @param _poolAddress the pool address of the third party protocol * @param _tokenId the token ID * @param _amount the amount to withdraw */ function performWithdraw( Source _source, address _poolAddress, uint256 _tokenId, uint256 _amount, WithdrawalStep _step ) public onlyAdmin nonReentrant { config.getOperator().performWithdraw(_source, _poolAddress, _tokenId, _amount, _step); } /** * @notice Transfer certain amount token of certain address to some other account * @param _account the address to transfer * @param _amount the amount to transfer * @param _tokenAddress the token address to transfer */ function _transferERC20( address _tokenAddress, address _account, uint256 _amount ) internal { IERC20Upgradeable(_tokenAddress).safeTransfer(_account, _amount); } /** * @notice Transfer certain amount token of certain address to some other account * @param _from the address to transfer from * @param _account the address to transfer * @param _amount the amount to transfer * @param _tokenAddress the token address to transfer */ function _transferERC20From( address _from, address _tokenAddress, address _account, uint256 _amount ) internal { IERC20Upgradeable(_tokenAddress).safeTransferFrom(_from, _account, _amount); } }
35,076
5
// The total of Dai deposited on the contract. /
uint256 totalBalance;
uint256 totalBalance;
18,158
119
// multiplies two float values, required since solidity does not handlefloating point valuesreturn uint256 /
function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div( SafeMath.add(SafeMath.mul(a, b), SafeMath.div(1000000000000000000, 2)), 1000000000000000000 ); }
function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div( SafeMath.add(SafeMath.mul(a, b), SafeMath.div(1000000000000000000, 2)), 1000000000000000000 ); }
15,526
2
// If there is already a key for this node and keyID, set the end date and mark it as revoked
uint numKeys = AlaDIDPubkeys[node][keyID].length; if (numKeys > 0) { AlaDIDPubkeys[node][keyID][numKeys-1].endDate = now; AlaDIDPubkeys[node][keyID][numKeys-1].status = Status.RevokedBySubject; }
uint numKeys = AlaDIDPubkeys[node][keyID].length; if (numKeys > 0) { AlaDIDPubkeys[node][keyID][numKeys-1].endDate = now; AlaDIDPubkeys[node][keyID][numKeys-1].status = Status.RevokedBySubject; }
34,152
45
// Decrease bonded stake
del.bondedAmount = del.bondedAmount.sub(penalty);
del.bondedAmount = del.bondedAmount.sub(penalty);
48,748
144
// stores the reserve configuration
ReserveConfigurationMap configuration;
ReserveConfigurationMap configuration;
7,697
216
// prevent further token generation
token.finalize(); tFinalized = now;
token.finalize(); tFinalized = now;
77,312
194
// Includes an account in jackpots/account the account to include
function includeInRaffle(address account) public onlyOwner { require(mappedAddresses[account]._isExcludedFromRaffle, "LuckyToad: Not excluded."); for (uint256 i = 0; i < raffleExclusions.length; i++) { if (raffleExclusions[i] == account) { // Overwrite the array item containing this address with the last array item raffleExclusions[i] = raffleExclusions[raffleExclusions.length - 1]; // Set included mappedAddresses[account]._isExcludedFromRaffle = false; // Delete the last array item raffleExclusions.pop(); break; } } }
function includeInRaffle(address account) public onlyOwner { require(mappedAddresses[account]._isExcludedFromRaffle, "LuckyToad: Not excluded."); for (uint256 i = 0; i < raffleExclusions.length; i++) { if (raffleExclusions[i] == account) { // Overwrite the array item containing this address with the last array item raffleExclusions[i] = raffleExclusions[raffleExclusions.length - 1]; // Set included mappedAddresses[account]._isExcludedFromRaffle = false; // Delete the last array item raffleExclusions.pop(); break; } } }
36,685
38
// Adjusting the last sold and transfer fees
if(_lastSoldFor != lastSoldFor[uint256(_cryptograph)]){ lastSoldFor[uint256(_cryptograph)] = _lastSoldFor; }
if(_lastSoldFor != lastSoldFor[uint256(_cryptograph)]){ lastSoldFor[uint256(_cryptograph)] = _lastSoldFor; }
11,377
61
// function used to safe transfer ERC20 tokens.erc20TokenAddress address of the token to transfer.to receiver of the tokens.value amount of tokens to transfer. /
function _safeTransfer(address erc20TokenAddress, address to, uint256 value) internal virtual { bytes memory returnData = _call(erc20TokenAddress, abi.encodeWithSelector(IERC20(erc20TokenAddress).transfer.selector, to, value)); require(returnData.length == 0 || abi.decode(returnData, (bool)), 'TRANSFER_FAILED'); }
function _safeTransfer(address erc20TokenAddress, address to, uint256 value) internal virtual { bytes memory returnData = _call(erc20TokenAddress, abi.encodeWithSelector(IERC20(erc20TokenAddress).transfer.selector, to, value)); require(returnData.length == 0 || abi.decode(returnData, (bool)), 'TRANSFER_FAILED'); }
50,332
20
// line 302 of Zora Auction House, the auction is deleted at the end of the endAuction() function since we checked that the auction DID exist when we deployed the partyBid, if it no longer exists that means the auction has been finalized.
return !auctionExists(auctionId);
return !auctionExists(auctionId);
42,531
197
// no need to spend the gas to harvest every time; tend is much cheaper
if (tendCounter < tendsPerHarvest) return false;
if (tendCounter < tendsPerHarvest) return false;
51,316
61
// If buyer was a zero address
if (_contract.buyer == address(0)) { address_contract_ids[msg.sender].push(_contract.id); _contract.buyer = msg.sender; }
if (_contract.buyer == address(0)) { address_contract_ids[msg.sender].push(_contract.id); _contract.buyer = msg.sender; }
73,884
24
// Returns an int256 array's element's value for a given key and index key The specified mapping key index The specified index of the desired elementreturn The int256 value at the specified index for the specified array /
function getIntArrayValue(bytes32 key, uint256 index) external view override returns (int256) { return manyInts[key][index]; }
function getIntArrayValue(bytes32 key, uint256 index) external view override returns (int256) { return manyInts[key][index]; }
7,642
32
// Constructor that initializes the contract./_assigner The assigner account./_locker The locker account.
constructor(address _assigner, address _locker) public { require(_assigner != address(0)); require(_locker != address(0)); assigner = _assigner; locker = _locker; }
constructor(address _assigner, address _locker) public { require(_assigner != address(0)); require(_locker != address(0)); assigner = _assigner; locker = _locker; }
27,804
62
// See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721ACommon, ERC2981) returns (bool) { return ERC721ACommon.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId);
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721ACommon, ERC2981) returns (bool) { return ERC721ACommon.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId);
20,413
33
// updates transferability for a given token id (tier) tokenId tokenId for which transferability should be updated transferabledetermines whether tokens from tier should be transferable or not /
function updateTransferableStatus(uint256 tokenId, bool transferable) public onlyOwner isTier(tokenId)
function updateTransferableStatus(uint256 tokenId, bool transferable) public onlyOwner isTier(tokenId)
8,674
245
// RESERVE_ASSET means price comes from quoteAssetReserve/baseAssetReserve INPUT_ASSET means getInput/Output price with snapshot's reserve
if (params.opt == TwapCalcOption.RESERVE_ASSET) { return snapshot.quoteAssetReserve.divD(snapshot.baseAssetReserve); } else if (params.opt == TwapCalcOption.INPUT_ASSET) {
if (params.opt == TwapCalcOption.RESERVE_ASSET) { return snapshot.quoteAssetReserve.divD(snapshot.baseAssetReserve); } else if (params.opt == TwapCalcOption.INPUT_ASSET) {
29,878
18
// Creates a new pool.// The created pool will need to have its reward weight initialized before it begins generating rewards.//_token The token the pool will accept for staking.// return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push(Pool.Data({ token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.uq192x64(0), lastUpdatedBlock: block.number, escrowPercentage: 0, exitFeePercentage: 0 })); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; }
function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push(Pool.Data({ token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.uq192x64(0), lastUpdatedBlock: block.number, escrowPercentage: 0, exitFeePercentage: 0 })); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; }
15,559
16
// Payments were made.principalPaid_ The portion of the total amount that went towards principal.interestPaid_The portion of the total amount that went towards interest.fees_The portion of the total amount that went towards fees. /
event PaymentMade(uint256 principalPaid_, uint256 interestPaid_, uint256 fees_);
event PaymentMade(uint256 principalPaid_, uint256 interestPaid_, uint256 fees_);
11,819
8
// User has custom permission to call method
canCall = guarded.canCall( guarded.guardedMethod.selector, address(user) ); assertTrue(canCall, "User has permission");
canCall = guarded.canCall( guarded.guardedMethod.selector, address(user) ); assertTrue(canCall, "User has permission");
32,989
7
// Return the DOMAIN_SEPARATOR It's named internal to allow making it public from the contract that uses it by creating a simple view function with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); }
function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); }
29,128
47
// solhint-disable no-complex-fallback / To avoid users trying to swap tokens using default payable function. We added this short codeto verify Ethers will be received only from reserves if transferred without a specific function call.
function() public payable { require(isReserve[msg.sender]); EtherReceival(msg.sender, msg.value); }
function() public payable { require(isReserve[msg.sender]); EtherReceival(msg.sender, msg.value); }
37,368
7
// check if hard cap reached before mintting new Tokens
modifier cap_reached(uint amount) { if((_supply + amount) > cap_tmx) revert(); _; }
modifier cap_reached(uint amount) { if((_supply + amount) > cap_tmx) revert(); _; }
817
9
// assigning the caller it's minted newItemId
nftHolders[msg.sender] = newItemId; emit CharacterNFTMinted(msg.sender, newItemId, _characterIndex); console.log( "Minted NFT w/ tokenId %s and characterIndex %s", newItemId, _characterIndex, nftHoldersAttributes[newItemId].imageURI );
nftHolders[msg.sender] = newItemId; emit CharacterNFTMinted(msg.sender, newItemId, _characterIndex); console.log( "Minted NFT w/ tokenId %s and characterIndex %s", newItemId, _characterIndex, nftHoldersAttributes[newItemId].imageURI );
5,477