// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../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.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (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.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(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.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(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 `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./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);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @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.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed 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}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed 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`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (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.
*/
function grantRole(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.
*/
function revokeRole(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 `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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}.
*/
interface IERC165 {
/**
* @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.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev 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}.
* - 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: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* 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 address zero.
*
* 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: UNLICENSED
// Taken from https://github.com/Uniswap/v4-periphery/blob/main/src/interfaces/IMulticall_v4.sol
pragma solidity =0.8.26;
/// @title Multicall_v4 interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall_v4 {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(
uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(
uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(
uint256 tokenId
)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(
MintParams calldata params
)
external
payable
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(
IncreaseLiquidityParams calldata params
) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(
DecreaseLiquidityParams calldata params
) external payable returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
CollectParams calldata params
) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(address token, uint256 amountMinimum, address recipient) external payable;
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity =0.8.26;
pragma abicoder v2;
import './uniswap/IUniswapV3Factory.sol';
import './uniswap/IUniswapV3Pool.sol';
import './uniswap/INonfungiblePositionManager.sol';
import './IMulticall_v4.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @title Ubeswap V3 Farming Interface
/// @notice Allows staking V3 nonfungible liquidity tokens in exchange for reward tokens
interface IUbeswapV3Farming is IERC721Receiver, IMulticall_v4 {
/// @param rewardToken The token being distributed as a reward
/// @param pool The Uniswap V3 compatible pool
/// @param startTime The time when the incentive program begins
/// @param lockTime Minimum time that is required for unstaking a position
/// @param minimumTickRange Minimum value of (tickUpper - tickLower) for a position to be staked
/// @param maxTickLower Maximum value of tickLower for a position to be staked
/// @param minTickLower Minimum value of tickLower for a position to be staked
/// @param maxTickUpper Maximum value of tickUpper for a position to be staked
/// @param minTickUpper Minimum value of tickUpper for a position to be staked
struct IncentiveKey {
IERC20 rewardToken;
IUniswapV3Pool pool;
uint32 startTime;
uint32 lockTime;
int24 minimumTickRange;
int24 maxTickLower;
int24 minTickLower;
int24 maxTickUpper;
int24 minTickUpper;
}
/// @notice The Uniswap V3 compatible Factory
function factory() external view returns (IUniswapV3Factory);
/// @notice The nonfungible position manager with which this staking contract is compatible
function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);
/// @notice The max amount of seconds into the future the incentive startTime can be set
function maxIncentiveStartLeadTime() external view returns (uint256);
/// @notice The max duration of an incentive in seconds
function maxIncentivePeriodDuration() external view returns (uint256);
/// @notice The max duration oc lock time that can be given to an incentive
function maxLockTime() external view returns (uint256);
/// @notice Address of the external reward distributor for the liquidity managers
function externalRewardDistributor() external view returns (address);
/// @notice Update function for externalRewardDistributor
function updateExternalRewardDistributor(address _new) external;
/// @notice Represents a staking incentive
/// @param incentiveId The ID of the incentive computed from its parameters
/// @return currentPeriodId current reward distribution period id
/// @return lastUpdateTime time of last update of cumulativeReward and IncentiveDistributionInfo
/// @return endTime End time of incentive
/// @return numberOfStakes Number of tokens that are staked on the incentive
function incentives(
bytes32 incentiveId
)
external
view
returns (
uint32 currentPeriodId,
uint32 lastUpdateTime,
uint32 endTime,
uint32 numberOfStakes,
uint128 distributedRewards,
bytes32 merkleRoot,
bytes32 ipfsHash,
uint128 excessRewards,
uint128 externalRewards
);
/// @notice
function incentivePeriods(
bytes32 incentiveId,
uint32 periodId
) external view returns (uint128 rewardPerSecond, uint32 startTime, uint32 endTime);
/// @notice Returns information about a deposited NFT
/// @return owner The owner of the deposited NFT
/// @return numberOfStakes Counter of how many incentives for which the liquidity is staked
/// @return tickLower The lower tick of the range
/// @return tickUpper The upper tick of the range
function deposits(
uint256 tokenId
)
external
view
returns (address owner, uint48 numberOfStakes, int24 tickLower, int24 tickUpper);
/// @notice Returns information about a staked liquidity NFT
/// @param incentiveId The ID of the incentive for which the token is staked
/// @param tokenId The ID of the staked token
function stakes(
bytes32 incentiveId,
uint256 tokenId
) external view returns (uint128 claimedReward, uint32 stakeTime, uint32 initialSecondsInside);
/// @notice Creates a new liquidity mining incentive program
/// @param key Details of the incentive to create
/// @param duration The amount of seconds for the first period
/// @param reward The amount of reward tokens to be distributed on the first period
function createIncentive(IncentiveKey memory key, uint32 duration, uint128 reward) external;
/// @notice Creates a new period for the incentive
/// @param key Details of the incentive to extend
/// @param newPeriodId the id for the new period. It should be one more from the previous period. This is taken for security
/// @param duration The amount of seconds for the new period
/// @param reward The amount of reward tokens to be distributed on the new period
function extendIncentive(
IncentiveKey memory key,
uint32 newPeriodId,
uint32 duration,
uint128 reward
) external;
/// @notice Add reward for already created and not started period
function increasePeriodReward(
IncentiveKey memory key,
uint32 periodId,
uint128 reward
) external;
function getAccumulatedReward(
bytes32 incentiveId,
uint32 timestamp
) external view returns (uint128 accumulatedReward, uint32 lastPeriodId);
/// @notice Update function for total liqudity seconds that is calculated off-chain
/// @param incentiveId The ID of the incentive to be updated
/// @param timestamp The timestamp of the block that the calculation is done on
function updateIncentiveDistributionInfo(
bytes32 incentiveId,
uint32 timestamp,
bytes32 merkleRoot,
bytes32 ipfsHash,
uint128 distributedRewardsSinceLastUpdate,
uint128 activeTvlNative,
uint128 externalTvlNative
) external;
/// @notice Refunds excess rewards for the given incentive
/// @param key Details of the incentive to end
function refundExcessRewards(IncentiveKey memory key) external;
/// @notice Transfers ownership of a deposit from the sender to the given recipient
/// @param tokenId The ID of the token (and the deposit) to transfer
/// @param to The new owner of the deposit
function transferDeposit(uint256 tokenId, address to) external;
/// @notice
function collectFee(
INonfungiblePositionManager.CollectParams calldata params
) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Withdraws a Ubeswap V3 LP token `tokenId` from this contract to the recipient `to`
/// @param tokenId The unique identifier of an Ubeswap V3 LP token
/// @param to The address where the LP token will be sent
/// @param data An optional data array that will be passed along to the `to` address via the NFT safeTransferFrom
function withdrawToken(uint256 tokenId, address to, bytes memory data) external;
/// @notice Stakes a Ubeswap V3 LP token
/// @param key The key of the incentive for which to stake the NFT
/// @param tokenId The ID of the token to stake
function stakeToken(IncentiveKey memory key, uint256 tokenId) external;
/// @notice Unstakes a Ubeswap V3 LP token
/// @param key The key of the incentive for which to unstake the NFT
/// @param tokenId The ID of the token to unstake
function unstakeToken(IncentiveKey memory key, uint256 tokenId) external;
/// @notice Transfers the rewards that are accumulated for the token in the incentive
/// @param key The key of the incentive for which to unstake the NFT
/// @param tokenId The ID of the token that has rewards
/// @param accumulatedRewards accumulated rewards for the position
/// @param proof Merkle proof for rewards
function collectReward(
IncentiveKey memory key,
uint256 tokenId,
uint128 accumulatedRewards,
bytes32[] memory proof
) external;
/// @notice Transfers the rewards that are accumulated for the external reward distributor
function collectExternalReward(IncentiveKey memory key) external;
function getStakedTokenByIndex(
bytes32 incentiveId,
uint256 index
) external view returns (uint256);
/// @notice Event emitted when a liquidity mining incentive has been created
/// @param rewardToken The token being distributed as a reward
/// @param pool The Uniswap V3 compatible pool
/// @param startTime The time when the incentive program begins
/// @param lockTime Minimum time that is required for unstaking a position
/// @param minimumTickRange Minimum value of (tickUpper - tickLower) for a position to be staked
/// @param maxTickLower Maximum value of tickLower for a position to be staked
/// @param minTickLower Minimum value of tickLower for a position to be staked
/// @param maxTickUpper Maximum value of tickUpper for a position to be staked
/// @param minTickUpper Minimum value of tickUpper for a position to be staked
event IncentiveCreated(
bytes32 indexed incentiveId,
IERC20 indexed rewardToken,
IUniswapV3Pool indexed pool,
uint32 startTime,
uint32 lockTime,
int24 minimumTickRange,
int24 maxTickLower,
int24 minTickLower,
int24 maxTickUpper,
int24 minTickUpper
);
/// @notice
event IncentiveExtended(
bytes32 indexed incentiveId,
uint32 newPeriodId,
uint32 duration,
uint128 reward
);
/// @notice
event PeriodRewardIncreased(bytes32 indexed incentiveId, uint32 periodId, uint128 reward);
/// @notice
event IncentiveUpdated(
bytes32 indexed incentiveId,
uint32 timestamp,
uint32 newPeriodId,
bytes32 merkleRoot,
bytes32 ipfsHash,
uint128 distributedRewardsSinceLastUpdate,
uint128 activeTvlNative,
uint128 externalTvlNative
);
/// @notice Event that can be emitted when excess rewards refunded
/// @param incentiveId The incentive which has excess rewards
event ExcessRewardsRefunded(bytes32 indexed incentiveId, uint128 refund);
/// @notice Emitted when ownership of a deposit changes
/// @param tokenId The ID of the deposit (and token) that is being transferred
/// @param oldOwner The owner before the deposit was transferred
/// @param newOwner The owner after the deposit was transferred
event DepositTransferred(
uint256 indexed tokenId,
address indexed oldOwner,
address indexed newOwner
);
/// @notice Event emitted when a Ubeswap V3 LP token has been staked
/// @param tokenId The unique identifier of an Ubeswap V3 LP token
/// @param liquidity The amount of liquidity staked
/// @param incentiveId The incentive in which the token is staking
event TokenStaked(
uint256 indexed tokenId,
bytes32 indexed incentiveId,
uint128 liquidity,
uint32 initialSecondsInside
);
/// @notice Event emitted when a Ubeswap V3 LP token has been unstaked
/// @param tokenId The unique identifier of an Ubeswap V3 LP token
/// @param incentiveId The incentive in which the token is staking
event TokenUnstaked(uint256 indexed tokenId, bytes32 indexed incentiveId);
/// @notice Event emitted when a reward collected for an incentive
/// @param tokenId The unique identifier of an Ubeswap V3 LP token
/// @param incentiveId The incentive
/// @param to The address where claimed rewards were sent to
/// @param reward The amount of reward tokens claimed
event RewardCollected(
uint256 indexed tokenId,
bytes32 indexed incentiveId,
address indexed to,
uint256 reward
);
/// @notice Event emitted when externalRewardDistributor contract collects reward
/// @param incentiveId The incentive
/// @param to externalRewardDistributor address at the time on transaction
/// @param reward The amount of reward tokens claimed
event ExternalRewardCollected(bytes32 indexed incentiveId, address to, uint256 reward);
/// @notice Event emitted when a fee collected from a pool
/// @param owner Owner account of the deposited token when the fee collected
/// @param tokenId The unique identifier of an Ubeswap V3 LP token
/// @param recipient Fee recepient
event FeeCollected(
address indexed owner,
uint256 indexed tokenId,
address recipient,
uint128 amount0Max,
uint128 amount1Max
);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, uint24 fee) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @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 amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @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 amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity =0.8.26;
pragma abicoder v2;
import '../interfaces/IUbeswapV3Farming.sol';
library IncentiveId {
/// @notice Calculate the key for a staking incentive
/// @param key The components used to compute the incentive identifier
/// @return incentiveId The identifier for the incentive
function compute(
IUbeswapV3Farming.IncentiveKey memory key
) internal pure returns (bytes32 incentiveId) {
return keccak256(abi.encode(key));
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity =0.8.26;
/**
* @dev This is like EnumerableSet
* But it doesn't use arrays for gas efficiency
* It gets length of the set from outside
*/
library KnownLengthSet {
struct UintSet {
// index => value
mapping(uint256 => uint256) _values;
// value => index
mapping(uint256 => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not already present.
*/
function add(
UintSet storage set,
uint256 value,
uint256 currentLength
) internal returns (bool) {
if (!contains(set, value)) {
set._values[currentLength] = value;
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = currentLength + 1;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was present.
*/
function remove(
UintSet storage set,
uint256 value,
uint256 currentLength
) internal returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element we delete the last element but
// if the element is not the last one, we swap them first
uint256 valueIndex = position - 1;
uint256 lastIndex = currentLength - 1;
if (valueIndex != lastIndex) {
uint256 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
delete set._values[lastIndex];
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return set._values[index];
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.20;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Sorts the pair (a, b) and hashes the result.
*/
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: GPL-2.0
// Taken from https://github.com/Uniswap/v4-periphery/blob/main/src/base/Multicall_v4.sol
pragma solidity =0.8.26;
import { IMulticall_v4 } from './interfaces/IMulticall_v4.sol';
/// @title Multicall_v4
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall_v4 is IMulticall_v4 {
/// @inheritdoc IMulticall_v4
function multicall(
bytes[] calldata data
) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// bubble up the revert reason
assembly {
revert(add(result, 0x20), mload(result))
}
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity =0.8.26;
import '../interfaces/uniswap/INonfungiblePositionManager.sol';
import '../interfaces/uniswap/IUniswapV3Factory.sol';
import '../interfaces/uniswap/IUniswapV3Pool.sol';
import './PoolAddress.sol';
/// @notice Encapsulates the logic for getting info about a NFT token ID
library NFTPositionInfo {
/// @param factory The address of the Uniswap V3 compatible Factory used in computing the pool address
/// @param nonfungiblePositionManager The address of the nonfungible position manager to query
/// @param tokenId The unique identifier of an Ubeswap V3 LP token
/// @return pool The address of the Uniswap V3 compatible pool
/// @return tickLower The lower tick of the Ubeswap V3 position
/// @return tickUpper The upper tick of the Ubeswap V3 position
/// @return liquidity The amount of liquidity staked
function getPositionInfo(
IUniswapV3Factory factory,
INonfungiblePositionManager nonfungiblePositionManager,
uint256 tokenId
)
internal
view
returns (IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity)
{
address token0;
address token1;
uint24 fee;
(
,
,
token0,
token1,
fee,
tickLower,
tickUpper,
liquidity,
,
,
,
) = nonfungiblePositionManager.positions(tokenId);
pool = IUniswapV3Pool(
PoolAddress.computeAddress(
address(factory),
PoolAddress.PoolKey({ token0: token0, token1: token1, fee: fee })
)
);
}
}
// SPDX-License-Identifier: GPL-2.0
// Taken from @uniswap/v3-periphery/contracts/libraries/PoolAddress.sol
// uint256 to address conversion is fixed for solidity 0.8 compatibility
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH =
0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({ token0: tokenA, token1: tokenB, fee: fee });
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(
address factory,
PoolKey memory key
) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
// SPDX-License-Identifier: GPL-2.0
pragma solidity =0.8.26;
pragma abicoder v2;
import './interfaces/IUbeswapV3Farming.sol';
import './libraries/IncentiveId.sol';
import './libraries/NFTPositionInfo.sol';
import './interfaces/uniswap/IUniswapV3Factory.sol';
import './interfaces/uniswap/IUniswapV3Pool.sol';
import './interfaces/uniswap/INonfungiblePositionManager.sol';
import './Multicall_v4.sol';
import './libraries/KnownLengthSet.sol';
import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol';
import '@openzeppelin/contracts/access/AccessControl.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
/// @title Off-chain assisted Ubeswap V3 Farming Protocol
contract UbeswapV3Farming is IUbeswapV3Farming, AccessControl, Multicall_v4 {
using KnownLengthSet for KnownLengthSet.UintSet;
bytes32 public constant INCENTIVE_MANAGER_ROLE = keccak256('INCENTIVE_MANAGER_ROLE');
bytes32 public constant INCENTIVE_UPDATER_ROLE = keccak256('INCENTIVE_UPDATER_ROLE');
bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256('REWARD_DISTRIBUTOR_ROLE');
/// @notice Represents a staking incentive
struct Incentive {
uint32 currentPeriodId;
uint32 lastUpdateTime;
uint32 endTime;
uint32 numberOfStakes;
uint128 distributedRewards;
// -----------
bytes32 merkleRoot;
// -----------
bytes32 ipfsHash;
// -----------
uint128 excessRewards;
uint128 externalRewards;
}
struct IncentivePeriod {
uint128 rewardPerSecond;
uint32 startTime;
uint32 endTime;
}
/// @notice Represents the deposit of a liquidity NFT
struct Deposit {
address owner;
uint48 numberOfStakes;
int24 tickLower;
int24 tickUpper;
}
/// @notice Represents a staked liquidity NFT
struct Stake {
uint128 claimedReward;
uint32 stakeTime;
uint32 initialSecondsInside;
}
/// @inheritdoc IUbeswapV3Farming
IUniswapV3Factory public immutable override factory;
/// @inheritdoc IUbeswapV3Farming
INonfungiblePositionManager public immutable override nonfungiblePositionManager;
/// @inheritdoc IUbeswapV3Farming
uint256 public immutable override maxIncentiveStartLeadTime;
/// @inheritdoc IUbeswapV3Farming
uint256 public immutable override maxIncentivePeriodDuration;
/// @inheritdoc IUbeswapV3Farming
uint256 public immutable override maxLockTime;
/// @inheritdoc IUbeswapV3Farming
address public override externalRewardDistributor;
/// @dev bytes32 refers to the return value of IncentiveId.compute
mapping(bytes32 => Incentive) public override incentives;
/// @dev incentivePeriods[incentiveId][periodId] => IncentivePeriod
mapping(bytes32 => mapping(uint32 => IncentivePeriod)) public override incentivePeriods;
/// @dev deposits[tokenId] => Deposit
mapping(uint256 => Deposit) public override deposits;
/// @dev stakes[incentiveId][tokenId] => Stake
mapping(bytes32 => mapping(uint256 => Stake)) public override stakes;
// incentiveId => staked tokens set
mapping(bytes32 => KnownLengthSet.UintSet) private _stakedTokens;
/// @param _factory the Uniswap V3 compatible factory
/// @param _nonfungiblePositionManager the NFT position manager contract address
/// @param _maxIncentiveStartLeadTime the max duration of an incentive in seconds
/// @param _maxIncentivePeriodDuration the max amount of seconds into the future the incentive startTime can be set
constructor(
IUniswapV3Factory _factory,
INonfungiblePositionManager _nonfungiblePositionManager,
uint256 _maxIncentiveStartLeadTime,
uint256 _maxIncentivePeriodDuration,
uint256 _maxLockTime
) {
factory = _factory;
nonfungiblePositionManager = _nonfungiblePositionManager;
maxIncentiveStartLeadTime = _maxIncentiveStartLeadTime;
maxIncentivePeriodDuration = _maxIncentivePeriodDuration;
maxLockTime = _maxLockTime;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(INCENTIVE_MANAGER_ROLE, msg.sender);
_grantRole(INCENTIVE_UPDATER_ROLE, msg.sender);
_grantRole(REWARD_DISTRIBUTOR_ROLE, msg.sender);
}
function updateExternalRewardDistributor(
address _new
) public override onlyRole(INCENTIVE_MANAGER_ROLE) {
externalRewardDistributor = _new;
}
/// @inheritdoc IUbeswapV3Farming
function createIncentive(
IncentiveKey memory key,
uint32 duration,
uint128 reward
) external override onlyRole(INCENTIVE_MANAGER_ROLE) {
uint32 endTime = key.startTime + duration;
require(reward > 0, 'reward must be positive');
require(duration > 0, 'duration must be positive');
require(block.timestamp <= key.startTime, 'startTime must be after now');
require(
key.startTime - block.timestamp <= maxIncentiveStartLeadTime,
'start time too far into future'
);
require(duration <= maxIncentivePeriodDuration, 'incentive duration is too long');
require(key.lockTime <= maxLockTime, 'wrong lock time');
require(key.maxTickLower > key.minTickLower, 'wrong tickLower range');
require(key.maxTickUpper > key.minTickUpper, 'wrong tickUpper range');
bytes32 incentiveId = IncentiveId.compute(key);
require(incentives[incentiveId].endTime == 0, 'incentive already exists');
incentives[incentiveId].endTime = endTime;
incentives[incentiveId].lastUpdateTime = key.startTime;
incentivePeriods[incentiveId][0] = IncentivePeriod({
rewardPerSecond: reward / duration,
startTime: key.startTime,
endTime: endTime
});
SafeERC20.safeTransferFrom(key.rewardToken, msg.sender, address(this), reward);
emit IncentiveCreated(
incentiveId,
key.rewardToken,
key.pool,
key.startTime,
key.lockTime,
key.minimumTickRange,
key.maxTickLower,
key.minTickLower,
key.maxTickUpper,
key.minTickUpper
);
emit IncentiveExtended(incentiveId, 0, duration, reward);
}
/// @inheritdoc IUbeswapV3Farming
function extendIncentive(
IncentiveKey memory key,
uint32 newPeriodId,
uint32 duration,
uint128 reward
) external override onlyRole(REWARD_DISTRIBUTOR_ROLE) {
require(reward > 0, 'reward must be positive');
require(duration > 0, 'duration must be positive');
require(duration <= maxIncentivePeriodDuration, 'incentive duration is too long');
bytes32 incentiveId = IncentiveId.compute(key);
uint32 currentEndTime = incentives[incentiveId].endTime;
require(currentEndTime > 0, 'non-existent incentive');
require(incentives[incentiveId].currentPeriodId == (newPeriodId - 1), 'wrong period id');
uint32 newEndTime = currentEndTime + duration;
incentivePeriods[incentiveId][newPeriodId] = IncentivePeriod({
rewardPerSecond: reward / duration,
startTime: currentEndTime,
endTime: newEndTime
});
incentives[incentiveId].endTime = newEndTime;
SafeERC20.safeTransferFrom(key.rewardToken, msg.sender, address(this), reward);
emit IncentiveExtended(incentiveId, newPeriodId, duration, reward);
}
/// @inheritdoc IUbeswapV3Farming
function increasePeriodReward(
IncentiveKey memory key,
uint32 periodId,
uint128 reward
) external override onlyRole(REWARD_DISTRIBUTOR_ROLE) {
require(reward > 0, 'reward must be positive');
bytes32 incentiveId = IncentiveId.compute(key);
IncentivePeriod memory period = incentivePeriods[incentiveId][periodId];
require(period.rewardPerSecond > 0, 'non-existent incentive or period');
require(block.timestamp <= period.startTime, 'period is started');
period.rewardPerSecond += reward / (period.endTime - period.startTime);
incentivePeriods[incentiveId][periodId] = period;
SafeERC20.safeTransferFrom(key.rewardToken, msg.sender, address(this), reward);
emit PeriodRewardIncreased(incentiveId, periodId, reward);
}
/// @inheritdoc IUbeswapV3Farming
function getAccumulatedReward(
bytes32 incentiveId,
uint32 timestamp
) public view override returns (uint128 accumulatedReward, uint32 lastPeriodId) {
uint32 currentPeriodId = incentives[incentiveId].currentPeriodId;
uint32 lastUpdateTime = incentives[incentiveId].lastUpdateTime;
lastPeriodId = currentPeriodId;
IncentivePeriod memory currPeriod = incentivePeriods[incentiveId][currentPeriodId];
accumulatedReward = 0;
if (timestamp > currPeriod.endTime) {
accumulatedReward = (currPeriod.endTime - lastUpdateTime) * currPeriod.rewardPerSecond;
lastPeriodId += 1;
IncentivePeriod memory nextPeriod = incentivePeriods[incentiveId][lastPeriodId];
require(nextPeriod.rewardPerSecond > 0, 'next period not exists');
require(timestamp <= nextPeriod.endTime, 'next period ended too');
accumulatedReward += (timestamp - currPeriod.endTime) * nextPeriod.rewardPerSecond;
} else {
accumulatedReward = (timestamp - lastUpdateTime) * currPeriod.rewardPerSecond;
}
}
/// @inheritdoc IUbeswapV3Farming
function updateIncentiveDistributionInfo(
bytes32 incentiveId,
uint32 timestamp,
bytes32 merkleRoot,
bytes32 ipfsHash,
uint128 distributedRewardsSinceLastUpdate,
uint128 activeTvlNative,
uint128 externalTvlNative
) external override onlyRole(INCENTIVE_UPDATER_ROLE) {
require(timestamp < block.timestamp, 'time must be before now');
Incentive memory incentive = incentives[incentiveId];
require(incentive.lastUpdateTime > 0, 'non-existent incentive');
require(timestamp > incentive.lastUpdateTime, 'timestamp > lastUpdateTime');
(uint128 accumulatedReward, uint32 lastPeriodId) = getAccumulatedReward(
incentiveId,
timestamp
);
uint128 tvlNative = activeTvlNative + externalTvlNative;
if (tvlNative == 0) {
// this means, no rewards has been disributed, so rewards will be refunded later
require(incentive.merkleRoot == merkleRoot, 'invalid merkleRoot');
require(distributedRewardsSinceLastUpdate == 0, 'reward must be 0');
incentive.excessRewards += accumulatedReward;
} else {
require(incentive.merkleRoot != merkleRoot, 'same merkleRoot');
require(incentive.ipfsHash != ipfsHash, 'same ipfsHash');
require(distributedRewardsSinceLastUpdate == accumulatedReward, 'invalid reward');
incentive.externalRewards += uint128(
(uint256(accumulatedReward) * uint256(externalTvlNative)) / uint256(tvlNative)
);
}
incentive.currentPeriodId = lastPeriodId;
incentive.distributedRewards += accumulatedReward;
incentive.lastUpdateTime = timestamp;
incentive.merkleRoot = merkleRoot;
incentive.ipfsHash = ipfsHash;
incentives[incentiveId] = incentive;
emit IncentiveUpdated(
incentiveId,
timestamp,
incentive.currentPeriodId,
merkleRoot,
ipfsHash,
accumulatedReward,
activeTvlNative,
externalTvlNative
);
}
/// @inheritdoc IUbeswapV3Farming
function refundExcessRewards(
IncentiveKey memory key
) external override onlyRole(INCENTIVE_MANAGER_ROLE) {
bytes32 incentiveId = IncentiveId.compute(key);
uint128 excessRewards = incentives[incentiveId].excessRewards;
require(excessRewards > 0, 'no excess rewards');
incentives[incentiveId].excessRewards = 0;
SafeERC20.safeTransfer(key.rewardToken, msg.sender, excessRewards);
emit ExcessRewardsRefunded(incentiveId, excessRewards);
}
/// @notice Upon receiving a Ubeswap V3 ERC721, creates the token deposit setting owner to `from`. Also stakes token
/// in one or more incentives if properly formatted `data` has a length > 0.
/// @inheritdoc IERC721Receiver
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
require(msg.sender == address(nonfungiblePositionManager), 'not a univ3 nft');
(, , , , , int24 tickLower, int24 tickUpper, , , , , ) = nonfungiblePositionManager
.positions(tokenId);
deposits[tokenId] = Deposit({
owner: from,
numberOfStakes: 0,
tickLower: tickLower,
tickUpper: tickUpper
});
emit DepositTransferred(tokenId, address(0), from);
if (data.length > 0) {
if (data.length == 288) {
_stakeToken(abi.decode(data, (IncentiveKey)), tokenId);
} else {
IncentiveKey[] memory keys = abi.decode(data, (IncentiveKey[]));
for (uint256 i = 0; i < keys.length; i++) {
_stakeToken(keys[i], tokenId);
}
}
}
return this.onERC721Received.selector;
}
/// @inheritdoc IUbeswapV3Farming
function transferDeposit(uint256 tokenId, address to) external override {
require(to != address(this), 'cannot transfer to farm');
require(to != address(0), 'invalid to address');
address owner = deposits[tokenId].owner;
require(owner == msg.sender, 'only owner can transfer');
deposits[tokenId].owner = to;
emit DepositTransferred(tokenId, owner, to);
}
/// @inheritdoc IUbeswapV3Farming
function collectFee(
INonfungiblePositionManager.CollectParams calldata params
) external payable override returns (uint256 amount0, uint256 amount1) {
address owner = deposits[params.tokenId].owner;
require(owner == msg.sender, 'only owner can collect');
(amount0, amount1) = nonfungiblePositionManager.collect{ value: msg.value }(params);
emit FeeCollected(
msg.sender,
params.tokenId,
params.recipient,
params.amount0Max,
params.amount1Max
);
}
/// @inheritdoc IUbeswapV3Farming
function withdrawToken(uint256 tokenId, address to, bytes memory data) external override {
require(to != address(this), 'cannot withdraw to farm');
require(to != address(0), 'invalid to address');
Deposit memory deposit = deposits[tokenId];
require(deposit.numberOfStakes == 0, 'token is staked');
require(deposit.owner == msg.sender, 'only owner can withdraw');
delete deposits[tokenId];
emit DepositTransferred(tokenId, deposit.owner, address(0));
nonfungiblePositionManager.safeTransferFrom(address(this), to, tokenId, data);
}
/// @inheritdoc IUbeswapV3Farming
function stakeToken(IncentiveKey memory key, uint256 tokenId) external override {
require(deposits[tokenId].owner == msg.sender, 'only owner can stake token');
_stakeToken(key, tokenId);
}
/// @inheritdoc IUbeswapV3Farming
function unstakeToken(IncentiveKey memory key, uint256 tokenId) external override {
require(deposits[tokenId].owner == msg.sender, 'only owner can unstake');
bytes32 incentiveId = IncentiveId.compute(key);
require(stakes[incentiveId][tokenId].stakeTime > 0, 'token not staked');
Incentive memory incentive = incentives[incentiveId];
if (key.lockTime > 0) {
require(
key.lockTime < (block.timestamp - stakes[incentiveId][tokenId].stakeTime),
'token locked'
);
}
_stakedTokens[incentiveId].remove(tokenId, incentive.numberOfStakes);
stakes[incentiveId][tokenId] = Stake({
claimedReward: stakes[incentiveId][tokenId].claimedReward,
stakeTime: 0,
initialSecondsInside: 0
});
deposits[tokenId].numberOfStakes--;
incentives[incentiveId].numberOfStakes--;
emit TokenUnstaked(tokenId, incentiveId);
}
/// @inheritdoc IUbeswapV3Farming
function collectReward(
IncentiveKey memory key,
uint256 tokenId,
uint128 accumulatedRewards,
bytes32[] memory proof
) external override {
require(deposits[tokenId].owner == msg.sender, 'only owner can collect');
bytes32 incentiveId = IncentiveId.compute(key);
bytes32 firstHash = keccak256(abi.encode(tokenId, accumulatedRewards));
bytes32 leaf = keccak256(bytes.concat(firstHash));
require(
MerkleProof.verify(proof, incentives[incentiveId].merkleRoot, leaf),
'Invalid proof'
);
uint256 reward = accumulatedRewards - stakes[incentiveId][tokenId].claimedReward;
require(reward > 0, 'no rewards');
stakes[incentiveId][tokenId].claimedReward = accumulatedRewards;
SafeERC20.safeTransferFrom(key.rewardToken, address(this), msg.sender, reward);
emit RewardCollected(tokenId, incentiveId, msg.sender, reward);
}
/// @inheritdoc IUbeswapV3Farming
function collectExternalReward(IncentiveKey memory key) external override {
require(externalRewardDistributor == msg.sender, 'not externalRewardDistributor');
bytes32 incentiveId = IncentiveId.compute(key);
uint128 reward = incentives[incentiveId].externalRewards;
require(reward > 0, 'no rewards');
incentives[incentiveId].externalRewards = 0;
SafeERC20.safeTransferFrom(key.rewardToken, address(this), msg.sender, reward);
emit ExternalRewardCollected(incentiveId, msg.sender, reward);
}
/// @inheritdoc IUbeswapV3Farming
function getStakedTokenByIndex(
bytes32 incentiveId,
uint256 index
) external view override returns (uint256) {
return _stakedTokens[incentiveId].at(index);
}
/// @dev Stakes a deposited token without doing an ownership check
function _stakeToken(IncentiveKey memory key, uint256 tokenId) private {
bytes32 incentiveId = IncentiveId.compute(key);
uint32 endTime = incentives[incentiveId].endTime;
uint32 numberOfStakes = incentives[incentiveId].numberOfStakes;
require(endTime > 0, 'non-existent incentive');
require(
block.timestamp >= key.startTime && block.timestamp < endTime,
'incentive not active'
);
require(stakes[incentiveId][tokenId].stakeTime == 0, 'token already staked');
(IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity) = NFTPositionInfo
.getPositionInfo(factory, nonfungiblePositionManager, tokenId);
require(pool == key.pool, 'token pool is not the incentive pool');
require(key.minimumTickRange <= (tickUpper - tickLower), 'wrong tick range');
require(key.maxTickLower >= tickLower && key.minTickLower <= tickLower, 'wrong tickLower');
require(key.maxTickUpper >= tickUpper && key.minTickUpper <= tickUpper, 'wrong tickUpper');
require(liquidity > 0, 'cannot stake token with 0 liquidity');
_stakedTokens[incentiveId].add(tokenId, numberOfStakes);
deposits[tokenId].numberOfStakes++;
incentives[incentiveId].numberOfStakes++;
(, , uint32 secondsInside) = pool.snapshotCumulativesInside(tickLower, tickUpper);
stakes[incentiveId][tokenId] = Stake({
claimedReward: stakes[incentiveId][tokenId].claimedReward,
stakeTime: uint32(block.timestamp),
initialSecondsInside: secondsInside
});
emit TokenStaked(tokenId, incentiveId, liquidity, secondsInside);
}
}
{
"compilationTarget": {
"contracts/UbeswapV3Farming.sol": "UbeswapV3Farming"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 100000
},
"remappings": []
}
[{"inputs":[{"internalType":"contract IUniswapV3Factory","name":"_factory","type":"address"},{"internalType":"contract INonfungiblePositionManager","name":"_nonfungiblePositionManager","type":"address"},{"internalType":"uint256","name":"_maxIncentiveStartLeadTime","type":"uint256"},{"internalType":"uint256","name":"_maxIncentivePeriodDuration","type":"uint256"},{"internalType":"uint256","name":"_maxLockTime","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"DepositTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint128","name":"refund","type":"uint128"}],"name":"ExcessRewardsRefunded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"ExternalRewardCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount0Max","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"amount1Max","type":"uint128"}],"name":"FeeCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":true,"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"indexed":true,"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"indexed":false,"internalType":"uint32","name":"startTime","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"lockTime","type":"uint32"},{"indexed":false,"internalType":"int24","name":"minimumTickRange","type":"int24"},{"indexed":false,"internalType":"int24","name":"maxTickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"minTickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"maxTickUpper","type":"int24"},{"indexed":false,"internalType":"int24","name":"minTickUpper","type":"int24"}],"name":"IncentiveCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint32","name":"newPeriodId","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"duration","type":"uint32"},{"indexed":false,"internalType":"uint128","name":"reward","type":"uint128"}],"name":"IncentiveExtended","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint32","name":"timestamp","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"newPeriodId","type":"uint32"},{"indexed":false,"internalType":"bytes32","name":"merkleRoot","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"ipfsHash","type":"bytes32"},{"indexed":false,"internalType":"uint128","name":"distributedRewardsSinceLastUpdate","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"activeTvlNative","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"externalTvlNative","type":"uint128"}],"name":"IncentiveUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint32","name":"periodId","type":"uint32"},{"indexed":false,"internalType":"uint128","name":"reward","type":"uint128"}],"name":"PeriodRewardIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"uint32","name":"initialSecondsInside","type":"uint32"}],"name":"TokenStaked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"}],"name":"TokenUnstaked","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INCENTIVE_MANAGER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INCENTIVE_UPDATER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REWARD_DISTRIBUTOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"}],"name":"collectExternalReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint128","name":"amount0Max","type":"uint128"},{"internalType":"uint128","name":"amount1Max","type":"uint128"}],"internalType":"struct INonfungiblePositionManager.CollectParams","name":"params","type":"tuple"}],"name":"collectFee","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"accumulatedRewards","type":"uint128"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"collectReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint32","name":"duration","type":"uint32"},{"internalType":"uint128","name":"reward","type":"uint128"}],"name":"createIncentive","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"deposits","outputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint48","name":"numberOfStakes","type":"uint48"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint32","name":"newPeriodId","type":"uint32"},{"internalType":"uint32","name":"duration","type":"uint32"},{"internalType":"uint128","name":"reward","type":"uint128"}],"name":"extendIncentive","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"externalRewardDistributor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"contract IUniswapV3Factory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"internalType":"uint32","name":"timestamp","type":"uint32"}],"name":"getAccumulatedReward","outputs":[{"internalType":"uint128","name":"accumulatedReward","type":"uint128"},{"internalType":"uint32","name":"lastPeriodId","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getStakedTokenByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"uint32","name":"","type":"uint32"}],"name":"incentivePeriods","outputs":[{"internalType":"uint128","name":"rewardPerSecond","type":"uint128"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"endTime","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"incentives","outputs":[{"internalType":"uint32","name":"currentPeriodId","type":"uint32"},{"internalType":"uint32","name":"lastUpdateTime","type":"uint32"},{"internalType":"uint32","name":"endTime","type":"uint32"},{"internalType":"uint32","name":"numberOfStakes","type":"uint32"},{"internalType":"uint128","name":"distributedRewards","type":"uint128"},{"internalType":"bytes32","name":"merkleRoot","type":"bytes32"},{"internalType":"bytes32","name":"ipfsHash","type":"bytes32"},{"internalType":"uint128","name":"excessRewards","type":"uint128"},{"internalType":"uint128","name":"externalRewards","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint32","name":"periodId","type":"uint32"},{"internalType":"uint128","name":"reward","type":"uint128"}],"name":"increasePeriodReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maxIncentivePeriodDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxIncentiveStartLeadTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLockTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"nonfungiblePositionManager","outputs":[{"internalType":"contract INonfungiblePositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"}],"name":"refundExcessRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"stakeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"stakes","outputs":[{"internalType":"uint128","name":"claimedReward","type":"uint128"},{"internalType":"uint32","name":"stakeTime","type":"uint32"},{"internalType":"uint32","name":"initialSecondsInside","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"transferDeposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"rewardToken","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"internalType":"uint32","name":"startTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"int24","name":"minimumTickRange","type":"int24"},{"internalType":"int24","name":"maxTickLower","type":"int24"},{"internalType":"int24","name":"minTickLower","type":"int24"},{"internalType":"int24","name":"maxTickUpper","type":"int24"},{"internalType":"int24","name":"minTickUpper","type":"int24"}],"internalType":"struct IUbeswapV3Farming.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"unstakeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_new","type":"address"}],"name":"updateExternalRewardDistributor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"internalType":"uint32","name":"timestamp","type":"uint32"},{"internalType":"bytes32","name":"merkleRoot","type":"bytes32"},{"internalType":"bytes32","name":"ipfsHash","type":"bytes32"},{"internalType":"uint128","name":"distributedRewardsSinceLastUpdate","type":"uint128"},{"internalType":"uint128","name":"activeTvlNative","type":"uint128"},{"internalType":"uint128","name":"externalTvlNative","type":"uint128"}],"name":"updateIncentiveDistributionInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"withdrawToken","outputs":[],"stateMutability":"nonpayable","type":"function"}]