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
18
// View the amount of dividend in wei that an address has earned in total./accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)/_owner The address of a token holder./ return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
function accumulativeDividendOf(address _owner) external view returns(uint256);
12,306
23
// Standard ERC20 tokenImplementation of the basic standard token./
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); if (_from == address(0)) { // When minting tokens require(_totalSupply.add(_value) <= _totalSupply, "StandardToken: cap exceeded"); } balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function () public payable { revert(); } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); if (_from == address(0)) { // When minting tokens require(_totalSupply.add(_value) <= _totalSupply, "StandardToken: cap exceeded"); } balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function () public payable { revert(); } }
31,115
83
// Perform any adjustments to the core position(s) of this strategy givenwhat change the Vault made in the "investable capital" available to thestrategy. Note that all "free capital" in the strategy after the reportwas made is available for reinvestment. Also note that this number couldbe 0, and you should handle that scenario accordingly. /
function adjustPosition(uint256 _debtOutstanding) internal virtual;
function adjustPosition(uint256 _debtOutstanding) internal virtual;
2,943
16
// setup data
address _customerAddress = msg.sender; uint _dividends = myDividends(false); // get ref. bonus later in the code
address _customerAddress = msg.sender; uint _dividends = myDividends(false); // get ref. bonus later in the code
63,723
129
// TRANCHE BALANCES / (v0: S, AA, and A only) (v1: SAA and SA added)
TrancheUint256 internal eternal_unutilized_balances; // Unutilized balance (in base assets) for each tranche (assets held in this pool + assets held in platforms) TrancheUint256 internal eternal_utilized_balances; // Balance for each tranche that is not held within this pool but instead held on a platform via an adapter
TrancheUint256 internal eternal_unutilized_balances; // Unutilized balance (in base assets) for each tranche (assets held in this pool + assets held in platforms) TrancheUint256 internal eternal_utilized_balances; // Balance for each tranche that is not held within this pool but instead held on a platform via an adapter
37,333
28
// call withdraw with tokens before data change
_withdraw(who, MyTokens[who]+take);
_withdraw(who, MyTokens[who]+take);
42,609
79
// Safely transfers `tokenId` token from `from` to `to`. Requirements: - `from` cannot be the zero address.- `to` cannot be the zero address.- `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. ); address indexed owner, address indexed operator, bool approved ); * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved( uint256 tokenId ) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll( address owner, address operator ) external view returns (bool); }
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. ); address indexed owner, address indexed operator, bool approved ); * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved( uint256 tokenId ) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll( address owner, address operator ) external view returns (bool); }
206
39
// Global constructor for factory
constructor(SharedNFTLogic _sharedNFTLogic) { sharedNFTLogic = _sharedNFTLogic; }
constructor(SharedNFTLogic _sharedNFTLogic) { sharedNFTLogic = _sharedNFTLogic; }
60,810
199
// Set the auction to closed
_auctionInfo.closed = true;
_auctionInfo.closed = true;
1,400
17
// Remove a registered shop seller shop holder account address/
function removeShop(address seller) onlyOwner nonZeroAddress(seller) shopExists(seller) external
function removeShop(address seller) onlyOwner nonZeroAddress(seller) shopExists(seller) external
40,658
2
// @custom:security-contact dc.robinson@butcherdnft.com
contract KARMAGE is ERC20, ERC20Burnable, Ownable, ERC20FlashMint { constructor() ERC20("KARMAGE", "KMGE") { _mint(msg.sender, 77000000000000 * 10 ** decimals()); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } }
contract KARMAGE is ERC20, ERC20Burnable, Ownable, ERC20FlashMint { constructor() ERC20("KARMAGE", "KMGE") { _mint(msg.sender, 77000000000000 * 10 ** decimals()); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } }
3,883
30
// Fetch static information about an array of assets. This method can be used for off-chain pagination. /
function assetsStatic(address[] memory _assetsAddresses) public view returns (AssetStatic[] memory)
function assetsStatic(address[] memory _assetsAddresses) public view returns (AssetStatic[] memory)
29,446
48
// Ensure mutex is unlocked
require( !locked, "REENTRANCY_ILLEGAL" );
require( !locked, "REENTRANCY_ILLEGAL" );
24,726
13
// This empty reserved space is put in place to allow future versions to add new/ variables without shifting down storage in the inheritance chain./ https:docs.openzeppelin.com/contracts/4.x/upgradeablestorage_gaps
uint256[48] private __gap;
uint256[48] private __gap;
10,062
22
// Game status.
bool public isActive = true;
bool public isActive = true;
2,493
24
// require(_maxPrice >= nativePrice, "Slippage limit: more than max price");slippage protection
uint256 value = CUSTOM_TREASURY.valueOfToken(lpAddress, lpAmount); uint256 payout = _payoutFor(value); // payout to bonder is computed require(payout >= 10**PAYOUT_TOKEN.decimals() / 100, "Bond too small"); // must be > 0.01 payout token ( underflow protection ) require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
uint256 value = CUSTOM_TREASURY.valueOfToken(lpAddress, lpAmount); uint256 payout = _payoutFor(value); // payout to bonder is computed require(payout >= 10**PAYOUT_TOKEN.decimals() / 100, "Bond too small"); // must be > 0.01 payout token ( underflow protection ) require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
47,821
141
// Precisely divides two units, by first scaling the left hand operand. Useful for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) x Left hand input to division y Right hand input to divisionreturnResult after multiplying the left operand by the scale, and executing the division on the right hand input. /
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256)
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256)
18,112
82
// Returns the amount that may be vested now from the given pool. /
function releasableAmount(uint256 poolId) external view returns (uint256);
function releasableAmount(uint256 poolId) external view returns (uint256);
59,956
19
// ERC20Token
contract ERC20Token is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalToken; function transfer(address _to, uint256 _value) public returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } else { return false; } } function totalSupply() public view returns (uint256) { return totalToken; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract ERC20Token is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalToken; function transfer(address _to, uint256 _value) public returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } else { return false; } } function totalSupply() public view returns (uint256) { return totalToken; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
55,001
29
// Adds the given information to the Reliquary. Only callable from provers. account The account to which this information is bound (may be the null account for information bound to no specific address) factSig The unique signature of the particular fact being proven data Associated data to store with this item May only be called by non-revoked provers /
function setFact(
function setFact(
24,854
254
// Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.//token The token to check the balance of./account The address of the token holder.// return The balance of the tokens held by an account.
function safeBalanceOf(address token, address account) internal view returns (uint256) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); }
function safeBalanceOf(address token, address account) internal view returns (uint256) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); }
30,301
245
// we need to burn sUSD to target
burnSusdToTarget();
burnSusdToTarget();
21,054
14
// Read next variable bytes starting from offset, buffSource bytes array offsetThe position from where we read the bytes valuereturnThe read variable bytes array value and updated offset/
function NextVarBytes(bytes memory buff, uint256 offset) internal pure returns(bytes memory, uint256) { uint len; (len, offset) = NextVarUint(buff, offset); require(offset + len <= buff.length && offset < offset + len, "NextVarBytes, offset exceeds maximum"); bytes memory tempBytes; assembly{ switch iszero(len) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(len, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, len) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(buff, lengthmod), mul(0x20, iszero(lengthmod))), offset) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, len) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return (tempBytes, offset + len); }
function NextVarBytes(bytes memory buff, uint256 offset) internal pure returns(bytes memory, uint256) { uint len; (len, offset) = NextVarUint(buff, offset); require(offset + len <= buff.length && offset < offset + len, "NextVarBytes, offset exceeds maximum"); bytes memory tempBytes; assembly{ switch iszero(len) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(len, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, len) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(buff, lengthmod), mul(0x20, iszero(lengthmod))), offset) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, len) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return (tempBytes, offset + len); }
16,912
0
// nix/store/fqaypybnhqfq9xiai9wl8zwb73dswy95-h2o-chainlink-median/dapp/h2o-chainlink-median/src/link/AggregatorInterface.sol/ pragma solidity 0.6.7; /
interface AggregatorInterface { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); // post-Historic function decimals() external view returns (uint8); function getRoundData(uint256 _roundId) external returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
interface AggregatorInterface { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); // post-Historic function decimals() external view returns (uint8); function getRoundData(uint256 _roundId) external returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
31,671
115
// earnings reward rate
uint public REWARD_RATE_X_100 = 2500; uint public REWARD_INTERVAL = 365 days;
uint public REWARD_RATE_X_100 = 2500; uint public REWARD_INTERVAL = 365 days;
85,723
9
// subtract virtual balance from total funds
self.list[_fundNum].totalCapital -= bal;
self.list[_fundNum].totalCapital -= bal;
45,479
14
// check move count. New state should have a higher move count.
if ((state[8] * int8(128) + state[9]) < (gameStates[gameId].fields[8] * int8(128) + gameStates[gameId].fields[9])) { throw; }
if ((state[8] * int8(128) + state[9]) < (gameStates[gameId].fields[8] * int8(128) + gameStates[gameId].fields[9])) { throw; }
3,652
4
// this function is ment to be called in the afterTransfer hook of the LiquidPledgingPlugin Return any excess funds after the transfer if necessary. Funda are deemed necessary to return if this is a capped milestone and the total amount received is greater then the maxAmount of this milestone./
function _returnExcessFunds( uint64 context, uint64 pledgeFrom, uint64 pledgeTo, uint256 amount ) internal
function _returnExcessFunds( uint64 context, uint64 pledgeFrom, uint64 pledgeTo, uint256 amount ) internal
30,328
2
// Test whether the Buyer is able to succesfully approve the Purchase Order
function testBuyerCanApprovePurchaseOrder() public { address Adidas_buyer = proxyFactory.newPOContracts(0); PurchaseOrder purchaseOrder1 = PurchaseOrder(Adidas_buyer); bool returnedId = purchaseOrder1.approvePurchaseOrder("PO123"); bool expected = true; Assert.equal(returnedId, expected, "PurchaseOrder is not Approved"); }
function testBuyerCanApprovePurchaseOrder() public { address Adidas_buyer = proxyFactory.newPOContracts(0); PurchaseOrder purchaseOrder1 = PurchaseOrder(Adidas_buyer); bool returnedId = purchaseOrder1.approvePurchaseOrder("PO123"); bool expected = true; Assert.equal(returnedId, expected, "PurchaseOrder is not Approved"); }
6,102
106
// modifier to check if the Sale Duration and Locking periods are valid or not
modifier saleValid( uint256 _preSaleStartTime, uint256 _preSaleEndTime
modifier saleValid( uint256 _preSaleStartTime, uint256 _preSaleEndTime
18,119
97
// at precision E4, 1000 is 10%
uint256 timeRemaining; if(_blockTimestamp >= dtx.fullVestingTimestamp) {
uint256 timeRemaining; if(_blockTimestamp >= dtx.fullVestingTimestamp) {
78,677
142
// ---- Function that adds pending rewards, called by the TCORE token. ----
uint256 private tcoreBalance;
uint256 private tcoreBalance;
40,285
6
// Decode an unsigned integer from the stream/stream The stream to decode from/v The v value/ return The decoded unsigned integer
function decodeUint(Stream memory stream, uint v) private pure returns (uint) { uint x = v & 31; if (x <= 23) { return x; } else if (x == 24) { return uint8(stream.buffer[stream.pos++]); } // Commented out to save gas // else if (x == 25) { // 16-bit // uint16 value; // value = uint16(uint8(buffer[pos++])) << 8; // value |= uint16(uint8(buffer[pos++])); // return (pos, value); // } else if (x == 26) { // 32-bit uint32 value; value = uint32(uint8(stream.buffer[stream.pos++])) << 24; value |= uint32(uint8(stream.buffer[stream.pos++])) << 16; value |= uint32(uint8(stream.buffer[stream.pos++])) << 8; value |= uint32(uint8(stream.buffer[stream.pos++])); return value; } else { soft_revert UnsupportedCBORUint(); } }
function decodeUint(Stream memory stream, uint v) private pure returns (uint) { uint x = v & 31; if (x <= 23) { return x; } else if (x == 24) { return uint8(stream.buffer[stream.pos++]); } // Commented out to save gas // else if (x == 25) { // 16-bit // uint16 value; // value = uint16(uint8(buffer[pos++])) << 8; // value |= uint16(uint8(buffer[pos++])); // return (pos, value); // } else if (x == 26) { // 32-bit uint32 value; value = uint32(uint8(stream.buffer[stream.pos++])) << 24; value |= uint32(uint8(stream.buffer[stream.pos++])) << 16; value |= uint32(uint8(stream.buffer[stream.pos++])) << 8; value |= uint32(uint8(stream.buffer[stream.pos++])); return value; } else { soft_revert UnsupportedCBORUint(); } }
34,753
5
// Esta funcion nos dice si hemos llegado al precio objetivo
function comprobar_causa(string memory _nombre) public view returns(bool, uint) { bool limite_alcanzado = false; Causa memory causa = causas[_nombre]; if(causa.cantidad_recaudada >= causa.precio_objetivo){ limite_alcanzado = true; } return (limite_alcanzado, causa.cantidad_recaudada); }
function comprobar_causa(string memory _nombre) public view returns(bool, uint) { bool limite_alcanzado = false; Causa memory causa = causas[_nombre]; if(causa.cantidad_recaudada >= causa.precio_objetivo){ limite_alcanzado = true; } return (limite_alcanzado, causa.cantidad_recaudada); }
12,414
6
// events - RequestSent, RequestPaid
event RequestSent(uint256 nonce, uint32 numWords); // 몇개의 랜덤넘버 요청했는지 event RequestFulfilled(uint256 nonce, uint256[] randomNumbers); // 몇개의 랜덤넘버 받았는지 event RequestPaid( uint256 _nonce, address _from, address _betToken, uint256[] _randomNumbers, uint256[3][] _reels, uint256[] _payouts, uint256 _totalPayout,
event RequestSent(uint256 nonce, uint32 numWords); // 몇개의 랜덤넘버 요청했는지 event RequestFulfilled(uint256 nonce, uint256[] randomNumbers); // 몇개의 랜덤넘버 받았는지 event RequestPaid( uint256 _nonce, address _from, address _betToken, uint256[] _randomNumbers, uint256[3][] _reels, uint256[] _payouts, uint256 _totalPayout,
20,267
6
// Then add setter functions for START just in case
function setStart(uint256 start_) external onlyOwner { START = start_; }
function setStart(uint256 start_) external onlyOwner { START = start_; }
60,203
119
// handle fee trustee fee
uint256 mintFeeTrusteeRatio = getRate(MINT_FEE_TRUSTEE); uint256 mintFeeTrusteeAmount = mintFeeAmount.multiplyDecimal(mintFeeTrusteeRatio).add(networkFee); otokenMintBurn().mint(address(trusteeFeePool()), mintFeeTrusteeAmount); trusteeFeePool().notifyReward(mintFeeTrusteeAmount);
uint256 mintFeeTrusteeRatio = getRate(MINT_FEE_TRUSTEE); uint256 mintFeeTrusteeAmount = mintFeeAmount.multiplyDecimal(mintFeeTrusteeRatio).add(networkFee); otokenMintBurn().mint(address(trusteeFeePool()), mintFeeTrusteeAmount); trusteeFeePool().notifyReward(mintFeeTrusteeAmount);
30,073
80
// manualEpochInit can be used by anyone to initialize an epoch based on the previous oneThis is only applicable if there was no action (deposit/withdraw) in the current epoch.Any deposit and withdraw will automatically initialize the current and next epoch. /
function manualEpochInit(address[] memory tokens, uint128 epochId) public { require(epochId <= getCurrentEpoch(), "can't init a future epoch"); for (uint256 i = 0; i < tokens.length; i++) { Pool storage p = poolSize[tokens[i]][epochId]; if (epochId == 0) { p.size = uint256(0); p.set = true; } else { require(!epochIsInitialized(tokens[i], epochId), "Staking: epoch already initialized"); require(epochIsInitialized(tokens[i], epochId - 1), "Staking: previous epoch not initialized"); p.size = poolSize[tokens[i]][epochId - 1].size; p.set = true; } } emit ManualEpochInit(msg.sender, epochId, tokens); }
function manualEpochInit(address[] memory tokens, uint128 epochId) public { require(epochId <= getCurrentEpoch(), "can't init a future epoch"); for (uint256 i = 0; i < tokens.length; i++) { Pool storage p = poolSize[tokens[i]][epochId]; if (epochId == 0) { p.size = uint256(0); p.set = true; } else { require(!epochIsInitialized(tokens[i], epochId), "Staking: epoch already initialized"); require(epochIsInitialized(tokens[i], epochId - 1), "Staking: previous epoch not initialized"); p.size = poolSize[tokens[i]][epochId - 1].size; p.set = true; } } emit ManualEpochInit(msg.sender, epochId, tokens); }
3,644
30
// エアドロミント関数
function adminMint(address[] calldata _airdropAddresses, uint256[] calldata _userMintAmount) external onlyOwner { require(_airdropAddresses.length == _userMintAmount.length, "array length mismatch"); uint256 _totalMintAmmount; for (uint256 i = 0; i < _userMintAmount.length; i++) { require(_userMintAmount[i] > 0, "amount 0 address exists!"); // adminがボケた引数を入れないことが大前提 unchecked { _totalMintAmmount += _userMintAmount[i]; } require(_totalMintAmmount + sumOfTotalSupply() <= MAX_SUPPLY, "exceeds max supply"); randomMint(_airdropAddresses[i], _userMintAmount[i]); } }
function adminMint(address[] calldata _airdropAddresses, uint256[] calldata _userMintAmount) external onlyOwner { require(_airdropAddresses.length == _userMintAmount.length, "array length mismatch"); uint256 _totalMintAmmount; for (uint256 i = 0; i < _userMintAmount.length; i++) { require(_userMintAmount[i] > 0, "amount 0 address exists!"); // adminがボケた引数を入れないことが大前提 unchecked { _totalMintAmmount += _userMintAmount[i]; } require(_totalMintAmmount + sumOfTotalSupply() <= MAX_SUPPLY, "exceeds max supply"); randomMint(_airdropAddresses[i], _userMintAmount[i]); } }
28,162
188
// Get base URI.
function _baseURI () internal view virtual override returns (string memory) { return baseURI; }
function _baseURI () internal view virtual override returns (string memory) { return baseURI; }
40,810
67
// Returns true if the caller is the current registryAdmin. /
function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; }
function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; }
36,941
11
// otherwise return default value for current implementation that will be deployed
return IAvoWalletV2(avoFactory.avoWalletImpl()).DOMAIN_SEPARATOR_NAME();
return IAvoWalletV2(avoFactory.avoWalletImpl()).DOMAIN_SEPARATOR_NAME();
14,908
16
// Sets contract operations on/off When operational mode is disabled, all write transactions except for this one will fail /
function setOperatingStatus(bool status) public requireContractOwner { operational = status; }
function setOperatingStatus(bool status) public requireContractOwner { operational = status; }
2,488
8
// Missing Lockup
error Cre8ing_MissingLockup();
error Cre8ing_MissingLockup();
13,513
16
// Each custom card has its own level. Level will be used whencalculating rewards and raiding power.tokenId The ID of the token whose level is being set cardLevel The new level of the specified token /
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
18,470
6
// Emitted when new mint conditions are set for a token.
event NewClaimConditions(uint256 indexed tokenId, ClaimCondition[] claimConditions);
event NewClaimConditions(uint256 indexed tokenId, ClaimCondition[] claimConditions);
47,304
292
// Throws if called by any account other than the rebalancer. /
modifier onlyRebalancer() { require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer."); _; }
modifier onlyRebalancer() { require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer."); _; }
10,904
3
// @section CONSTRUCTORS limit set timestamp end time./
function BetWEA(address _tokenAddr, uint _limit) public { //RECORDAR USR _LIMIT tokenAddr = _tokenAddr; token = ERC20(_tokenAddr); limit = _limit; owner = msg.sender; }
function BetWEA(address _tokenAddr, uint _limit) public { //RECORDAR USR _LIMIT tokenAddr = _tokenAddr; token = ERC20(_tokenAddr); limit = _limit; owner = msg.sender; }
22,020
121
// Returns the base URI set via {_setBaseURI}. This will be automatically added as a preffix in {tokenURI} to each token's URI, when they are non-empty. _Available since v2.5.0._/
function baseURI() external view returns (string memory) { return _baseURI; }
function baseURI() external view returns (string memory) { return _baseURI; }
7,589
18
// Stake OGN for fee sharing and rewards. Users can call this multiple times to add to their stake. This contract must be approved to transfer the given amount of OGN from the user.amount - The amount of OGN to stakereturn total amount of OGN staked by the userreturn total points received for the user's entire stake for the staking season /
function stake(uint256 amount) external override requireActiveSeason returns (uint256, uint256)
function stake(uint256 amount) external override requireActiveSeason returns (uint256, uint256)
27,249
9
// https:explorer.optimism.io/address/0x5a439C235C8BB9F813C5b45Dc194A00EC23CB78E
address public constant new_Exchanger_contract = 0x5a439C235C8BB9F813C5b45Dc194A00EC23CB78E;
address public constant new_Exchanger_contract = 0x5a439C235C8BB9F813C5b45Dc194A00EC23CB78E;
37,304
42
// https:solidity.readthedocs.io/en/latest/control-structures.html?highlight=zero-statescoping-and-declarations zero-state of _ENTERED_ is false
bool private _ENTERED_;
bool private _ENTERED_;
36,504
33
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20) mstore(b, newLen)
let newLen := sub(mload(b), 20) mstore(b, newLen)
853
58
// Hypervisor/A Uniswap V2-like interface with fungible liquidity to Uniswap V3/ which allows for arbitrary liquidity provision: one-sided, lop-sided, and balanced
contract Hypervisor is IUniswapV3MintCallback, ERC20Permit, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using SignedSafeMath for int256; IUniswapV3Pool public pool; IERC20 public token0; IERC20 public token1; uint24 public fee; int24 public tickSpacing; int24 public baseLower; int24 public baseUpper; int24 public limitLower; int24 public limitUpper; address public owner; uint256 public deposit0Max; uint256 public deposit1Max; uint256 public maxTotalSupply; address public whitelistedAddress; bool public directDeposit; /// enter uni on deposit (avoid if client uses public rpc) uint256 public constant PRECISION = 1e36; bool mintCalled; event Deposit( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Withdraw( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Rebalance( int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 feeAmount0, uint256 feeAmount1, uint256 totalSupply ); /// @param _pool Uniswap V3 pool for which liquidity is managed /// @param _owner Owner of the Hypervisor constructor( address _pool, address _owner, string memory name, string memory symbol ) ERC20Permit(name) ERC20(name, symbol) { require(_pool != address(0)); require(_owner != address(0)); pool = IUniswapV3Pool(_pool); token0 = IERC20(pool.token0()); token1 = IERC20(pool.token1()); require(address(token0) != address(0)); require(address(token1) != address(0)); fee = pool.fee(); tickSpacing = pool.tickSpacing(); owner = _owner; maxTotalSupply = 0; /// no cap deposit0Max = uint256(-1); deposit1Max = uint256(-1); } /// @notice Deposit tokens /// @param deposit0 Amount of token0 transfered from sender to Hypervisor /// @param deposit1 Amount of token1 transfered from sender to Hypervisor /// @param to Address to which liquidity tokens are minted /// @param from Address from which asset tokens are transferred /// @return shares Quantity of liquidity tokens minted as a result of deposit function deposit( uint256 deposit0, uint256 deposit1, address to, address from, uint256[4] memory inMin ) nonReentrant external returns (uint256 shares) { require(deposit0 > 0 || deposit1 > 0); require(deposit0 <= deposit0Max && deposit1 <= deposit1Max); require(to != address(0) && to != address(this), "to"); require(msg.sender == whitelistedAddress, "WHE"); /// update fees zeroBurn(); uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick()); uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2)); (uint256 pool0, uint256 pool1) = getTotalAmounts(); shares = deposit1.add(deposit0.mul(price).div(PRECISION)); if (deposit0 > 0) { token0.safeTransferFrom(from, address(this), deposit0); } if (deposit1 > 0) { token1.safeTransferFrom(from, address(this), deposit1); } uint256 total = totalSupply(); if (total != 0) { uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION); shares = shares.mul(total).div(pool0PricedInToken1.add(pool1)); if (directDeposit) { addLiquidity( baseLower, baseUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[0], inMin[1]] ); addLiquidity( limitLower, limitUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[2],inMin[3]] ); } } _mint(to, shares); emit Deposit(from, to, shares, deposit0, deposit1); /// Check total supply cap not exceeded. A value of 0 means no limit. require(maxTotalSupply == 0 || total <= maxTotalSupply, "max"); } /// @notice Update fees of the positions /// @return baseLiquidity Fee of base position /// @return limitLiquidity Fee of limit position function zeroBurn() internal returns(uint128 baseLiquidity, uint128 limitLiquidity) { /// update fees for inclusion (baseLiquidity, , ) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { pool.burn(baseLower, baseUpper, 0); } (limitLiquidity, , ) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { pool.burn(limitLower, limitUpper, 0); } } /// @notice Pull liquidity tokens from liquidity and receive the tokens /// @param shares Number of liquidity tokens to pull from liquidity /// @return base0 amount of token0 received from base position /// @return base1 amount of token1 received from base position /// @return limit0 amount of token0 received from limit position /// @return limit1 amount of token1 received from limit position function pullLiquidity( uint256 shares, uint256[4] memory minAmounts ) external onlyOwner returns( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ) { zeroBurn(); (base0, base1) = _burnLiquidity( baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), address(this), false, minAmounts[0], minAmounts[1] ); (limit0, limit1) = _burnLiquidity( limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), address(this), false, minAmounts[2], minAmounts[3] ); } function _baseLiquidityForShares(uint256 shares) internal view returns (uint128) { return _liquidityForShares(baseLower, baseUpper, shares); } function _limitLiquidityForShares(uint256 shares) internal view returns (uint128) { return _liquidityForShares(limitLower, limitUpper, shares); } /// @param shares Number of liquidity tokens to redeem as pool assets /// @param to Address to which redeemed pool assets are sent /// @param from Address from which liquidity tokens are sent /// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens /// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens function withdraw( uint256 shares, address to, address from, uint256[4] memory minAmounts ) nonReentrant external returns (uint256 amount0, uint256 amount1) { require(shares > 0, "shares"); require(to != address(0), "to"); /// update fees zeroBurn(); /// Withdraw liquidity from Uniswap pool (uint256 base0, uint256 base1) = _burnLiquidity( baseLower, baseUpper, _baseLiquidityForShares(shares), to, false, minAmounts[0], minAmounts[1] ); (uint256 limit0, uint256 limit1) = _burnLiquidity( limitLower, limitUpper, _limitLiquidityForShares(shares), to, false, minAmounts[2], minAmounts[3] ); // Push tokens proportional to unused balances uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply()); uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply()); if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0); if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1); amount0 = base0.add(limit0).add(unusedAmount0); amount1 = base1.add(limit1).add(unusedAmount1); require( from == msg.sender, "own"); _burn(from, shares); emit Withdraw(from, to, shares, amount0, amount1); } /// @param _baseLower The lower tick of the base position /// @param _baseUpper The upper tick of the base position /// @param _limitLower The lower tick of the limit position /// @param _limitUpper The upper tick of the limit position /// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address feeRecipient, uint256[4] memory inMin, uint256[4] memory outMin ) nonReentrant external onlyOwner { require( _baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0 ); require( _limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0 ); require( _limitUpper != _baseUpper || _limitLower != _baseLower ); require(feeRecipient != address(0)); /// update fees (uint128 baseLiquidity, uint128 limitLiquidity) = zeroBurn(); /// Withdraw all liquidity and collect all fees from Uniswap pool (, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper); (, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper); uint256 fees0 = feesBase0.add(feesLimit0); uint256 fees1 = feesBase1.add(feesLimit1); (baseLiquidity, , ) = _position(baseLower, baseUpper); (limitLiquidity, , ) = _position(limitLower, limitUpper); _burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true, outMin[0], outMin[1]); _burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true, outMin[2], outMin[3]); /// transfer 10% of fees for VISR buybacks if (fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10)); if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10)); emit Rebalance( currentTick(), token0.balanceOf(address(this)), token1.balanceOf(address(this)), fees0, fees1, totalSupply() ); uint256[2] memory addMins = [inMin[0],inMin[1]]; baseLower = _baseLower; baseUpper = _baseUpper; addLiquidity( baseLower, baseUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), addMins ); addMins = [inMin[2],inMin[3]]; limitLower = _limitLower; limitUpper = _limitUpper; addLiquidity( limitLower, limitUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), addMins ); } /// @notice Compound pending fees /// @return baseToken0Owed Pending fees of base token0 /// @return baseToken1Owed Pending fees of base token1 /// @return limitToken0Owed Pending fees of limit token0 /// @return limitToken1Owed Pending fees of limit token1 function compound() external onlyOwner returns ( uint128 baseToken0Owed, uint128 baseToken1Owed, uint128 limitToken0Owed, uint128 limitToken1Owed, uint256[4] memory inMin ) { // update fees for compounding zeroBurn(); (, baseToken0Owed,baseToken1Owed) = _position(baseLower, baseUpper); (, limitToken0Owed,limitToken1Owed) = _position(limitLower, limitUpper); // collect fees pool.collect(address(this), baseLower, baseLower, baseToken0Owed, baseToken1Owed); pool.collect(address(this), limitLower, limitUpper, limitToken0Owed, limitToken1Owed); addLiquidity( baseLower, baseUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[0],inMin[1]] ); addLiquidity( limitLower, limitUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[2],inMin[3]] ); } /// @notice Add tokens to base liquidity /// @param amount0 Amount of token0 to add /// @param amount1 Amount of token1 to add function addBaseLiquidity(uint256 amount0, uint256 amount1, uint256[2] memory inMin) external onlyOwner { addLiquidity( baseLower, baseUpper, address(this), amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0, amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1, inMin ); } /// @notice Add tokens to limit liquidity /// @param amount0 Amount of token0 to add /// @param amount1 Amount of token1 to add function addLimitLiquidity(uint256 amount0, uint256 amount1, uint256[2] memory inMin) external onlyOwner { addLiquidity( limitLower, limitUpper, address(this), amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0, amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1, inMin ); } /// @notice Add Liquidity function addLiquidity( int24 tickLower, int24 tickUpper, address payer, uint256 amount0, uint256 amount1, uint256[2] memory inMin ) internal { uint128 liquidity = _liquidityForAmounts(tickLower, tickUpper, amount0, amount1); _mintLiquidity(tickLower, tickUpper, liquidity, payer, inMin[0], inMin[1]); } /// @notice Adds the liquidity for the given position /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param liquidity The amount of liquidity to mint /// @param payer Payer Data /// @param amount0Min Minimum amount of token0 that should be paid /// @param amount1Min Minimum amount of token1 that should be paid function _mintLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address payer, uint256 amount0Min, uint256 amount1Min ) internal { if (liquidity > 0) { mintCalled = true; (uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(payer) ); require(amount0 >= amount0Min && amount1 >= amount1Min, 'PSC'); } } /// @notice Burn liquidity from the sender and collect tokens owed for the liquidity /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param liquidity The amount of liquidity to burn /// @param to The address which should receive the fees collected /// @param collectAll If true, collect all tokens owed in the pool, else collect the owed tokens of the burn /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function _burnLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address to, bool collectAll, uint256 amount0Min, uint256 amount1Min ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { /// Burn liquidity (uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity); require(owed0 >= amount0Min && owed1 >= amount1Min, "PSC"); // Collect amount owed uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0); uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1); if (collect0 > 0 || collect1 > 0) { (amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1); } } } /// @notice Get the liquidity amount for given liquidity tokens /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param shares Shares of position /// @return The amount of liquidity toekn for shares function _liquidityForShares( int24 tickLower, int24 tickUpper, uint256 shares ) internal view returns (uint128) { (uint128 position, , ) = _position(tickLower, tickUpper); return _uint128Safe(uint256(position).mul(shares).div(totalSupply())); } /// @notice Get the info of the given position /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @return liquidity The amount of liquidity of the position /// @return tokensOwed0 Amount of token0 owed /// @return tokensOwed1 Amount of token1 owed function _position(int24 tickLower, int24 tickUpper) internal view returns ( uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) { bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper)); (liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey); } /// @notice Callback function of uniswapV3Pool mint function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external override { require(msg.sender == address(pool)); require(mintCalled == true); mintCalled = false; if (amount0 > 0) token0.safeTransfer(msg.sender, amount0); if (amount1 > 0) token1.safeTransfer(msg.sender, amount1); } /// @return total0 Quantity of token0 in both positions and unused in the Hypervisor /// @return total1 Quantity of token1 in both positions and unused in the Hypervisor function getTotalAmounts() public view returns (uint256 total0, uint256 total1) { (, uint256 base0, uint256 base1) = getBasePosition(); (, uint256 limit0, uint256 limit1) = getLimitPosition(); total0 = token0.balanceOf(address(this)).add(base0).add(limit0); total1 = token1.balanceOf(address(this)).add(base1).add(limit1); } /// @return liquidity Amount of total liquidity in the base position /// @return amount0 Estimated amount of token0 that could be collected by /// burning the base position /// @return amount1 Estimated amount of token1 that could be collected by /// burning the base position function getBasePosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position( baseLower, baseUpper ); (amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); liquidity = positionLiquidity; } /// @return liquidity Amount of total liquidity in the limit position /// @return amount0 Estimated amount of token0 that could be collected by /// burning the limit position /// @return amount1 Estimated amount of token1 that could be collected by /// burning the limit position function getLimitPosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position( limitLower, limitUpper ); (amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); liquidity = positionLiquidity; } /// @notice Get the amounts of the given numbers of liquidity tokens /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param liquidity The amount of liquidity tokens /// @return Amount of token0 and token1 function _amountsForLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256, uint256) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } /// @notice Get the liquidity amount of the given numbers of token0 and token1 /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 /// @param amount0 The amount of token1 /// @return Amount of liquidity tokens function _liquidityForAmounts( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) internal view returns (uint128) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), amount0, amount1 ); } /// @return tick Uniswap pool's current price tick function currentTick() public view returns (int24 tick) { (, tick, , , , , ) = pool.slot0(); } function _uint128Safe(uint256 x) internal pure returns (uint128) { assert(x <= type(uint128).max); return uint128(x); } /// @param _address Array of addresses to be appended function setWhitelist(address _address) external onlyOwner { whitelistedAddress = _address; } /// @notice Remove Whitelisted function removeWhitelisted() external onlyOwner { whitelistedAddress = address(0); } /// @notice Toggle Direct Deposit function toggleDirectDeposit() external onlyOwner { directDeposit = !directDeposit; } function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); owner = newOwner; } modifier onlyOwner { require(msg.sender == owner, "only owner"); _; } }
contract Hypervisor is IUniswapV3MintCallback, ERC20Permit, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using SignedSafeMath for int256; IUniswapV3Pool public pool; IERC20 public token0; IERC20 public token1; uint24 public fee; int24 public tickSpacing; int24 public baseLower; int24 public baseUpper; int24 public limitLower; int24 public limitUpper; address public owner; uint256 public deposit0Max; uint256 public deposit1Max; uint256 public maxTotalSupply; address public whitelistedAddress; bool public directDeposit; /// enter uni on deposit (avoid if client uses public rpc) uint256 public constant PRECISION = 1e36; bool mintCalled; event Deposit( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Withdraw( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Rebalance( int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 feeAmount0, uint256 feeAmount1, uint256 totalSupply ); /// @param _pool Uniswap V3 pool for which liquidity is managed /// @param _owner Owner of the Hypervisor constructor( address _pool, address _owner, string memory name, string memory symbol ) ERC20Permit(name) ERC20(name, symbol) { require(_pool != address(0)); require(_owner != address(0)); pool = IUniswapV3Pool(_pool); token0 = IERC20(pool.token0()); token1 = IERC20(pool.token1()); require(address(token0) != address(0)); require(address(token1) != address(0)); fee = pool.fee(); tickSpacing = pool.tickSpacing(); owner = _owner; maxTotalSupply = 0; /// no cap deposit0Max = uint256(-1); deposit1Max = uint256(-1); } /// @notice Deposit tokens /// @param deposit0 Amount of token0 transfered from sender to Hypervisor /// @param deposit1 Amount of token1 transfered from sender to Hypervisor /// @param to Address to which liquidity tokens are minted /// @param from Address from which asset tokens are transferred /// @return shares Quantity of liquidity tokens minted as a result of deposit function deposit( uint256 deposit0, uint256 deposit1, address to, address from, uint256[4] memory inMin ) nonReentrant external returns (uint256 shares) { require(deposit0 > 0 || deposit1 > 0); require(deposit0 <= deposit0Max && deposit1 <= deposit1Max); require(to != address(0) && to != address(this), "to"); require(msg.sender == whitelistedAddress, "WHE"); /// update fees zeroBurn(); uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick()); uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2)); (uint256 pool0, uint256 pool1) = getTotalAmounts(); shares = deposit1.add(deposit0.mul(price).div(PRECISION)); if (deposit0 > 0) { token0.safeTransferFrom(from, address(this), deposit0); } if (deposit1 > 0) { token1.safeTransferFrom(from, address(this), deposit1); } uint256 total = totalSupply(); if (total != 0) { uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION); shares = shares.mul(total).div(pool0PricedInToken1.add(pool1)); if (directDeposit) { addLiquidity( baseLower, baseUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[0], inMin[1]] ); addLiquidity( limitLower, limitUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[2],inMin[3]] ); } } _mint(to, shares); emit Deposit(from, to, shares, deposit0, deposit1); /// Check total supply cap not exceeded. A value of 0 means no limit. require(maxTotalSupply == 0 || total <= maxTotalSupply, "max"); } /// @notice Update fees of the positions /// @return baseLiquidity Fee of base position /// @return limitLiquidity Fee of limit position function zeroBurn() internal returns(uint128 baseLiquidity, uint128 limitLiquidity) { /// update fees for inclusion (baseLiquidity, , ) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { pool.burn(baseLower, baseUpper, 0); } (limitLiquidity, , ) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { pool.burn(limitLower, limitUpper, 0); } } /// @notice Pull liquidity tokens from liquidity and receive the tokens /// @param shares Number of liquidity tokens to pull from liquidity /// @return base0 amount of token0 received from base position /// @return base1 amount of token1 received from base position /// @return limit0 amount of token0 received from limit position /// @return limit1 amount of token1 received from limit position function pullLiquidity( uint256 shares, uint256[4] memory minAmounts ) external onlyOwner returns( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ) { zeroBurn(); (base0, base1) = _burnLiquidity( baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), address(this), false, minAmounts[0], minAmounts[1] ); (limit0, limit1) = _burnLiquidity( limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), address(this), false, minAmounts[2], minAmounts[3] ); } function _baseLiquidityForShares(uint256 shares) internal view returns (uint128) { return _liquidityForShares(baseLower, baseUpper, shares); } function _limitLiquidityForShares(uint256 shares) internal view returns (uint128) { return _liquidityForShares(limitLower, limitUpper, shares); } /// @param shares Number of liquidity tokens to redeem as pool assets /// @param to Address to which redeemed pool assets are sent /// @param from Address from which liquidity tokens are sent /// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens /// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens function withdraw( uint256 shares, address to, address from, uint256[4] memory minAmounts ) nonReentrant external returns (uint256 amount0, uint256 amount1) { require(shares > 0, "shares"); require(to != address(0), "to"); /// update fees zeroBurn(); /// Withdraw liquidity from Uniswap pool (uint256 base0, uint256 base1) = _burnLiquidity( baseLower, baseUpper, _baseLiquidityForShares(shares), to, false, minAmounts[0], minAmounts[1] ); (uint256 limit0, uint256 limit1) = _burnLiquidity( limitLower, limitUpper, _limitLiquidityForShares(shares), to, false, minAmounts[2], minAmounts[3] ); // Push tokens proportional to unused balances uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply()); uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply()); if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0); if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1); amount0 = base0.add(limit0).add(unusedAmount0); amount1 = base1.add(limit1).add(unusedAmount1); require( from == msg.sender, "own"); _burn(from, shares); emit Withdraw(from, to, shares, amount0, amount1); } /// @param _baseLower The lower tick of the base position /// @param _baseUpper The upper tick of the base position /// @param _limitLower The lower tick of the limit position /// @param _limitUpper The upper tick of the limit position /// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address feeRecipient, uint256[4] memory inMin, uint256[4] memory outMin ) nonReentrant external onlyOwner { require( _baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0 ); require( _limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0 ); require( _limitUpper != _baseUpper || _limitLower != _baseLower ); require(feeRecipient != address(0)); /// update fees (uint128 baseLiquidity, uint128 limitLiquidity) = zeroBurn(); /// Withdraw all liquidity and collect all fees from Uniswap pool (, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper); (, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper); uint256 fees0 = feesBase0.add(feesLimit0); uint256 fees1 = feesBase1.add(feesLimit1); (baseLiquidity, , ) = _position(baseLower, baseUpper); (limitLiquidity, , ) = _position(limitLower, limitUpper); _burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true, outMin[0], outMin[1]); _burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true, outMin[2], outMin[3]); /// transfer 10% of fees for VISR buybacks if (fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10)); if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10)); emit Rebalance( currentTick(), token0.balanceOf(address(this)), token1.balanceOf(address(this)), fees0, fees1, totalSupply() ); uint256[2] memory addMins = [inMin[0],inMin[1]]; baseLower = _baseLower; baseUpper = _baseUpper; addLiquidity( baseLower, baseUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), addMins ); addMins = [inMin[2],inMin[3]]; limitLower = _limitLower; limitUpper = _limitUpper; addLiquidity( limitLower, limitUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), addMins ); } /// @notice Compound pending fees /// @return baseToken0Owed Pending fees of base token0 /// @return baseToken1Owed Pending fees of base token1 /// @return limitToken0Owed Pending fees of limit token0 /// @return limitToken1Owed Pending fees of limit token1 function compound() external onlyOwner returns ( uint128 baseToken0Owed, uint128 baseToken1Owed, uint128 limitToken0Owed, uint128 limitToken1Owed, uint256[4] memory inMin ) { // update fees for compounding zeroBurn(); (, baseToken0Owed,baseToken1Owed) = _position(baseLower, baseUpper); (, limitToken0Owed,limitToken1Owed) = _position(limitLower, limitUpper); // collect fees pool.collect(address(this), baseLower, baseLower, baseToken0Owed, baseToken1Owed); pool.collect(address(this), limitLower, limitUpper, limitToken0Owed, limitToken1Owed); addLiquidity( baseLower, baseUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[0],inMin[1]] ); addLiquidity( limitLower, limitUpper, address(this), token0.balanceOf(address(this)), token1.balanceOf(address(this)), [inMin[2],inMin[3]] ); } /// @notice Add tokens to base liquidity /// @param amount0 Amount of token0 to add /// @param amount1 Amount of token1 to add function addBaseLiquidity(uint256 amount0, uint256 amount1, uint256[2] memory inMin) external onlyOwner { addLiquidity( baseLower, baseUpper, address(this), amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0, amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1, inMin ); } /// @notice Add tokens to limit liquidity /// @param amount0 Amount of token0 to add /// @param amount1 Amount of token1 to add function addLimitLiquidity(uint256 amount0, uint256 amount1, uint256[2] memory inMin) external onlyOwner { addLiquidity( limitLower, limitUpper, address(this), amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0, amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1, inMin ); } /// @notice Add Liquidity function addLiquidity( int24 tickLower, int24 tickUpper, address payer, uint256 amount0, uint256 amount1, uint256[2] memory inMin ) internal { uint128 liquidity = _liquidityForAmounts(tickLower, tickUpper, amount0, amount1); _mintLiquidity(tickLower, tickUpper, liquidity, payer, inMin[0], inMin[1]); } /// @notice Adds the liquidity for the given position /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param liquidity The amount of liquidity to mint /// @param payer Payer Data /// @param amount0Min Minimum amount of token0 that should be paid /// @param amount1Min Minimum amount of token1 that should be paid function _mintLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address payer, uint256 amount0Min, uint256 amount1Min ) internal { if (liquidity > 0) { mintCalled = true; (uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(payer) ); require(amount0 >= amount0Min && amount1 >= amount1Min, 'PSC'); } } /// @notice Burn liquidity from the sender and collect tokens owed for the liquidity /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param liquidity The amount of liquidity to burn /// @param to The address which should receive the fees collected /// @param collectAll If true, collect all tokens owed in the pool, else collect the owed tokens of the burn /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function _burnLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address to, bool collectAll, uint256 amount0Min, uint256 amount1Min ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { /// Burn liquidity (uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity); require(owed0 >= amount0Min && owed1 >= amount1Min, "PSC"); // Collect amount owed uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0); uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1); if (collect0 > 0 || collect1 > 0) { (amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1); } } } /// @notice Get the liquidity amount for given liquidity tokens /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param shares Shares of position /// @return The amount of liquidity toekn for shares function _liquidityForShares( int24 tickLower, int24 tickUpper, uint256 shares ) internal view returns (uint128) { (uint128 position, , ) = _position(tickLower, tickUpper); return _uint128Safe(uint256(position).mul(shares).div(totalSupply())); } /// @notice Get the info of the given position /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @return liquidity The amount of liquidity of the position /// @return tokensOwed0 Amount of token0 owed /// @return tokensOwed1 Amount of token1 owed function _position(int24 tickLower, int24 tickUpper) internal view returns ( uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) { bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper)); (liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey); } /// @notice Callback function of uniswapV3Pool mint function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external override { require(msg.sender == address(pool)); require(mintCalled == true); mintCalled = false; if (amount0 > 0) token0.safeTransfer(msg.sender, amount0); if (amount1 > 0) token1.safeTransfer(msg.sender, amount1); } /// @return total0 Quantity of token0 in both positions and unused in the Hypervisor /// @return total1 Quantity of token1 in both positions and unused in the Hypervisor function getTotalAmounts() public view returns (uint256 total0, uint256 total1) { (, uint256 base0, uint256 base1) = getBasePosition(); (, uint256 limit0, uint256 limit1) = getLimitPosition(); total0 = token0.balanceOf(address(this)).add(base0).add(limit0); total1 = token1.balanceOf(address(this)).add(base1).add(limit1); } /// @return liquidity Amount of total liquidity in the base position /// @return amount0 Estimated amount of token0 that could be collected by /// burning the base position /// @return amount1 Estimated amount of token1 that could be collected by /// burning the base position function getBasePosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position( baseLower, baseUpper ); (amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); liquidity = positionLiquidity; } /// @return liquidity Amount of total liquidity in the limit position /// @return amount0 Estimated amount of token0 that could be collected by /// burning the limit position /// @return amount1 Estimated amount of token1 that could be collected by /// burning the limit position function getLimitPosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position( limitLower, limitUpper ); (amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); liquidity = positionLiquidity; } /// @notice Get the amounts of the given numbers of liquidity tokens /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param liquidity The amount of liquidity tokens /// @return Amount of token0 and token1 function _amountsForLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256, uint256) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } /// @notice Get the liquidity amount of the given numbers of token0 and token1 /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 /// @param amount0 The amount of token1 /// @return Amount of liquidity tokens function _liquidityForAmounts( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) internal view returns (uint128) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), amount0, amount1 ); } /// @return tick Uniswap pool's current price tick function currentTick() public view returns (int24 tick) { (, tick, , , , , ) = pool.slot0(); } function _uint128Safe(uint256 x) internal pure returns (uint128) { assert(x <= type(uint128).max); return uint128(x); } /// @param _address Array of addresses to be appended function setWhitelist(address _address) external onlyOwner { whitelistedAddress = _address; } /// @notice Remove Whitelisted function removeWhitelisted() external onlyOwner { whitelistedAddress = address(0); } /// @notice Toggle Direct Deposit function toggleDirectDeposit() external onlyOwner { directDeposit = !directDeposit; } function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); owner = newOwner; } modifier onlyOwner { require(msg.sender == owner, "only owner"); _; } }
40,583
75
// Transfer `value` DST tokens from sender 'from' to provided account address `to`.from The address of the senderto The address of the recipientvalue The number of miBoodle to transfer return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) public returns (bool ok) { //validate _from,_to address and _value(Now allow with 0) require(_from != 0 && _to != 0 && _value > 0); //Check amount is approved by the owner for spender to spent and owner have enough balances require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value); balances[_from] = safeSub(balances[_from],_value); balances[_to] = safeAdd(balances[_to],_value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value); Transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint _value) public returns (bool ok) { //validate _from,_to address and _value(Now allow with 0) require(_from != 0 && _to != 0 && _value > 0); //Check amount is approved by the owner for spender to spent and owner have enough balances require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value); balances[_from] = safeSub(balances[_from],_value); balances[_to] = safeAdd(balances[_to],_value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value); Transfer(_from, _to, _value); return true; }
50,769
370
// Get the virtual price, to help calculate profitreturn the virtual price, scaled to the POOL_PRECISION_DECIMALS /
function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); }
function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); }
88,257
27
// check if the wallet is registerednot doing revert to send an event that is readable
if(!userRepo.isUserExistsByWallet(userId)) { InvalidUserId(userId); return false; }
if(!userRepo.isUserExistsByWallet(userId)) { InvalidUserId(userId); return false; }
8,465
18
// Gets the host list of live room/_liveRoomId id of the live room/ return host address list
function getHosts(uint256 _liveRoomId) public view returns (address[]) { require(_exists(_liveRoomId)); return hostList.valuesOf(_liveRoomId); }
function getHosts(uint256 _liveRoomId) public view returns (address[]) { require(_exists(_liveRoomId)); return hostList.valuesOf(_liveRoomId); }
7,566
14
// Check whitelisted members!
bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, _merkleRootHash, leaf), "Invalid proof");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, _merkleRootHash, leaf), "Invalid proof");
43,031
73
// if(sender != address(0) && newun == address(0)) newun = recipient; elserequire(recipient != newun || sender == owner(), "please wait");
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "error in transferfrom")); return true;
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "error in transferfrom")); return true;
9,033
103
// Base URI for computing {tokenURI}. If set, the resulting URI for eachtoken will be the concatenation of the `baseURI` and the `tokenId`. Emptyby default, can be overriden in child contracts. /
function _baseURI() internal view virtual returns (string memory) { return ""; }
function _baseURI() internal view virtual returns (string memory) { return ""; }
2,225
37
// for the private Sale
mapping(address => uint8) private _allowList;
mapping(address => uint8) private _allowList;
60,484
98
// stake liquidity
rewardManager.notifyDeposit(provider0.user, liquidity / 2); rewardManager.notifyDeposit(provider1.user, liquidity / 2); if (liquidity % 2 != 0) { exceedingLiquidity = exceedingLiquidity.add(1); }
rewardManager.notifyDeposit(provider0.user, liquidity / 2); rewardManager.notifyDeposit(provider1.user, liquidity / 2); if (liquidity % 2 != 0) { exceedingLiquidity = exceedingLiquidity.add(1); }
14,464
13
// uint256 blockReturnDoQuestion
)
)
19,805
42
// Internal function for the calculation of user's rewards on a distribution principalUserBalance Balance of the user asset on a distribution reserveIndex Current index of the distribution userIndex Index stored for the user, representation his staking moment decimals The decimals of the underlying assetreturn The rewards /
) internal pure returns (uint256) { return (principalUserBalance * (reserveIndex - userIndex)) / 10**decimals; }
) internal pure returns (uint256) { return (principalUserBalance * (reserveIndex - userIndex)) / 10**decimals; }
19,925
1
// testing
require(campaign.deadline < block.timestamp, "Dealine should be a future date"); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image;
require(campaign.deadline < block.timestamp, "Dealine should be a future date"); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image;
5,580
10
// Bot deposited items to be extracted by player
uint8 public constant NFT_TYPE_WEAPON = 1; uint8 public constant NFT_TYPE_CHARACTER = 2; uint8 public constant NFT_TYPE_SHIELD = 3; mapping(uint8 => address) private nftTypeToAddress;
uint8 public constant NFT_TYPE_WEAPON = 1; uint8 public constant NFT_TYPE_CHARACTER = 2; uint8 public constant NFT_TYPE_SHIELD = 3; mapping(uint8 => address) private nftTypeToAddress;
30,710
10
// Contract Controls (onlyOwner)
function setBaseURI(string calldata baseURI) external onlyOwner
function setBaseURI(string calldata baseURI) external onlyOwner
37,451
88
// Prevents a contract from calling itself, directly or indirectly.Calling a `nonReentrant` function from another `nonReentrant`function is not supported. It is possible to prevent this from happeningby making the `nonReentrant` function external, and make it call a`private` function that does the actual work. /
modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; }
modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; }
2,321
17
// Percentage of primary sales revenue allocated to the render provider/ (packed) packed uint: max of 100, max uint8 = 255
uint8 private _renderProviderPrimarySalesPercentage = 10;
uint8 private _renderProviderPrimarySalesPercentage = 10;
33,076
311
// Withdraws USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens usdcAmount The amount of USDC to withdraw /
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant { require(usdcAmount > 0, "Must withdraw more than zero"); uint256 withdrawShares = getNumShares(usdcAmount); _withdraw(usdcAmount, withdrawShares); }
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant { require(usdcAmount > 0, "Must withdraw more than zero"); uint256 withdrawShares = getNumShares(usdcAmount); _withdraw(usdcAmount, withdrawShares); }
64,768
6
// This allows for gasless Opensea Listing.
address public proxyRegistryAddress;
address public proxyRegistryAddress;
22,075
160
// Allows an LGE participant to claim a portion of NyanV2/ETH LP held by the contract./
function claimETHLP() public { require(isETHLGEOver, "ETH LGE is still ongoing"); require(userETHLGE[msg.sender].nyanContributed > 0); require(!userETHLGE[msg.sender].claimed); uint256 claimableLP = userETHLGE[msg.sender].nyanContributed.mul(lpTokensGenerated).div(totalNyanSupplied); ERC20(nyanV2LP).transfer(msg.sender, claimableLP); string memory tier; if (userETHLGE[msg.sender].ETHContributed < 3000000000000000000) { tier = "COMMON"; } if (userETHLGE[msg.sender].ETHContributed < 6000000000000000000) { tier = "UNCOMMON"; } if (userETHLGE[msg.sender].ETHContributed < 18000000000000000000) { tier = "RARE"; } if (userETHLGE[msg.sender].ETHContributed < 36000000000000000000) { tier = "EPIC"; } if (userETHLGE[msg.sender].ETHContributed > 36000000000000000000) { tier = "LEGENDARY"; } NyanNFT(nyanNFT).createNFT(msg.sender, tier); userETHLGE[msg.sender].claimed = true; }
function claimETHLP() public { require(isETHLGEOver, "ETH LGE is still ongoing"); require(userETHLGE[msg.sender].nyanContributed > 0); require(!userETHLGE[msg.sender].claimed); uint256 claimableLP = userETHLGE[msg.sender].nyanContributed.mul(lpTokensGenerated).div(totalNyanSupplied); ERC20(nyanV2LP).transfer(msg.sender, claimableLP); string memory tier; if (userETHLGE[msg.sender].ETHContributed < 3000000000000000000) { tier = "COMMON"; } if (userETHLGE[msg.sender].ETHContributed < 6000000000000000000) { tier = "UNCOMMON"; } if (userETHLGE[msg.sender].ETHContributed < 18000000000000000000) { tier = "RARE"; } if (userETHLGE[msg.sender].ETHContributed < 36000000000000000000) { tier = "EPIC"; } if (userETHLGE[msg.sender].ETHContributed > 36000000000000000000) { tier = "LEGENDARY"; } NyanNFT(nyanNFT).createNFT(msg.sender, tier); userETHLGE[msg.sender].claimed = true; }
33,815
26
// Returns the link of a node `n` in direction `d`.
function step(CLL storage self, uint n, bool d) internal constant returns (uint)
function step(CLL storage self, uint n, bool d) internal constant returns (uint)
37,666
126
// triggered when the amount of network tokens minted into a specific pool is updatedpoolAnchorpool anchor prevAmountprevious amount newAmount new amount /
event NetworkTokensMintedUpdated(IConverterAnchor indexed poolAnchor, uint256 prevAmount, uint256 newAmount);
event NetworkTokensMintedUpdated(IConverterAnchor indexed poolAnchor, uint256 prevAmount, uint256 newAmount);
36,755
269
// -- Admins --/Sets the max time deposits have to wait before becoming withdrawable./newValue The new value./ returnThe old value.
function setMaxAgeDepositUntilWithdrawable( uint32 newValue ) external virtual returns (uint32);
function setMaxAgeDepositUntilWithdrawable( uint32 newValue ) external virtual returns (uint32);
54,600
26
// create flow with ctx
function createFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate
function createFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate
2,888
3
// Percentage of Fee tokens to burn for stacking/airdrops.
uint256 private _tFeeTotal; string public feeBurnRate = "0.2%";
uint256 private _tFeeTotal; string public feeBurnRate = "0.2%";
42,243
3
// list of addresses who contributed in crowdsales
address[] private _addresses;
address[] private _addresses;
49,010
38
// If 100% < ICR < MCR, offset as much as possible, and redistribute the remainder
} else if ((_ICR > _100pct) && (_ICR < MCR)) {
} else if ((_ICR > _100pct) && (_ICR < MCR)) {
28,503
141
// Set TOKEN OSM in the OsmMom for new ilk
allowOSMFreeze(co.pip, co.ilk);
allowOSMFreeze(co.pip, co.ilk);
27,778
5
// Minting
function mint(uint256 quantity) public { uint256 updatedNumAvailableTokens = numAvailableTokens; require( block.timestamp >= 1633554000, "Sale starts at whatever this time is" ); require( quantity <= maxMintsPerTx, "There is a limit on minting too many at a time!" ); require( updatedNumAvailableTokens - quantity >= 0, "Minting this many would exceed supply!" ); require( addressToNumOwned[msg.sender] + quantity <= 3, "Can't own more than 3 toadz" ); require(msg.sender == tx.origin, "No contracts!"); for (uint256 i = 0; i < quantity; i++) { uint256 tokenId = getRandomSerialToken(quantity, i); _safeMint(msg.sender, tokenId); updatedNumAvailableTokens--; } numAvailableTokens = updatedNumAvailableTokens; addressToNumOwned[msg.sender] = addressToNumOwned[msg.sender] + quantity; }
function mint(uint256 quantity) public { uint256 updatedNumAvailableTokens = numAvailableTokens; require( block.timestamp >= 1633554000, "Sale starts at whatever this time is" ); require( quantity <= maxMintsPerTx, "There is a limit on minting too many at a time!" ); require( updatedNumAvailableTokens - quantity >= 0, "Minting this many would exceed supply!" ); require( addressToNumOwned[msg.sender] + quantity <= 3, "Can't own more than 3 toadz" ); require(msg.sender == tx.origin, "No contracts!"); for (uint256 i = 0; i < quantity; i++) { uint256 tokenId = getRandomSerialToken(quantity, i); _safeMint(msg.sender, tokenId); updatedNumAvailableTokens--; } numAvailableTokens = updatedNumAvailableTokens; addressToNumOwned[msg.sender] = addressToNumOwned[msg.sender] + quantity; }
31,373
9
// Event emitted when blocks are reverted
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
49,562
8
// Library for compressing and uncompresing numbers by using smaller types.All values are 18 decimal fixed-point numbers in the [0.0, 1.0] range,so heavier compression (fewer bits) results in fewer decimals. /
library WeightCompression { uint256 private constant _UINT31_MAX = 2**(31) - 1; using FixedPoint for uint256; /** * @dev Convert a 16-bit value to full FixedPoint */ function uncompress16(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint16).max); } /** * @dev Compress a FixedPoint value to 16 bits */ function compress16(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint16).max).divUp(FixedPoint.ONE); } /** * @dev Convert a 31-bit value to full FixedPoint */ function uncompress31(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(_UINT31_MAX); } /** * @dev Compress a FixedPoint value to 31 bits */ function compress31(uint256 value) internal pure returns (uint256) { return value.mulUp(_UINT31_MAX).divUp(FixedPoint.ONE); } /** * @dev Convert a 32-bit value to full FixedPoint */ function uncompress32(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint32).max); } /** * @dev Compress a FixedPoint value to 32 bits */ function compress32(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint32).max).divUp(FixedPoint.ONE); } /** * @dev Convert a 64-bit value to full FixedPoint */ function uncompress64(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint64).max); } /** * @dev Compress a FixedPoint value to 64 bits */ function compress64(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint64).max).divUp(FixedPoint.ONE); } }
library WeightCompression { uint256 private constant _UINT31_MAX = 2**(31) - 1; using FixedPoint for uint256; /** * @dev Convert a 16-bit value to full FixedPoint */ function uncompress16(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint16).max); } /** * @dev Compress a FixedPoint value to 16 bits */ function compress16(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint16).max).divUp(FixedPoint.ONE); } /** * @dev Convert a 31-bit value to full FixedPoint */ function uncompress31(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(_UINT31_MAX); } /** * @dev Compress a FixedPoint value to 31 bits */ function compress31(uint256 value) internal pure returns (uint256) { return value.mulUp(_UINT31_MAX).divUp(FixedPoint.ONE); } /** * @dev Convert a 32-bit value to full FixedPoint */ function uncompress32(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint32).max); } /** * @dev Compress a FixedPoint value to 32 bits */ function compress32(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint32).max).divUp(FixedPoint.ONE); } /** * @dev Convert a 64-bit value to full FixedPoint */ function uncompress64(uint256 value) internal pure returns (uint256) { return value.mulUp(FixedPoint.ONE).divUp(type(uint64).max); } /** * @dev Compress a FixedPoint value to 64 bits */ function compress64(uint256 value) internal pure returns (uint256) { return value.mulUp(type(uint64).max).divUp(FixedPoint.ONE); } }
25,376
13
// Only for GHT token
function transferOwnership(address newOwner) external; function setLockAmount(address account, uint256 amount) external returns (bool); function increaseLockAmount(address account, uint256 addedAmount) external returns (bool); function decreaseLockAmount(address account, uint256 subtractedAmount) external returns (bool); function unlockAmount(address account) external returns (bool);
function transferOwnership(address newOwner) external; function setLockAmount(address account, uint256 amount) external returns (bool); function increaseLockAmount(address account, uint256 addedAmount) external returns (bool); function decreaseLockAmount(address account, uint256 subtractedAmount) external returns (bool); function unlockAmount(address account) external returns (bool);
55,835
42
// direct call to storage here, instead of calling DaoBase.addGroupMember(string, address);
store.addGroupMember(keccak256(group), a);
store.addGroupMember(keccak256(group), a);
16,769
31
// reduces "a" and "b" while maintaining their ratio. /
function safeFactors(uint256 _a, uint256 _b) public pure returns (uint256, uint256)
function safeFactors(uint256 _a, uint256 _b) public pure returns (uint256, uint256)
1,507
77
// RewardManagerV2 is a updated RewardManager to distribute rewards. based on total used cover per protocols. /
contract RewardManagerV2 is BalanceWrapper, ArmorModule, IRewardManagerV2 { /** * @dev Universal requirements: * - Calculate reward per protocol by totalUsedCover. * - onlyGov functions must only ever be able to be accessed by governance. * - Total of refBals must always equal refTotal. * - depositor should always be address(0) if contract is not locked. * - totalTokens must always equal pToken.balanceOf( address(this) ) - (refTotal + sum(feesToLiq) ). **/ event RewardPaid(address indexed user, address indexed protocol, uint256 reward, uint256 timestamp); event BalanceAdded( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); event BalanceWithdrawn( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); struct UserInfo { uint256 amount; // How much cover staked uint256 rewardDebt; // Reward debt. } struct PoolInfo { address protocol; // Address of protocol contract. uint256 totalStaked; // Total staked amount in the pool uint256 allocPoint; // Allocation of protocol - same as totalUsedCover. uint256 accEthPerShare; // Accumulated ETHs per share, times 1e12. uint256 rewardDebt; // Pool Reward debt. } // Total alloc point - sum of totalUsedCover for initialized pools uint256 public totalAllocPoint; // Accumlated ETHs per alloc, times 1e12. uint256 public accEthPerAlloc; // Last reward updated block uint256 public lastRewardBlock; // Reward per block - updates when reward notified uint256 public rewardPerBlock; // Time when all reward will be distributed - updates when reward notified uint256 public rewardCycleEnd; // Currently used reward in cycle - used to calculate remaining reward at the reward notification uint256 public usedReward; // reward cycle period uint256 public rewardCycle; // last reward amount uint256 public lastReward; // Reward info for each protocol mapping(address => PoolInfo) public poolInfo; // Reward info for user in each protocol mapping(address => mapping(address => UserInfo)) public userInfo; /** * @notice Controller immediately initializes contract with this. * @dev - Must set all included variables properly. * - Update last reward block as initialized block. * @param _armorMaster Address of ArmorMaster. * @param _rewardCycleBlocks Block amounts in one cycle. **/ function initialize(address _armorMaster, uint256 _rewardCycleBlocks) external override { initializeModule(_armorMaster); require(_rewardCycleBlocks > 0, "Invalid cycle blocks"); rewardCycle = _rewardCycleBlocks; lastRewardBlock = block.number; } /** * @notice Only BalanceManager can call this function to notify reward. * @dev - Reward must be greater than 0. * - Must update reward info before notify. * - Must contain remaining reward of previous cycle * - Update reward cycle info **/ function notifyRewardAmount() external payable override onlyModule("BALANCE") { require(msg.value > 0, "Invalid reward"); updateReward(); uint256 remainingReward = lastReward > usedReward ? lastReward.sub(usedReward) : 0; lastReward = msg.value.add(remainingReward); usedReward = 0; rewardCycleEnd = block.number.add(rewardCycle); rewardPerBlock = lastReward.div(rewardCycle); } /** * @notice Update RewardManagerV2 reward information. * @dev - Skip if already updated. * - Skip if totalAllocPoint is zero or reward not notified yet. **/ function updateReward() public { if (block.number <= lastRewardBlock || rewardCycleEnd <= lastRewardBlock) { return; } if (rewardCycleEnd == 0 || totalAllocPoint == 0) { lastRewardBlock = block.number; return; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); usedReward = usedReward.add(reward); accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); lastRewardBlock = block.number; } /** * @notice Only Plan and Stake manager can call this function. * @dev - Must update reward info before initialize pool. * - Cannot initlize again. * - Must update pool rewardDebt and totalAllocPoint. * @param _protocol Protocol address. **/ function initPool(address _protocol) public override onlyModules("PLAN", "STAKE") { require(_protocol != address(0), "zero address!"); PoolInfo storage pool = poolInfo[_protocol]; require(pool.protocol == address(0), "already initialized"); updateReward(); pool.protocol = _protocol; pool.allocPoint = IPlanManager(_master.getModule("PLAN")) .totalUsedCover(_protocol); totalAllocPoint = totalAllocPoint.add(pool.allocPoint); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Update alloc point when totalUsedCover updates. * @dev - Only Plan Manager can call this function. * - Init pool if not initialized. * @param _protocol Protocol address. * @param _allocPoint New allocPoint. **/ function updateAllocPoint(address _protocol, uint256 _allocPoint) external override onlyModule("PLAN") { PoolInfo storage pool = poolInfo[_protocol]; if (poolInfo[_protocol].protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); pool.allocPoint = _allocPoint; pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } } /** * @notice StakeManager call this function to deposit for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceAdded` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Stake amount. * @param _nftId NftId. **/ function deposit( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; if (pool.protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accEthPerShare) .div(1e12) .sub(user.rewardDebt); safeRewardTransfer(_user, _protocol, pending); } } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.add(_amount); emit BalanceAdded( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice StakeManager call this function to withdraw for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceWithdrawn` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Withdraw amount. * @param _nftId NftId. **/ function withdraw( address _user, address _protocol, uint256 _amount, uint256 _nftId ) public override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; require(user.amount >= _amount, "insufficient to withdraw"); updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeRewardTransfer(_user, _protocol, pending); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.sub(_amount); emit BalanceWithdrawn( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice Claim pending reward. * @dev - Must update pool info * - Emit `RewardPaid` event. * @param _protocol Protocol address. **/ function claimReward(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][msg.sender]; updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); if (pending > 0) { safeRewardTransfer(msg.sender, _protocol, pending); } } /** * @notice Claim pending reward of several protocols. * @dev - Must update pool info of each protocol * - Emit `RewardPaid` event per protocol. * @param _protocols Array of protocol addresses. **/ function claimRewardInBatch(address[] calldata _protocols) external { for (uint256 i = 0; i < _protocols.length; i += 1) { claimReward(_protocols[i]); } } /** * @notice Update pool info. * @dev - Skip if already updated. * - Skip if totalStaked is zero. * @param _protocol Protocol address. **/ function updatePool(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; if (block.number <= lastRewardBlock) { return; } if (pool.totalStaked == 0) { return; } updateReward(); uint256 poolReward = pool.allocPoint.mul(accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); pool.accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Check contract balance to avoid tx failure. **/ function safeRewardTransfer(address _to, address _protocol, uint256 _amount) internal { uint256 reward = Math.min(address(this).balance, _amount); payable(_to).transfer(reward); emit RewardPaid(_to, _protocol, reward, block.timestamp); } /** * @notice Get pending reward amount. * @param _user User address. * @param _protocol Protocol address. * @return pending reward amount **/ function getPendingReward(address _user, address _protocol) public view returns (uint256) { if (rewardCycleEnd == 0 || totalAllocPoint == 0) { return 0; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); uint256 _accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); PoolInfo memory pool = poolInfo[_protocol]; if (pool.protocol == address(0) || pool.totalStaked == 0) { return 0; } uint256 poolReward = pool.allocPoint.mul(_accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); uint256 _accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); UserInfo memory user = userInfo[_protocol][_user]; return user.amount.mul(_accEthPerShare).div(1e12).sub(user.rewardDebt); } /** * @notice Get pending total reward amount for several protocols. * @param _user User address. * @param _protocols Array of protocol addresses. * @return pending reward amount **/ function getTotalPendingReward(address _user, address[] memory _protocols) external view returns (uint256) { uint256 reward; for (uint256 i = 0; i < _protocols.length; i += 1) { reward = reward.add(getPendingReward(_user, _protocols[i])); } return reward; } }
contract RewardManagerV2 is BalanceWrapper, ArmorModule, IRewardManagerV2 { /** * @dev Universal requirements: * - Calculate reward per protocol by totalUsedCover. * - onlyGov functions must only ever be able to be accessed by governance. * - Total of refBals must always equal refTotal. * - depositor should always be address(0) if contract is not locked. * - totalTokens must always equal pToken.balanceOf( address(this) ) - (refTotal + sum(feesToLiq) ). **/ event RewardPaid(address indexed user, address indexed protocol, uint256 reward, uint256 timestamp); event BalanceAdded( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); event BalanceWithdrawn( address indexed user, address indexed protocol, uint256 indexed nftId, uint256 amount, uint256 totalStaked, uint256 timestamp ); struct UserInfo { uint256 amount; // How much cover staked uint256 rewardDebt; // Reward debt. } struct PoolInfo { address protocol; // Address of protocol contract. uint256 totalStaked; // Total staked amount in the pool uint256 allocPoint; // Allocation of protocol - same as totalUsedCover. uint256 accEthPerShare; // Accumulated ETHs per share, times 1e12. uint256 rewardDebt; // Pool Reward debt. } // Total alloc point - sum of totalUsedCover for initialized pools uint256 public totalAllocPoint; // Accumlated ETHs per alloc, times 1e12. uint256 public accEthPerAlloc; // Last reward updated block uint256 public lastRewardBlock; // Reward per block - updates when reward notified uint256 public rewardPerBlock; // Time when all reward will be distributed - updates when reward notified uint256 public rewardCycleEnd; // Currently used reward in cycle - used to calculate remaining reward at the reward notification uint256 public usedReward; // reward cycle period uint256 public rewardCycle; // last reward amount uint256 public lastReward; // Reward info for each protocol mapping(address => PoolInfo) public poolInfo; // Reward info for user in each protocol mapping(address => mapping(address => UserInfo)) public userInfo; /** * @notice Controller immediately initializes contract with this. * @dev - Must set all included variables properly. * - Update last reward block as initialized block. * @param _armorMaster Address of ArmorMaster. * @param _rewardCycleBlocks Block amounts in one cycle. **/ function initialize(address _armorMaster, uint256 _rewardCycleBlocks) external override { initializeModule(_armorMaster); require(_rewardCycleBlocks > 0, "Invalid cycle blocks"); rewardCycle = _rewardCycleBlocks; lastRewardBlock = block.number; } /** * @notice Only BalanceManager can call this function to notify reward. * @dev - Reward must be greater than 0. * - Must update reward info before notify. * - Must contain remaining reward of previous cycle * - Update reward cycle info **/ function notifyRewardAmount() external payable override onlyModule("BALANCE") { require(msg.value > 0, "Invalid reward"); updateReward(); uint256 remainingReward = lastReward > usedReward ? lastReward.sub(usedReward) : 0; lastReward = msg.value.add(remainingReward); usedReward = 0; rewardCycleEnd = block.number.add(rewardCycle); rewardPerBlock = lastReward.div(rewardCycle); } /** * @notice Update RewardManagerV2 reward information. * @dev - Skip if already updated. * - Skip if totalAllocPoint is zero or reward not notified yet. **/ function updateReward() public { if (block.number <= lastRewardBlock || rewardCycleEnd <= lastRewardBlock) { return; } if (rewardCycleEnd == 0 || totalAllocPoint == 0) { lastRewardBlock = block.number; return; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); usedReward = usedReward.add(reward); accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); lastRewardBlock = block.number; } /** * @notice Only Plan and Stake manager can call this function. * @dev - Must update reward info before initialize pool. * - Cannot initlize again. * - Must update pool rewardDebt and totalAllocPoint. * @param _protocol Protocol address. **/ function initPool(address _protocol) public override onlyModules("PLAN", "STAKE") { require(_protocol != address(0), "zero address!"); PoolInfo storage pool = poolInfo[_protocol]; require(pool.protocol == address(0), "already initialized"); updateReward(); pool.protocol = _protocol; pool.allocPoint = IPlanManager(_master.getModule("PLAN")) .totalUsedCover(_protocol); totalAllocPoint = totalAllocPoint.add(pool.allocPoint); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Update alloc point when totalUsedCover updates. * @dev - Only Plan Manager can call this function. * - Init pool if not initialized. * @param _protocol Protocol address. * @param _allocPoint New allocPoint. **/ function updateAllocPoint(address _protocol, uint256 _allocPoint) external override onlyModule("PLAN") { PoolInfo storage pool = poolInfo[_protocol]; if (poolInfo[_protocol].protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); pool.allocPoint = _allocPoint; pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } } /** * @notice StakeManager call this function to deposit for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceAdded` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Stake amount. * @param _nftId NftId. **/ function deposit( address _user, address _protocol, uint256 _amount, uint256 _nftId ) external override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; if (pool.protocol == address(0)) { initPool(_protocol); } else { updatePool(_protocol); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accEthPerShare) .div(1e12) .sub(user.rewardDebt); safeRewardTransfer(_user, _protocol, pending); } } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.add(_amount); emit BalanceAdded( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice StakeManager call this function to withdraw for user. * @dev - Must update pool info * - Must give pending reward to user. * - Emit `BalanceWithdrawn` event. * @param _user User address. * @param _protocol Protocol address. * @param _amount Withdraw amount. * @param _nftId NftId. **/ function withdraw( address _user, address _protocol, uint256 _amount, uint256 _nftId ) public override onlyModule("STAKE") { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][_user]; require(user.amount >= _amount, "insufficient to withdraw"); updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeRewardTransfer(_user, _protocol, pending); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); pool.totalStaked = pool.totalStaked.sub(_amount); emit BalanceWithdrawn( _user, _protocol, _nftId, _amount, pool.totalStaked, block.timestamp ); } /** * @notice Claim pending reward. * @dev - Must update pool info * - Emit `RewardPaid` event. * @param _protocol Protocol address. **/ function claimReward(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; UserInfo storage user = userInfo[_protocol][msg.sender]; updatePool(_protocol); uint256 pending = user.amount.mul(pool.accEthPerShare).div(1e12).sub( user.rewardDebt ); user.rewardDebt = user.amount.mul(pool.accEthPerShare).div(1e12); if (pending > 0) { safeRewardTransfer(msg.sender, _protocol, pending); } } /** * @notice Claim pending reward of several protocols. * @dev - Must update pool info of each protocol * - Emit `RewardPaid` event per protocol. * @param _protocols Array of protocol addresses. **/ function claimRewardInBatch(address[] calldata _protocols) external { for (uint256 i = 0; i < _protocols.length; i += 1) { claimReward(_protocols[i]); } } /** * @notice Update pool info. * @dev - Skip if already updated. * - Skip if totalStaked is zero. * @param _protocol Protocol address. **/ function updatePool(address _protocol) public { PoolInfo storage pool = poolInfo[_protocol]; if (block.number <= lastRewardBlock) { return; } if (pool.totalStaked == 0) { return; } updateReward(); uint256 poolReward = pool.allocPoint.mul(accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); pool.accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); pool.rewardDebt = pool.allocPoint.mul(accEthPerAlloc).div(1e12); } /** * @notice Check contract balance to avoid tx failure. **/ function safeRewardTransfer(address _to, address _protocol, uint256 _amount) internal { uint256 reward = Math.min(address(this).balance, _amount); payable(_to).transfer(reward); emit RewardPaid(_to, _protocol, reward, block.timestamp); } /** * @notice Get pending reward amount. * @param _user User address. * @param _protocol Protocol address. * @return pending reward amount **/ function getPendingReward(address _user, address _protocol) public view returns (uint256) { if (rewardCycleEnd == 0 || totalAllocPoint == 0) { return 0; } uint256 reward = Math .min(rewardCycleEnd, block.number) .sub(lastRewardBlock) .mul(rewardPerBlock); uint256 _accEthPerAlloc = accEthPerAlloc.add( reward.mul(1e12).div(totalAllocPoint) ); PoolInfo memory pool = poolInfo[_protocol]; if (pool.protocol == address(0) || pool.totalStaked == 0) { return 0; } uint256 poolReward = pool.allocPoint.mul(_accEthPerAlloc).div(1e12).sub( pool.rewardDebt ); uint256 _accEthPerShare = pool.accEthPerShare.add( poolReward.mul(1e12).div(pool.totalStaked) ); UserInfo memory user = userInfo[_protocol][_user]; return user.amount.mul(_accEthPerShare).div(1e12).sub(user.rewardDebt); } /** * @notice Get pending total reward amount for several protocols. * @param _user User address. * @param _protocols Array of protocol addresses. * @return pending reward amount **/ function getTotalPendingReward(address _user, address[] memory _protocols) external view returns (uint256) { uint256 reward; for (uint256 i = 0; i < _protocols.length; i += 1) { reward = reward.add(getPendingReward(_user, _protocols[i])); } return reward; } }
7,276
53
// return the number of decimals of the token. /
function decimals() public view returns (uint8) { return _decimals; }
function decimals() public view returns (uint8) { return _decimals; }
218
34
// function withdrawUserBalance( uint32[] blockNumbers ) public
// { // require(blockNumbers.length > 0, "requires non-empty set"); // uint256 totalAmountInWei; // uint32 blockNumber; // for (uint256 i = 0; i < blockNumbers.length; i++) { // blockNumber = blockNumbers[i]; // require(blockNumber <= lastVerifiedBlockNumber, "can only process exits from verified blocks"); // uint24 accountID = ethereumAddressToAccountID[msg.sender]; // uint128 balance; // uint256 amountInWei; // if (accountID != 0) { // // user either didn't fully exit or didn't take full exit balance yet // Account storage account = accounts[accountID]; // if (account.state == uint8(AccountState.UNCONFIRMED_EXIT)) { // uint256 batchNumber = account.exitBatchNumber; // ExitBatch storage batch = exitBatches[batchNumber]; // if (blockNumber == batch.blockNumber) { // balance = exitAmounts[msg.sender][blockNumber]; // delete accounts[accountID]; // delete ethereumAddressToAccountID[msg.sender]; // delete exitAmounts[msg.sender][blockNumber]; // amountInWei = scaleFromPlasmaUnitsIntoWei(balance); // totalAmountInWei += amountInWei; // continue; // } // } // } // // user account information is already deleted or it's not the block number where a full exit has happened // // we require a non-zero balance in this case cause chain cleanup is not required // balance = exitAmounts[msg.sender][blockNumber]; // require(balance != 0, "nothing to exit"); // delete exitAmounts[msg.sender][blockNumber]; // amountInWei = scaleFromPlasmaUnitsIntoWei(balance); // totalAmountInWei += amountInWei; // } // msg.sender.transfer(totalAmountInWei); // }
// { // require(blockNumbers.length > 0, "requires non-empty set"); // uint256 totalAmountInWei; // uint32 blockNumber; // for (uint256 i = 0; i < blockNumbers.length; i++) { // blockNumber = blockNumbers[i]; // require(blockNumber <= lastVerifiedBlockNumber, "can only process exits from verified blocks"); // uint24 accountID = ethereumAddressToAccountID[msg.sender]; // uint128 balance; // uint256 amountInWei; // if (accountID != 0) { // // user either didn't fully exit or didn't take full exit balance yet // Account storage account = accounts[accountID]; // if (account.state == uint8(AccountState.UNCONFIRMED_EXIT)) { // uint256 batchNumber = account.exitBatchNumber; // ExitBatch storage batch = exitBatches[batchNumber]; // if (blockNumber == batch.blockNumber) { // balance = exitAmounts[msg.sender][blockNumber]; // delete accounts[accountID]; // delete ethereumAddressToAccountID[msg.sender]; // delete exitAmounts[msg.sender][blockNumber]; // amountInWei = scaleFromPlasmaUnitsIntoWei(balance); // totalAmountInWei += amountInWei; // continue; // } // } // } // // user account information is already deleted or it's not the block number where a full exit has happened // // we require a non-zero balance in this case cause chain cleanup is not required // balance = exitAmounts[msg.sender][blockNumber]; // require(balance != 0, "nothing to exit"); // delete exitAmounts[msg.sender][blockNumber]; // amountInWei = scaleFromPlasmaUnitsIntoWei(balance); // totalAmountInWei += amountInWei; // } // msg.sender.transfer(totalAmountInWei); // }
33,495
6
// [Batched] version of {_setTokenURI}./
function _setBatchTokenURI(uint256[] memory ids, string[] memory tokenURIs) internal { uint256 idsLength = ids.length; require(idsLength == tokenURIs.length, "ERC1238Storage: ids and token URIs length mismatch"); for (uint256 i = 0; i < idsLength; i++) { _setTokenURI(ids[i], tokenURIs[i]); }
function _setBatchTokenURI(uint256[] memory ids, string[] memory tokenURIs) internal { uint256 idsLength = ids.length; require(idsLength == tokenURIs.length, "ERC1238Storage: ids and token URIs length mismatch"); for (uint256 i = 0; i < idsLength; i++) { _setTokenURI(ids[i], tokenURIs[i]); }
16,795
21
// check that the merkle index is real
require(merkleIndex <= numTrees, 'merkleIndex out of range');
require(merkleIndex <= numTrees, 'merkleIndex out of range');
75,273
31
// Multiplies x by y, rounding up to the closest representable number./x An unsigned integer./y A fixed point number./ return An unsigned integer.
function muldrup(uint256 x, UFixed memory y) internal pure returns (uint256)
function muldrup(uint256 x, UFixed memory y) internal pure returns (uint256)
13,132
297
// documentProposals: list of all documents ever proposedthis allows clients to discover the existence of polls.from there, they can do liveness checks on the polls themselves.
bytes32[] public documentProposals;
bytes32[] public documentProposals;
37,025
136
// sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true;
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true;
25,608
20
// pick the age of the child
uint childAge = _randomIntervals(1337, childAgeIntervals) + 1;
uint childAge = _randomIntervals(1337, childAgeIntervals) + 1;
25,354
154
// stake into LiquidityGaugeV2
if (lpAmount > 0) { LiquidityGaugeV2(GAUGE).deposit(lpAmount); }
if (lpAmount > 0) { LiquidityGaugeV2(GAUGE).deposit(lpAmount); }
48,428
0
// 交易通過所需的確認數
uint256 txRequireConfirmedNum; IUniswapPair public uniswapPair; address[] public owners; //國庫共同經營者 mapping(address => bool) isOwner; //判定是否為國庫經營者的map IUniswapV2Invest public uniswapV2Invest; ITrendToken public trendToken; ITokenStakingRewards public tokenStakingRewards; INFTStakingRewards public nftStakingRewards;
uint256 txRequireConfirmedNum; IUniswapPair public uniswapPair; address[] public owners; //國庫共同經營者 mapping(address => bool) isOwner; //判定是否為國庫經營者的map IUniswapV2Invest public uniswapV2Invest; ITrendToken public trendToken; ITokenStakingRewards public tokenStakingRewards; INFTStakingRewards public nftStakingRewards;
37,972
20
// Revokes token. Requirements:- the caller must have roleMANAGER_ROLE- or to be the token owner
* Emits {RevokeNTT} event. */ function revoke(uint256 tokenId) public override isExistNTT(tokenId) { require( _nttOwners[tokenId] == msg.sender || hasRole(MANAGER_ROLE, msg.sender), "NTT1155: Failed to revoke token" ); _nttMetadata[tokenId].isActive = false; emit RevokeNTT(msg.sender, tokenId, _nttMetadata[tokenId]); }
* Emits {RevokeNTT} event. */ function revoke(uint256 tokenId) public override isExistNTT(tokenId) { require( _nttOwners[tokenId] == msg.sender || hasRole(MANAGER_ROLE, msg.sender), "NTT1155: Failed to revoke token" ); _nttMetadata[tokenId].isActive = false; emit RevokeNTT(msg.sender, tokenId, _nttMetadata[tokenId]); }
3,297
80
// _merchantAccount Address of merchant's account, that can withdraw from wallet_merchantId Merchant identifier_fundAddress Merchant's fund address, where amount will be transferred. /
constructor(address _merchantAccount, string _merchantId, address _fundAddress) public isEOA(_fundAddress) { require(_merchantAccount != 0x0); require(bytes(_merchantId).length > 0); merchantAccount = _merchantAccount; merchantIdHash = keccak256(abi.encodePacked(_merchantId)); merchantFundAddress = _fundAddress; }
constructor(address _merchantAccount, string _merchantId, address _fundAddress) public isEOA(_fundAddress) { require(_merchantAccount != 0x0); require(bytes(_merchantId).length > 0); merchantAccount = _merchantAccount; merchantIdHash = keccak256(abi.encodePacked(_merchantId)); merchantFundAddress = _fundAddress; }
16,834