// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)pragmasolidity ^0.8.0;import"./IAccessControl.sol";
import"../utils/Context.sol";
import"../utils/Strings.sol";
import"../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/abstractcontractAccessControlisContext, IAccessControl, ERC165{
structRoleData {
mapping(address=>bool) members;
bytes32 adminRole;
}
mapping(bytes32=> RoleData) private _roles;
bytes32publicconstant DEFAULT_ADMIN_ROLE =0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/modifieronlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IAccessControl).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/functionhasRole(bytes32 role, address account) publicviewvirtualoverridereturns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/function_checkRole(bytes32 role) internalviewvirtual{
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/function_checkRole(bytes32 role, address account) internalviewvirtual{
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/functiongetRoleAdmin(bytes32 role) publicviewvirtualoverridereturns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/functiongrantRole(bytes32 role, address account) publicvirtualoverrideonlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/functionrevokeRole(bytes32 role, address account) publicvirtualoverrideonlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/functionrenounceRole(bytes32 role, address account) publicvirtualoverride{
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/function_setupRole(bytes32 role, address account) internalvirtual{
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/function_setRoleAdmin(bytes32 role, bytes32 adminRole) internalvirtual{
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/function_grantRole(bytes32 role, address account) internalvirtual{
if (!hasRole(role, account)) {
_roles[role].members[account] =true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/function_revokeRole(bytes32 role, address account) internalvirtual{
if (hasRole(role, account)) {
_roles[role].members[account] =false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
Contract Source Code
File 2 of 17: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 3 of 17: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 4 of 17: ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity >=0.8.0;/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation./// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.abstractcontractERC20{
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventTransfer(addressindexedfrom, addressindexed to, uint256 amount);
eventApproval(addressindexed owner, addressindexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/stringpublic name;
stringpublic symbol;
uint8publicimmutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/uint256public totalSupply;
mapping(address=>uint256) public balanceOf;
mapping(address=>mapping(address=>uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/uint256internalimmutable INITIAL_CHAIN_ID;
bytes32internalimmutable INITIAL_DOMAIN_SEPARATOR;
mapping(address=>uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/constructor(stringmemory _name,
stringmemory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID =block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/functionapprove(address spender, uint256 amount) publicvirtualreturns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
returntrue;
}
functiontransfer(address to, uint256 amount) publicvirtualreturns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
returntrue;
}
functiontransferFrom(addressfrom,
address to,
uint256 amount
) publicvirtualreturns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.if (allowed !=type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
returntrue;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtual{
require(deadline >=block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing// the owner's nonce which cannot realistically overflow.unchecked {
address recoveredAddress =ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress !=address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
functionDOMAIN_SEPARATOR() publicviewvirtualreturns (bytes32) {
returnblock.chainid== INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
functioncomputeDomainSeparator() internalviewvirtualreturns (bytes32) {
returnkeccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/function_mint(address to, uint256 amount) internalvirtual{
totalSupply += amount;
// Cannot overflow because the sum of all user// balances can't exceed the max uint256 value.unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function_burn(addressfrom, uint256 amount) internalvirtual{
balanceOf[from] -= amount;
// Cannot underflow because a user's balance// will never be larger than the total supply.unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
Contract Source Code
File 5 of 17: IAccessControl.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)pragmasolidity ^0.8.0;/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/interfaceIAccessControl{
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/eventRoleAdminChanged(bytes32indexed role, bytes32indexed previousAdminRole, bytes32indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/eventRoleGranted(bytes32indexed role, addressindexed account, addressindexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/eventRoleRevoked(bytes32indexed role, addressindexed account, addressindexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/functionhasRole(bytes32 role, address account) externalviewreturns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/functiongetRoleAdmin(bytes32 role) externalviewreturns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functiongrantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functionrevokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/functionrenounceRole(bytes32 role, address account) external;
}
Contract Source Code
File 6 of 17: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)pragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
enumRounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/functionaverage(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b) / 2 can overflow.return (a & b) + (a ^ b) /2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/functionceilDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.return a ==0 ? 0 : (a -1) / b +1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator) internalpurereturns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256// variables such that product = prod1 * 2^256 + prod0.uint256 prod0; // Least significant 256 bits of the productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(x, y, not(0))
prod0 :=mul(x, y)
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.if (prod1 ==0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.// The surrounding unchecked block does not change this fact.// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////// 512 by 256 division.///////////////////////////////////////////////// Make division exact by subtracting the remainder from [prod1 prod0].uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder :=mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 :=sub(prod1, gt(remainder, prod0))
prod0 :=sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.// See https://cs.stackexchange.com/q/138556/92363.// Does not overflow because the denominator cannot be zero at this stage in the function.uint256 twos = denominator & (~denominator +1);
assembly {
// Divide denominator by twos.
denominator :=div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 :=div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos :=add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for// four bits. That is, denominator * inv = 1 mod 2^4.uint256 inverse = (3* denominator) ^2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works// in modular arithmetic, doubling the correct bits in each step.
inverse *=2- denominator * inverse; // inverse mod 2^8
inverse *=2- denominator * inverse; // inverse mod 2^16
inverse *=2- denominator * inverse; // inverse mod 2^32
inverse *=2- denominator * inverse; // inverse mod 2^64
inverse *=2- denominator * inverse; // inverse mod 2^128
inverse *=2- denominator * inverse; // inverse mod 2^256// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internalpurereturns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up &&mulmod(x, y, denominator) >0) {
result +=1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/functionsqrt(uint256 a) internalpurereturns (uint256) {
if (a ==0) {
return0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.//// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.//// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`//// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.uint256 result =1<< (log2(a) >>1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision// into the expected uint128 result.unchecked {
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/functionsqrt(uint256 a, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=128;
}
if (value >>64>0) {
value >>=64;
result +=64;
}
if (value >>32>0) {
value >>=32;
result +=32;
}
if (value >>16>0) {
value >>=16;
result +=16;
}
if (value >>8>0) {
value >>=8;
result +=8;
}
if (value >>4>0) {
value >>=4;
result +=4;
}
if (value >>2>0) {
value >>=2;
result +=2;
}
if (value >>1>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result =log2(value);
return result + (rounding == Rounding.Up &&1<< result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >=10**64) {
value /=10**64;
result +=64;
}
if (value >=10**32) {
value /=10**32;
result +=32;
}
if (value >=10**16) {
value /=10**16;
result +=16;
}
if (value >=10**8) {
value /=10**8;
result +=8;
}
if (value >=10**4) {
value /=10**4;
result +=4;
}
if (value >=10**2) {
value /=10**2;
result +=2;
}
if (value >=10**1) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up &&10** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/functionlog256(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=16;
}
if (value >>64>0) {
value >>=64;
result +=8;
}
if (value >>32>0) {
value >>=32;
result +=4;
}
if (value >>16>0) {
value >>=16;
result +=2;
}
if (value >>8>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog256(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up &&1<< (result <<3) < value ? 1 : 0);
}
}
}
Contract Source Code
File 15 of 17: OptionTokenV3.sol
// SPDX-License-Identifier: AGPL-3.0pragmasolidity 0.8.13;import {AccessControl} from"openzeppelin-contracts/contracts/access/AccessControl.sol";
import {SignedMath} from"openzeppelin-contracts/contracts/utils/math/SignedMath.sol";
import {ERC20} from"solmate/tokens/ERC20.sol";
import {IERC20} from"./interfaces/IERC20.sol";
import {IFlow} from"./interfaces/IFlow.sol";
import {IGaugeV2} from"./interfaces/IGaugeV2.sol";
import {IVoter} from"./interfaces/IVoter.sol";
import {IVotingEscrow} from"./interfaces/IVotingEscrow.sol";
import {IPair} from"./interfaces/IPair.sol";
import {IRouter} from"./interfaces/IRouter.sol";
/// @title Option Token/// @notice Option token representing the right to purchase the underlying token/// at TWAP reduced rate. Similar to call options but with a variable strike/// price that's always at a certain discount to the market price./// @dev Assumes the underlying token and the payment token both use 18 decimals and revert on// failure to transfer.contractOptionTokenV3isERC20, AccessControl{
/// -----------------------------------------------------------------------/// Constants/// -----------------------------------------------------------------------uint256publicconstant MAX_DISCOUNT =100; // 100%uint256publicconstant MIN_DISCOUNT =0; // 0%uint256publicconstant MAX_TWAP_POINTS =50; // 25 hoursuint256publicconstant FULL_LOCK =52*7*86400; // 52 weeksuint256publicconstant MAX_FEES =50; // 50%/// -----------------------------------------------------------------------/// Roles/// -----------------------------------------------------------------------/// @dev The identifier of the role which maintains other roles and settingsbytes32publicconstant ADMIN_ROLE =keccak256("ADMIN");
/// @dev The identifier of the role which is allowed to mint options tokenbytes32publicconstant MINTER_ROLE =keccak256("MINTER");
/// @dev The identifier of the role which allows accounts to pause execrcising options/// in case of emergencybytes32publicconstant PAUSER_ROLE =keccak256("PAUSER");
/// -----------------------------------------------------------------------/// Errors/// -----------------------------------------------------------------------errorOptionToken_PastDeadline();
errorOptionToken_NoAdminRole();
errorOptionToken_NoMinterRole();
errorOptionToken_NoPauserRole();
errorOptionToken_SlippageTooHigh();
errorOptionToken_InvalidDiscount();
errorOptionToken_InvalidLockDuration();
errorOptionToken_InvalidFee();
errorOptionToken_Paused();
errorOptionToken_InvalidTwapPoints();
errorOptionToken_IncorrectPairToken();
/// -----------------------------------------------------------------------/// Events/// -----------------------------------------------------------------------eventExercise(addressindexed sender,
addressindexed recipient,
uint256 amount,
uint256 paymentAmount
);
eventExerciseVe(addressindexed sender,
addressindexed recipient,
uint256 amount,
uint256 paymentAmount,
uint256 nftId
);
eventExerciseLp(addressindexed sender,
addressindexed recipient,
uint256 amount,
uint256 paymentAmount,
uint256 lpAmount
);
eventSetPairAndPaymentToken(
IPair indexed newPair,
addressindexed newPaymentToken
);
eventSetGauge(addressindexed newGauge);
eventSetTreasury(addressindexed newTreasury,addressindexed newVMTreasury);
eventSetFees(uint256 newTeamFee,uint256 newVMFee);
eventSetRouter(addressindexed newRouter);
eventSetDiscount(uint256 discount);
eventSetVeDiscount(uint256 veDiscount);
eventSetMinLPDiscount(uint256 lpMinDiscount);
eventSetMaxLPDiscount(uint256 lpMaxDiscount);
eventSetLockDurationForMaxLpDiscount(uint256 lockDurationForMaxLpDiscount);
eventSetLockDurationForMinLpDiscount(uint256 lockDurationForMinLpDiscount);
eventPauseStateChanged(bool isPaused);
eventSetTwapPoints(uint256 twapPoints);
/// -----------------------------------------------------------------------/// Immutable parameters/// -----------------------------------------------------------------------/// @notice The token paid by the options token holder during redemptionaddresspublic paymentToken;
/// @notice The underlying token purchased during redemptionaddresspublicimmutable underlyingToken;
/// @notice The voting escrow for locking FLOW to veFLOWaddresspublicimmutable votingEscrow;
/// @notice The voter contractaddresspublicimmutable voter;
/// -----------------------------------------------------------------------/// Storage variables/// -----------------------------------------------------------------------/// @notice The router for adding liquidityaddresspublic router; // this should not be immutable/// @notice The pair contract that provides the current TWAP price to purchase/// the underlying token while exercising options (the strike price)
IPair public pair;
/// @notice The guage contract for the pairaddresspublic gauge;
/// @notice The treasury address which receives tokens paid during redemptionaddresspublic treasury;
/// @notice The VM address which receives tokens paid during redemptionaddresspublic vmTreasury;
/// @notice the discount given during exercising with locking to the LPuint256public maxLPDiscount =20; // User pays 20%uint256public minLPDiscount =80; // User pays 80%/// @notice the discount given during exercising. 30 = user pays 30%uint256public discount =99; // User pays 90%/// @notice the discount for locking to veFLOWuint256public veDiscount =10; // User pays 10%/// @notice the lock duration for max discount to create locked LPuint256public lockDurationForMaxLpDiscount = FULL_LOCK; // 52 weeks// @notice the lock duration for max discount to create locked LPuint256public lockDurationForMinLpDiscount =7*86400; // 1 week/// @noticeuint256public teamFee =5; // 5%/// @noticeuint256public vmFee =5; // 5%/// @notice controls the duration of the twap used to calculate the strike price// each point represents 30 minutes. 4 points = 2 hoursuint256public twapPoints =4;
/// @notice Is excersizing options currently pausedboolpublic isPaused;
/// -----------------------------------------------------------------------/// Modifiers/// -----------------------------------------------------------------------/// @dev A modifier which checks that the caller has the admin role.modifieronlyAdmin() {
if (!hasRole(ADMIN_ROLE, msg.sender)) revert OptionToken_NoAdminRole();
_;
}
/// @dev A modifier which checks that the caller has the admin role.modifieronlyMinter() {
if (
!hasRole(ADMIN_ROLE, msg.sender) &&!hasRole(MINTER_ROLE, msg.sender)
) revert OptionToken_NoMinterRole();
_;
}
/// @dev A modifier which checks that the caller has the pause role.modifieronlyPauser() {
if (!hasRole(PAUSER_ROLE, msg.sender))
revert OptionToken_NoPauserRole();
_;
}
/// -----------------------------------------------------------------------/// Constructor/// -----------------------------------------------------------------------constructor(stringmemory _name,
stringmemory _symbol,
address _admin,
address _paymentToken,
address _underlyingToken,
IPair _pair,
address _gaugeFactory,
address _treasury,
address _voter,
address _votingEscrow,
address _router
) ERC20(_name, _symbol, 18) {
_grantRole(ADMIN_ROLE, _admin);
_grantRole(PAUSER_ROLE, _admin);
_grantRole(ADMIN_ROLE, _gaugeFactory);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setRoleAdmin(MINTER_ROLE, ADMIN_ROLE);
_setRoleAdmin(PAUSER_ROLE, ADMIN_ROLE);
paymentToken = _paymentToken;
underlyingToken = _underlyingToken;
pair = _pair;
treasury = _treasury;
vmTreasury = _treasury;
voter = _voter;
votingEscrow = _votingEscrow;
router = _router;
emit SetPairAndPaymentToken(_pair, paymentToken);
emit SetTreasury(_treasury,_treasury);
emit SetRouter(_router);
}
/// -----------------------------------------------------------------------/// External functions/// -----------------------------------------------------------------------/// @notice Exercises options tokens to purchase the underlying tokens./// @dev The oracle may revert if it cannot give a secure result./// @param _amount The amount of options tokens to exercise/// @param _maxPaymentAmount The maximum acceptable amount to pay. Used for slippage protection./// @param _recipient The recipient of the purchased underlying tokens/// @return The amount paid to the treasury to purchase the underlying tokensfunctionexercise(uint256 _amount,
uint256 _maxPaymentAmount,
address _recipient
) externalreturns (uint256) {
return _exercise(_amount, _maxPaymentAmount, _recipient);
}
/// @notice Exercises options tokens to purchase the underlying tokens./// @dev The oracle may revert if it cannot give a secure result./// @param _amount The amount of options tokens to exercise/// @param _maxPaymentAmount The maximum acceptable amount to pay. Used for slippage protection./// @param _recipient The recipient of the purchased underlying tokens/// @param _deadline The Unix timestamp (in seconds) after which the call will revert/// @return The amount paid to the treasury to purchase the underlying tokensfunctionexercise(uint256 _amount,
uint256 _maxPaymentAmount,
address _recipient,
uint256 _deadline
) externalreturns (uint256) {
if (block.timestamp> _deadline) revert OptionToken_PastDeadline();
return _exercise(_amount, _maxPaymentAmount, _recipient);
}
/// @notice Exercises options tokens to purchase the underlying tokens./// @dev The oracle may revert if it cannot give a secure result./// @param _amount The amount of options tokens to exercise/// @param _maxPaymentAmount The maximum acceptable amount to pay. Used for slippage protection./// @param _recipient The recipient of the purchased underlying tokens/// @param _deadline The Unix timestamp (in seconds) after which the call will revert/// @return The amount paid to the treasury to purchase the underlying tokensfunctionexerciseVe(uint256 _amount,
uint256 _maxPaymentAmount,
address _recipient,
uint256 _deadline
) externalreturns (uint256, uint256) {
if (block.timestamp> _deadline) revert OptionToken_PastDeadline();
return _exerciseVe(_amount, _maxPaymentAmount, _recipient);
}
/// @notice Exercises options tokens to create LP and stake in gauges with lock./// @dev The oracle may revert if it cannot give a secure result./// @param _amount The amount of options tokens to exercise/// @param _maxPaymentAmount The maximum acceptable amount to pay. Used for slippage protection./// @param _discount The desired discount/// @param _deadline The Unix timestamp (in seconds) after which the call will revert/// @return The amount paid to the treasury to purchase the underlying tokensfunctionexerciseLp(uint256 _amount,
uint256 _maxPaymentAmount,
address _recipient,
uint256 _discount,
uint256 _deadline
) externalreturns (uint256, uint256) {
if (block.timestamp> _deadline) revert OptionToken_PastDeadline();
return _exerciseLp(_amount, _maxPaymentAmount, _recipient, _discount);
}
/// -----------------------------------------------------------------------/// Public functions/// -----------------------------------------------------------------------/// @notice Returns the discounted price in paymentTokens for a given amount of options tokens/// @param _amount The amount of options tokens to exercise/// @return The amount of payment tokens to pay to purchase the underlying tokensfunctiongetDiscountedPrice(uint256 _amount) publicviewreturns (uint256) {
return (getTimeWeightedAveragePrice(_amount) * discount) /100;
}
/// @notice Returns the discounted price in paymentTokens for a given amount of options tokens redeemed to veFLOW/// @param _amount The amount of options tokens to exercise/// @return The amount of payment tokens to pay to purchase the underlying tokensfunctiongetVeDiscountedPrice(uint256 _amount
) publicviewreturns (uint256) {
return (getTimeWeightedAveragePrice(_amount) * veDiscount) /100;
}
/// @notice Returns the discounted price in paymentTokens for a given amount of options tokens redeemed to veFLOW/// @param _amount The amount of options tokens to exercise/// @param _discount The discount amount/// @return The amount of payment tokens to pay to purchase the underlying tokensfunctiongetLpDiscountedPrice(uint256 _amount,
uint256 _discount
) publicviewreturns (uint256) {
return (getTimeWeightedAveragePrice(_amount) * _discount) /100;
}
/// @notice Returns the lock duration for a desired discount to create locked LP///functiongetLockDurationForLpDiscount(uint256 _discount
) publicviewreturns (uint256 duration) {
(int256 slope, int256 intercept) = getSlopeInterceptForLpDiscount();
duration = SignedMath.abs(slope *int256(_discount) + intercept);
}
// @notice Returns the amount in paymentTokens for a given amount of options tokens required for the LP exercise lp/// @param _amount The amount of options tokens to exercise/// @param _discount The discount amountfunctiongetPaymentTokenAmountForExerciseLp(uint256 _amount,uint256 _discount) publicviewreturns (uint256 paymentAmount, uint256 paymentAmountToAddLiquidity)
{
paymentAmount = getLpDiscountedPrice(_amount, _discount);
(uint256 underlyingReserve, uint256 paymentReserve) = IRouter(router).getReserves(underlyingToken, paymentToken, false);
paymentAmountToAddLiquidity = (_amount * paymentReserve) / underlyingReserve;
}
functiongetSlopeInterceptForLpDiscount()
publicviewreturns (int256 slope, int256 intercept)
{
slope =int256(lockDurationForMaxLpDiscount - lockDurationForMinLpDiscount) /
(int256(maxLPDiscount) -int256(minLPDiscount));
intercept =int256(lockDurationForMinLpDiscount) - (slope *int256(minLPDiscount));
}
/// @notice Returns the average price in payment tokens over 2 hours for a given amount of underlying tokens/// @param _amount The amount of underlying tokens to purchase/// @return The amount of payment tokensfunctiongetTimeWeightedAveragePrice(uint256 _amount
) publicviewreturns (uint256) {
uint256[] memory amtsOut = IPair(pair).prices(
underlyingToken,
_amount,
twapPoints
);
uint256 len = amtsOut.length;
uint256 summedAmount;
for (uint256 i =0; i < len; i++) {
summedAmount += amtsOut[i];
}
return summedAmount / twapPoints;
}
/// -----------------------------------------------------------------------/// Admin functions/// -----------------------------------------------------------------------/// @notice Sets the pair contract. Only callable by the admin./// @param _pair The new pair contractfunctionsetPairAndPaymentToken(
IPair _pair,
address _paymentToken
) externalonlyAdmin{
(address token0, address token1) = _pair.tokens();
if (
!((token0 == _paymentToken && token1 == underlyingToken) ||
(token0 == underlyingToken && token1 == _paymentToken))
) revert OptionToken_IncorrectPairToken();
pair = _pair;
gauge = IVoter(voter).gauges(address(_pair));
paymentToken = _paymentToken;
emit SetPairAndPaymentToken(_pair, _paymentToken);
}
/// @notice Update gauge address to match with Voter contractfunctionupdateGauge() external{
address newGauge = IVoter(voter).gauges(address(pair));
gauge = newGauge;
emit SetGauge(newGauge);
}
/// @notice Sets the gauge address when the gauge is not listed in Voter. Only callable by the admin./// @param _gauge The new treasury addressfunctionsetGauge(address _gauge) externalonlyAdmin{
gauge = _gauge;
emit SetGauge(_gauge);
}
/// @notice Sets the treasury address. Only callable by the admin./// @param _treasury The new treasury addressfunctionsetTreasury(address _treasury,address _vmTreasury) externalonlyAdmin{
treasury = _treasury;
vmTreasury = _vmTreasury;
emit SetTreasury(_treasury,_vmTreasury);
}
/// @notice Sets the router address. Only callable by the admin./// @param _router The new router addressfunctionsetRouter(address _router) externalonlyAdmin{
router = _router;
emit SetRouter(_router);
}
/// @notice Sets the team fee. Only callable by the admin./// @param _fee The new team fee./// @param _vmFee The new vm fee.functionsetFees(uint256 _fee,uint256 _vmFee) externalonlyAdmin{
if (_fee + _vmFee > MAX_FEES) revert OptionToken_InvalidFee();
teamFee = _fee;
vmFee = _vmFee;
emit SetFees(_fee,_vmFee);
}
/// @notice Sets the discount amount. Only callable by the admin./// @param _discount The new discount amount.functionsetDiscount(uint256 _discount) externalonlyAdmin{
if (_discount > MAX_DISCOUNT || _discount == MIN_DISCOUNT)
revert OptionToken_InvalidDiscount();
discount = _discount;
emit SetDiscount(_discount);
}
/// @notice Sets the discount amount for locking. Only callable by the admin./// @param _veDiscount The new discount amount.functionsetVeDiscount(uint256 _veDiscount) externalonlyAdmin{
if (_veDiscount > MAX_DISCOUNT || _veDiscount == MIN_DISCOUNT)
revert OptionToken_InvalidDiscount();
veDiscount = _veDiscount;
emit SetVeDiscount(_veDiscount);
}
/// @notice Sets the discount amount for lp. Only callable by the admin./// @param _lpMinDiscount The new discount amount.functionsetMinLPDiscount(uint256 _lpMinDiscount) externalonlyAdmin{
if (_lpMinDiscount > MAX_DISCOUNT || _lpMinDiscount == MIN_DISCOUNT || maxLPDiscount > _lpMinDiscount)
revert OptionToken_InvalidDiscount();
minLPDiscount = _lpMinDiscount;
emit SetMinLPDiscount(_lpMinDiscount);
}
/// @notice Sets the discount amount for lp. Only callable by the admin./// @param _lpMaxDiscount The new discount amount.functionsetMaxLPDiscount(uint256 _lpMaxDiscount) externalonlyAdmin{
if (_lpMaxDiscount > MAX_DISCOUNT || _lpMaxDiscount == MIN_DISCOUNT || _lpMaxDiscount > minLPDiscount)
revert OptionToken_InvalidDiscount();
maxLPDiscount = _lpMaxDiscount;
emit SetMaxLPDiscount(_lpMaxDiscount);
}
/// @notice Sets the lock duration for max discount amount to create LP and stake in gauge. Only callable by the admin./// @param _duration The new lock duration.functionsetLockDurationForMaxLpDiscount(uint256 _duration
) externalonlyAdmin{
if (_duration <= lockDurationForMinLpDiscount)
revert OptionToken_InvalidLockDuration();
lockDurationForMaxLpDiscount = _duration;
emit SetLockDurationForMaxLpDiscount(_duration);
}
// @notice Sets the lock duration for min discount amount to create LP and stake in gauge. Only callable by the admin./// @param _duration The new lock duration.functionsetLockDurationForMinLpDiscount(uint256 _duration
) externalonlyAdmin{
if (_duration > lockDurationForMaxLpDiscount)
revert OptionToken_InvalidLockDuration();
lockDurationForMinLpDiscount = _duration;
emit SetLockDurationForMinLpDiscount(_duration);
}
/// @notice Sets the twap points. to control the length of our twap/// @param _twapPoints The new twap points.functionsetTwapPoints(uint256 _twapPoints) externalonlyAdmin{
if (_twapPoints > MAX_TWAP_POINTS || _twapPoints ==0)
revert OptionToken_InvalidTwapPoints();
twapPoints = _twapPoints;
emit SetTwapPoints(_twapPoints);
}
/// @notice Called by the admin to mint options tokens. Admin must grant token approval./// @param _to The address that will receive the minted options tokens/// @param _amount The amount of options tokens that will be mintedfunctionmint(address _to, uint256 _amount) externalonlyMinter{
// transfer underlying tokens from the caller
_safeTransferFrom(underlyingToken, msg.sender, address(this), _amount);
// mint options tokens
_mint(_to, _amount);
}
/// @notice Called by the admin to burn options tokens and transfer underlying tokens to the caller./// @param _amount The amount of options tokens that will be burned and underlying tokens transferred to the callerfunctionburn(uint256 _amount) externalonlyAdmin{
// transfer underlying tokens to the caller
_safeTransfer(underlyingToken, msg.sender, _amount);
// burn option tokens
_burn(msg.sender, _amount);
}
/// @notice called by the admin to re-enable option exercising from a paused state.functionunPause() externalonlyAdmin{
if (!isPaused) return;
isPaused =false;
emit PauseStateChanged(false);
}
/// -----------------------------------------------------------------------/// Pauser functions/// -----------------------------------------------------------------------functionpause() externalonlyPauser{
if (isPaused) return;
isPaused =true;
emit PauseStateChanged(true);
}
/// -----------------------------------------------------------------------/// Internal functions/// -----------------------------------------------------------------------function_exercise(uint256 _amount,
uint256 _maxPaymentAmount,
address _recipient
) internalreturns (uint256 paymentAmount) {
if (isPaused) revert OptionToken_Paused();
// burn callers tokens
_burn(msg.sender, _amount);
paymentAmount = getDiscountedPrice(_amount);
if (paymentAmount > _maxPaymentAmount)
revert OptionToken_SlippageTooHigh();
// transfer team fee to treasury and notify reward amount in gaugeuint256 gaugeRewardAmount = _takeFees(paymentToken, paymentAmount);
_usePaymentAsGaugeReward(gaugeRewardAmount);
// send underlying tokens to recipient
_safeTransfer(underlyingToken, _recipient, _amount);
emit Exercise(msg.sender, _recipient, _amount, paymentAmount);
}
function_exerciseVe(uint256 _amount,
uint256 _maxPaymentAmount,
address _recipient
) internalreturns (uint256 paymentAmount, uint256 nftId) {
if (isPaused) revert OptionToken_Paused();
// burn callers tokens
_burn(msg.sender, _amount);
paymentAmount = getVeDiscountedPrice(_amount);
if (paymentAmount > _maxPaymentAmount)
revert OptionToken_SlippageTooHigh();
// transfer team fee to treasury and notify reward amount in gaugeuint256 gaugeRewardAmount = _takeFees(paymentToken, paymentAmount);
_usePaymentAsGaugeReward(gaugeRewardAmount);
// lock underlying tokens to veFLOW
_safeApprove(underlyingToken, votingEscrow, _amount);
nftId = IVotingEscrow(votingEscrow).create_lock_for(
_amount,
FULL_LOCK,
_recipient
);
emit ExerciseVe(msg.sender, _recipient, _amount, paymentAmount, nftId);
}
function_exerciseLp(uint256 _amount, // the oTOKEN amount the user wants to redeem withuint256 _maxPaymentAmount, // the address _recipient,
uint256 _discount
) internalreturns (uint256 paymentAmount, uint256 lpAmount) {
if (isPaused) revert OptionToken_Paused();
if (_discount > minLPDiscount || _discount < maxLPDiscount)
revert OptionToken_InvalidDiscount();
// burn callers tokens
_burn(msg.sender, _amount);
(uint256 paymentAmount,uint256 paymentAmountToAddLiquidity) = getPaymentTokenAmountForExerciseLp(_amount,_discount);
if (paymentAmount > _maxPaymentAmount)
revert OptionToken_SlippageTooHigh();
// Take team feeuint256 paymentGaugeRewardAmount = _takeFees(
paymentToken,
paymentAmount
);
_safeTransferFrom(
paymentToken,
msg.sender,
address(this),
paymentGaugeRewardAmount + paymentAmountToAddLiquidity
);
// Create Lp for users
_safeApprove(underlyingToken, router, _amount);
_safeApprove(paymentToken, router, paymentAmountToAddLiquidity);
(, , lpAmount) = IRouter(router).addLiquidity(
underlyingToken,
paymentToken,
false,
_amount,
paymentAmountToAddLiquidity,
1,
1,
address(this),
block.timestamp
);
// Stake the LP in the gauge with lockaddress _gauge = gauge;
_safeApprove(address(pair), _gauge, lpAmount);
IGaugeV2(_gauge).depositWithLock(
_recipient,
lpAmount,
getLockDurationForLpDiscount(_discount)
);
// notify gauge reward with payment token
_transferRewardToGauge();
emit ExerciseLp(
msg.sender,
_recipient,
_amount,
paymentAmount,
lpAmount
);
}
function_takeFees(address token,
uint256 paymentAmount
) internalreturns (uint256 remaining) {
uint256 _teamFee = (paymentAmount * teamFee) /100;
uint256 _vmFee = (paymentAmount * vmFee) /100;
_safeTransferFrom(token, msg.sender, treasury, _teamFee);
_safeTransferFrom(token, msg.sender, vmTreasury, _vmFee);
remaining = paymentAmount - _teamFee - _vmFee;
}
function_usePaymentAsGaugeReward(uint256 amount) internal{
_safeTransferFrom(paymentToken, msg.sender, address(this), amount);
_transferRewardToGauge();
}
function_transferRewardToGauge() internal{
uint256 paymentTokenCollectedAmount = IERC20(paymentToken).balanceOf(address(this));
uint256 leftRewards = IGaugeV2(gauge).left(paymentToken);
if(paymentTokenCollectedAmount > leftRewards) { // we are sending rewards only if we have more then the current rewards in the gauge
_safeApprove(paymentToken, gauge, paymentTokenCollectedAmount);
IGaugeV2(gauge).notifyRewardAmount(paymentToken, paymentTokenCollectedAmount);
}
}
function_safeTransfer(address token, address to, uint256 value) internal{
require(token.code.length>0);
(bool success, bytesmemory data) = token.call(
abi.encodeWithSelector(IERC20.transfer.selector, to, value)
);
require(success && (data.length==0||abi.decode(data, (bool))));
}
function_safeTransferFrom(address token,
addressfrom,
address to,
uint256 value
) internal{
require(token.code.length>0);
(bool success, bytesmemory data) = token.call(
abi.encodeWithSelector(
IERC20.transferFrom.selector,
from,
to,
value
)
);
require(success && (data.length==0||abi.decode(data, (bool))));
}
function_safeApprove(address token,
address spender,
uint256 value
) internal{
require(token.code.length>0);
(bool success, bytesmemory data) = token.call(
abi.encodeWithSelector(IERC20.approve.selector, spender, value)
);
require(success && (data.length==0||abi.decode(data, (bool))));
}
}
Contract Source Code
File 16 of 17: SignedMath.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)pragmasolidity ^0.8.0;/**
* @dev Standard signed math utilities missing in the Solidity language.
*/librarySignedMath{
/**
* @dev Returns the largest of two signed numbers.
*/functionmax(int256 a, int256 b) internalpurereturns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/functionmin(int256 a, int256 b) internalpurereturns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/functionaverage(int256 a, int256 b) internalpurereturns (int256) {
// Formula from the book "Hacker's Delight"int256 x = (a & b) + ((a ^ b) >>1);
return x + (int256(uint256(x) >>255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/functionabs(int256 n) internalpurereturns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`returnuint256(n >=0 ? n : -n);
}
}
}
Contract Source Code
File 17 of 17: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)pragmasolidity ^0.8.0;import"./math/Math.sol";
import"./math/SignedMath.sol";
/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _SYMBOLS ="0123456789abcdef";
uint8privateconstant _ADDRESS_LENGTH =20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
uint256 length = Math.log10(value) +1;
stringmemory buffer =newstring(length);
uint256 ptr;
/// @solidity memory-safe-assemblyassembly {
ptr :=add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assemblyassembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /=10;
if (value ==0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/functiontoString(int256 value) internalpurereturns (stringmemory) {
returnstring(abi.encodePacked(value <0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
return toHexString(value, Math.log256(value) +1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/functiontoHexString(address addr) internalpurereturns (stringmemory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/functionequal(stringmemory a, stringmemory b) internalpurereturns (bool) {
returnkeccak256(bytes(a)) ==keccak256(bytes(b));
}
}