// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
/// minting and transferring zero tokens, as well as self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
/// the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The total supply has overflowed.
error TotalSupplyOverflow();
/// @dev The allowance has overflowed.
error AllowanceOverflow();
/// @dev The allowance has underflowed.
error AllowanceUnderflow();
/// @dev Insufficient balance.
error InsufficientBalance();
/// @dev Insufficient allowance.
error InsufficientAllowance();
/// @dev The permit is invalid.
error InvalidPermit();
/// @dev The permit has expired.
error PermitExpired();
/// @dev The allowance of Permit2 is fixed at infinity.
error Permit2AllowanceIsFixedAtInfinity();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The storage slot for the total supply.
uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
/// @dev The balance slot of `owner` is given by:
/// ```
/// mstore(0x0c, _BALANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
/// @dev The allowance slot of (`owner`, `spender`) is given by:
/// ```
/// mstore(0x20, spender)
/// mstore(0x0c, _ALLOWANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let allowanceSlot := keccak256(0x0c, 0x34)
/// ```
uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
/// @dev The nonce slot of `owner` is given by:
/// ```
/// mstore(0x0c, _NONCES_SLOT_SEED)
/// mstore(0x00, owner)
/// let nonceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 private constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("1")`.
/// If you need to use a different version, override `_versionHash`.
bytes32 private constant _DEFAULT_VERSION_HASH =
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
bytes32 private constant _PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @dev The canonical Permit2 address.
/// For signature-based allowance granting for single transaction ERC20 `transferFrom`.
/// To enable, override `_givePermit2InfiniteAllowance()`.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the name of the token.
function name() public view virtual returns (string memory);
/// @dev Returns the symbol of the token.
function symbol() public view virtual returns (string memory);
/// @dev Returns the decimals places of the token.
function decimals() public view virtual returns (uint8) {
return 18;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the amount of tokens in existence.
function totalSupply() public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_TOTAL_SUPPLY_SLOT)
}
}
/// @dev Returns the amount of tokens owned by `owner`.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
function allowance(address owner, address spender)
public
view
virtual
returns (uint256 result)
{
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return type(uint256).max;
}
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x34))
}
}
/// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
///
/// Emits a {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
}
return true;
}
/// @dev Transfer `amount` tokens from the caller to `to`.
///
/// Requirements:
/// - `from` must at least have `amount`.
///
/// Emits a {Transfer} event.
function transfer(address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(msg.sender, to, amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, caller())
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
}
_afterTokenTransfer(msg.sender, to, amount);
return true;
}
/// @dev Transfers `amount` tokens from `from` to `to`.
///
/// Note: Does not update the allowance if it is the maximum uint256 value.
///
/// Requirements:
/// - `from` must at least have `amount`.
/// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(from, to, amount);
// Code duplication is for zero-cost abstraction if possible.
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
if iszero(eq(caller(), _PERMIT2)) {
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
}
_afterTokenTransfer(from, to, amount);
return true;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-2612 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For more performance, override to return the constant value
/// of `keccak256(bytes(name()))` if `name()` will never change.
function _constantNameHash() internal view virtual returns (bytes32 result) {}
/// @dev If you need a different value, override this function.
function _versionHash() internal view virtual returns (bytes32 result) {
result = _DEFAULT_VERSION_HASH;
}
/// @dev For inheriting contracts to increment the nonce.
function _incrementNonce(address owner) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
sstore(nonceSlot, add(1, sload(nonceSlot)))
}
}
/// @dev Returns the current nonce for `owner`.
/// This value is used to compute the signature for EIP-2612 permit.
function nonces(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Compute the nonce slot and load its value.
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
/// authorized by a signed approval by `owner`.
///
/// Emits a {Approval} event.
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && value != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
// Revert if the block timestamp is greater than `deadline`.
if gt(timestamp(), deadline) {
mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
revert(0x1c, 0x04)
}
let m := mload(0x40) // Grab the free memory pointer.
// Clean the upper 96 bits.
owner := shr(96, shl(96, owner))
spender := shr(96, shl(96, spender))
// Compute the nonce slot and load its value.
mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
let nonceValue := sload(nonceSlot)
// Prepare the domain separator.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
mstore(0x2e, keccak256(m, 0xa0))
// Prepare the struct hash.
mstore(m, _PERMIT_TYPEHASH)
mstore(add(m, 0x20), owner)
mstore(add(m, 0x40), spender)
mstore(add(m, 0x60), value)
mstore(add(m, 0x80), nonceValue)
mstore(add(m, 0xa0), deadline)
mstore(0x4e, keccak256(m, 0xc0))
// Prepare the ecrecover calldata.
mstore(0x00, keccak256(0x2c, 0x42))
mstore(0x20, and(0xff, v))
mstore(0x40, r)
mstore(0x60, s)
let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20)
// If the ecrecover fails, the returndatasize will be 0x00,
// `owner` will be checked if it equals the hash at 0x00,
// which evaluates to false (i.e. 0), and we will revert.
// If the ecrecover succeeds, the returndatasize will be 0x20,
// `owner` will be compared against the returned address at 0x20.
if iszero(eq(mload(returndatasize()), owner)) {
mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
revert(0x1c, 0x04)
}
// Increment and store the updated nonce.
sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
// Compute the allowance slot and store the value.
// The `owner` is already at slot 0x20.
mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
sstore(keccak256(0x2c, 0x34), value)
// Emit the {Approval} event.
log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Grab the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
result := keccak256(m, 0xa0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `amount` tokens to `to`, increasing the total supply.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 amount) internal virtual {
_beforeTokenTransfer(address(0), to, amount);
/// @solidity memory-safe-assembly
assembly {
let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
let totalSupplyAfter := add(totalSupplyBefore, amount)
// Revert if the total supply overflows.
if lt(totalSupplyAfter, totalSupplyBefore) {
mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
revert(0x1c, 0x04)
}
// Store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
}
_afterTokenTransfer(address(0), to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Burns `amount` tokens from `from`, reducing the total supply.
///
/// Emits a {Transfer} event.
function _burn(address from, uint256 amount) internal virtual {
_beforeTokenTransfer(from, address(0), amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, from)
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Subtract and store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
// Emit the {Transfer} event.
mstore(0x00, amount)
log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
}
_afterTokenTransfer(from, address(0), amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Moves `amount` of tokens from `from` to `to`.
function _transfer(address from, address to, uint256 amount) internal virtual {
_beforeTokenTransfer(from, to, amount);
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
_afterTokenTransfer(from, to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL ALLOWANCE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite.
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and load its value.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
}
/// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
///
/// Emits a {Approval} event.
function _approve(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
let owner_ := shl(96, owner)
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any transfer of tokens.
/// This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/// @dev Hook that is called after any transfer of tokens.
/// This includes minting and burning.
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PERMIT2 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether to fix the Permit2 contract's allowance at infinity.
///
/// This value should be kept constant after contract initialization,
/// or else the actual allowance values may not match with the {Approval} events.
/// For best performance, return a compile-time constant for zero-cost abstraction.
function _givePermit2InfiniteAllowance() internal view virtual returns (bool) {
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./IERC20Unlocker.sol";
/// @title IERC20Lockable - Interface for a lockable token account.
/// @notice A token holder can lock their account, preventing any transfers from the account.
/// An unlocker contract is able to unlock the account. The unlocker contract is expected to
/// implement the `IERC20Unlocker` interface.
/// Used mainly for staking contracts that don't require transferring the token into the contract.
interface IERC20Lockable {
event Lock(address indexed account, IERC20Unlocker indexed unlocker);
event Unlock(address indexed account, IERC20Unlocker indexed unlocker);
/// @dev Error when calling lock() and the account is already locked.
error AlreadyLocked();
/// @dev Error when calling unlock() and the account is already unlocked.
error AlreadyUnlocked();
/// @dev Error when the caller is not the unlocker of the account.
error NotUnlocker();
/// @dev Error when trasferring tokens from a locked account.
error AccountLocked();
/// @notice Called by a token holder to lock their account. Once locked an account
/// can no longer transfer tokens until it's been unlocked. Only `unlocker` has the
/// ability to unlock the account. Reverts if the account is already locked.
/// @dev `unlocker` will receive the data via a `lockCallback()` call from this contract.
/// @param unlocker The address that will be able to unlock the account.
/// @param data Additional data with no specified format.
function lock(IERC20Unlocker unlocker, bytes calldata data) external;
/// @notice Called by an unlocker contract to unlock an account.
/// Reverts if the caller is not the unlocker of the account, or if
/// the account is not locked.
/// @param account The account to unlock.
function unlock(address account) external;
/// @notice Returns true if the account is locked, false otherwise.
/// @param account The account to check.
/// @return True if the account is locked, false otherwise.
function isLocked(address account) external view returns (bool);
/// @notice Returns the unlocker of the account. Be aware that the unlocker
/// is not set to 0 after the account has been unlocked, so the caller should
/// use this function in combination with `isLocked()`.
/// @param account The account whose unlocker is to be returned.
/// @return unlocker The unlocker of the account.
function unlockerOf(address account) external view returns (IERC20Unlocker unlocker);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title IERC20Unlocker - Interface for an unlocker contract for `IERC20Lockable`.
/// @notice An unlocker contract is able to unlock accounts that have been locked by a `IERC20Lockable` contract.
/// The unlocker contract is expected to implement the `IERC20Unlocker` interface.
interface IERC20Unlocker {
/// @notice Called when an account calls `IERC20Lockable.lock()` and specifies this contract as the unlocker.
/// @param account The account that called `IERC20Lockable.lock()`.
/// @param balance The balance of the account after the lock.
/// @param data The data passed to `IERC20Lockable.lock()`.
function lockCallback(address account, uint256 balance, bytes calldata data) external;
/// @notice Called when a locked account with this contract as the unlocker receives tokens.
/// @param account The account that received tokens.
/// @param receiveAmount The amount of tokens received.
function lockedUserReceiveCallback(address account, uint256 receiveAmount) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.4;
import {RushPoolId} from "../types/RushPoolId.sol";
import {RushPoolKey} from "../types/RushPoolKey.sol";
import {RecurPoolId} from "../types/RecurPoolId.sol";
import {RecurPoolKey} from "../types/RecurPoolKey.sol";
import {IERC20Unlocker} from "../external/IERC20Unlocker.sol";
import {IERC20Lockable} from "../external/IERC20Lockable.sol";
/// @title MasterBunni
/// @notice MasterBunni is a contract that incentivizes stakers in multiple pools.
/// It uses stake tokens that are IERC20Lockable.
/// @author zefram.eth
interface IMasterBunni is IERC20Unlocker {
error MasterBunni__AmountTooLarge();
error MasterBunni__RewardTooSmall();
error MasterBunni__InvalidRecipient();
event DepositIncentive(
address indexed sender,
address indexed incentiveToken,
address indexed recipient,
RushIncentiveParams[] params,
uint256 totalIncentiveAmount
);
event WithdrawIncentive(
address indexed sender,
address indexed incentiveToken,
address indexed recipient,
RushIncentiveParams[] params,
uint256 totalWithdrawnAmount
);
event RefundIncentive(
address indexed sender,
address indexed incentiveToken,
address indexed recipient,
RushPoolKey[] keys,
uint256 totalRefundAmount
);
event IncentivizeRecurPool(
address indexed sender,
address indexed incentiveToken,
RecurIncentiveParams[] params,
uint256 totalIncentiveAmount
);
event JoinRushPool(address indexed sender, RushPoolKey key);
event ExitRushPool(address indexed sender, RushPoolKey key);
event JoinRecurPool(address indexed sender, RecurPoolKey key);
event ExitRecurPool(address indexed sender, RecurPoolKey key);
event Unlock(address indexed sender, IERC20Lockable indexed stakeToken);
event ClaimRushPoolReward(
address indexed sender,
address indexed incentiveToken,
address indexed recipient,
uint256 claimableReward,
RushPoolKey key
);
event ClaimRecurPoolReward(
address indexed sender,
address indexed incentiveToken,
address indexed recipient,
uint256 reward,
RecurPoolKey key
);
/// @member stakeAmount The amount of stake tokens staked.
/// @member stakeXTimeStored The cumulativestake x time value since the last stake amount update.
/// @member lastStakeAmountUpdateTimestamp The timestamp of the last stake amount update in seconds. Must be at most the end timestamp of the program.
struct RushStakeState {
uint256 stakeAmount;
uint256 stakeXTimeStored;
uint256 lastStakeAmountUpdateTimestamp;
}
/// @member lastUpdateTime The last Unix timestamp (in seconds) when rewardPerTokenStored was updated
/// @member periodFinish The Unix timestamp (in seconds) at which the current reward period ends
/// @member rewardRate The per-second rate at which rewardPerToken increases
/// @member rewardPerTokenStored The last stored rewardPerToken value
/// @member totalSupply The total tokens staked in the pool
/// @member zeroStakeRewardAccrued The reward distributed during periods where the total stake was zero in the current duration
/// @member balanceOf The amount of tokens staked by an account
/// @member userRewardPerTokenPaid The rewardPerToken value when an account last staked/withdrew/withdrew rewards
/// @member rewards The earned() value when an account last staked/withdrew/withdrew rewards
struct RecurPoolState {
uint64 lastUpdateTime;
uint64 periodFinish;
uint256 rewardRate;
uint256 rewardPerTokenStored;
uint256 totalSupply;
uint256 zeroStakeRewardAccrued;
mapping(address => uint256) balanceOf;
mapping(address => uint256) userRewardPerTokenPaid;
mapping(address => uint256) rewards;
}
/// @member key The RushPoolKey of the RushPool.
/// @member incentiveAmount The amount of incentive tokens to deposit into the pool.
struct RushIncentiveParams {
RushPoolKey key;
uint256 incentiveAmount;
}
/// @member key The RecurPoolKey of the RecurPool.
/// @member incentiveAmount The amount of incentive tokens to deposit into the pool.
struct RecurIncentiveParams {
RecurPoolKey key;
uint256 incentiveAmount;
}
/// @member incentiveToken The incentive token to claim.
/// @member keys The list of RushPools to claim the incentives for.
struct RushClaimParams {
address incentiveToken;
RushPoolKey[] keys;
}
/// @member incentiveToken The incentive token to claim.
/// @member keys The list of RecurPools to claim the incentives for.
struct RecurClaimParams {
address incentiveToken;
RecurPoolKey[] keys;
}
/// @member rushKeys The list of RushPools to stake into.
/// @member recurKeys The list of RecurPools to stake into.
struct LockCallbackData {
RushPoolKey[] rushKeys;
RecurPoolKey[] recurKeys;
}
/// -----------------------------------------------------------------------
/// Getters
/// -----------------------------------------------------------------------
/// @notice Returns the number of incentive pools a user has staked a stake token in.
/// @dev Used to check if a user can unlock a stake token.
/// @param user The address of the user.
/// @param stakeToken The stake token to check.
/// @return The number of incentive pools a user has staked a stake token in.
function userPoolCounts(address user, IERC20Lockable stakeToken) external view returns (uint256);
/// @notice Returns the global stake state of a RushPool.
/// @param id The RushPoolId of the RushPool.
/// @return stakeAmount The amount of stake tokens staked.
/// @return stakeXTimeStored The cumulativestake x time value since the last stake amount update.
/// @return lastStakeAmountUpdateTimestamp The timestamp of the last stake amount update in seconds. Must be at most the end timestamp of the program.
function rushPoolStates(RushPoolId id)
external
view
returns (uint256 stakeAmount, uint256 stakeXTimeStored, uint256 lastStakeAmountUpdateTimestamp);
/// @notice Returns the amount of incentive tokens deposited into a RushPool.
/// @param id The RushPoolId of the RushPool.
/// @param incentiveToken The incentive token to check.
/// @return The amount of incentive tokens deposited into the RushPool.
function rushPoolIncentiveAmounts(RushPoolId id, address incentiveToken) external view returns (uint256);
/// @notice Returns the amount of incentive tokens deposited by an address into a RushPool.
/// @param id The RushPoolId of the RushPool.
/// @param incentiveToken The incentive token to check.
/// @param depositor The address to check.
/// @return The amount of incentive tokens deposited by the address into the RushPool.
function rushPoolIncentiveDeposits(RushPoolId id, address incentiveToken, address depositor)
external
view
returns (uint256);
/// @notice Returns the user's stake state in a RushPool.
/// @param id The RushPoolId of the RushPool.
/// @param user The address of the user.
/// @return stakeAmount The amount of stake tokens staked.
/// @return stakeXTimeStored The cumulativestake x time value since the last stake amount update.
/// @return lastStakeAmountUpdateTimestamp The timestamp of the last stake amount update in seconds. Must be at most the end timestamp of the program.
function rushPoolUserStates(RushPoolId id, address user)
external
view
returns (uint256 stakeAmount, uint256 stakeXTimeStored, uint256 lastStakeAmountUpdateTimestamp);
/// @notice Returns the amount of incentive tokens claimed by a user in a RushPool.
/// @param id The RushPoolId of the RushPool.
/// @param user The address of the user.
/// @param incentiveToken The incentive token to check.
/// @return The amount of incentive tokens claimed by the user in the RushPool.
function rushPoolUserRewardPaid(RushPoolId id, address user, address incentiveToken)
external
view
returns (uint256);
/// @notice Returns the global state of a RecurPool.
/// @param id The RecurPoolId of the RecurPool.
/// @return lastUpdateTime The last Unix timestamp (in seconds) when rewardPerTokenStored was updated
/// @return periodFinish The Unix timestamp (in seconds) at which the current reward period ends
/// @return rewardRate The per-second rate at which rewardPerToken increases
/// @return rewardPerTokenStored The last stored rewardPerToken value
/// @return totalSupply The total tokens staked in the pool
/// @return zeroStakeRewardAccrued The reward distributed during periods where the total stake was zero in the current duration
function recurPoolStates(RecurPoolId id)
external
view
returns (
uint64 lastUpdateTime,
uint64 periodFinish,
uint256 rewardRate,
uint256 rewardPerTokenStored,
uint256 totalSupply,
uint256 zeroStakeRewardAccrued
);
/// @notice Returns the amount of tokens staked by an address in a RecurPool.
/// @param id The RecurPoolId of the RecurPool.
/// @param user The address of the user.
/// @return The amount of tokens staked by the user in the RecurPool.
function recurPoolStakeBalanceOf(RecurPoolId id, address user) external view returns (uint256);
/// @notice Returns the rewardPerTokenPaid value of an address in a RecurPool.
/// @param id The RecurPoolId of the RecurPool.
/// @param user The address of the user.
/// @return The rewardPerTokenPaid value of the user in the RecurPool.
function recurPoolUserRewardPerTokenPaid(RecurPoolId id, address user) external view returns (uint256);
/// @notice Returns the accumulated rewards of an address in a RecurPool.
/// @param id The RecurPoolId of the RecurPool.
/// @param user The address of the user.
/// @return The accumulated rewards of the user in the RecurPool.
function recurPoolRewards(RecurPoolId id, address user) external view returns (uint256);
/// @notice Returns the amount of claimable reward for a user in a RushPool.
/// @param key The RushPoolKey of the RushPool.
/// @param user The address of the user.
/// @param incentiveToken The incentive token to check.
/// @return claimableReward The amount of claimable reward for the user in the RushPool.
function getRushPoolClaimableReward(RushPoolKey calldata key, address user, address incentiveToken)
external
view
returns (uint256 claimableReward);
/// @notice Returns the amount of claimable reward for a user in a RecurPool.
/// @param key The RecurPoolKey of the RecurPool.
/// @param user The address of the user.
/// @return claimableReward The amount of claimable reward for the user in the RecurPool.
function getRecurPoolClaimableReward(RecurPoolKey calldata key, address user)
external
view
returns (uint256 claimableReward);
/// @notice Returns true if the key is valid.
/// @param key The RushPoolKey or RecurPoolKey to check.
/// @return isValid True if the key is valid, false otherwise.
function isValidRushPoolKey(RushPoolKey calldata key) external pure returns (bool isValid);
/// @notice Returns true if the key is valid.
/// @param key The RushPoolKey or RecurPoolKey to check.
/// @return isValid True if the key is valid, false otherwise.
function isValidRecurPoolKey(RecurPoolKey calldata key) external pure returns (bool isValid);
/// -----------------------------------------------------------------------
/// Incentivizer actions
/// -----------------------------------------------------------------------
/// @notice Deposits an incentive token to a list of RushPools. Should be called before the RushPools are active.
/// If one of the RushPools is already active, the incentive will not be pulled from the caller or deposited into the RushPool.
/// @param params The list of RushPools to deposit the incentive into and the amount to deposit.
/// @param incentiveToken The incentive token to deposit.
/// @param recipient The address that will receive the right to withdraw the incentive tokens.
/// @return totalIncentiveAmount The total amount of incentive tokens deposited.
function depositIncentive(RushIncentiveParams[] calldata params, address incentiveToken, address recipient)
external
returns (uint256 totalIncentiveAmount);
/// @notice Withdraws an incentive token from a list of RushPools. Should be called before the RushPools are active.
/// If one of the RushPools is already active, the corresponding incentive will not be withdrawn from.
/// @param params The list of RushPools to withdraw the incentive from and the amount to withdraw.
/// @param incentiveToken The incentive token to withdraw.
/// @param recipient The address that will receive the withdrawn incentive tokens.
/// @return totalWithdrawnAmount The total amount of incentive tokens withdrawn.
function withdrawIncentive(RushIncentiveParams[] calldata params, address incentiveToken, address recipient)
external
returns (uint256 totalWithdrawnAmount);
/// @notice Refund unused incentive tokens deposited by msg.sender. Should be called after the RushPools are over.
/// @param params The list of RushPools to refund the incentive into and the incentive tokens to refund.
/// @param recipient The address that will receive the refunded incentive tokens.
function refundIncentive(RushClaimParams[] calldata params, address recipient) external;
/// @notice Incentivizes a list of RecurPools. Transfers incentive tokens from msgSender to this contract.
/// @param params The list of RecurPools to incentivize and the incentive amounts.
/// @param incentiveToken The incentive token to use.
/// @return totalIncentiveAmount The total incentive amount.
function incentivizeRecurPool(RecurIncentiveParams[] calldata params, address incentiveToken)
external
returns (uint256 totalIncentiveAmount);
/// -----------------------------------------------------------------------
/// Staker actions
/// -----------------------------------------------------------------------
/// @notice Joins a list of RushPools. Can join a pool where the user has existing stake if more capacity has opened up.
/// msg.sender should already have locked the stake tokens before calling this function.
/// @param keys The list of RushPools to join.
function joinRushPool(RushPoolKey[] calldata keys) external;
/// @notice Exits a list of RushPools.
/// @param keys The list of RushPools to exit.
function exitRushPool(RushPoolKey[] calldata keys) external;
/// @notice Joins a list of RecurPools. msg.sender should already have locked the stake tokens before calling this function.
/// @param keys The list of RecurPools to join.
function joinRecurPool(RecurPoolKey[] calldata keys) external;
/// @notice Exits a list of RecurPools.
/// @param keys The list of RecurPools to exit.
function exitRecurPool(RecurPoolKey[] calldata keys) external;
/// @notice Unlocks a list of stake tokens that msg.sender has locked.
/// A stake token is ignored if the user didn't unstake it from all RushPools
/// or if this contract is not the msg.sender's unlocker.
/// @param stakeTokens The list of stake tokens to unlock.
function unlock(IERC20Lockable[] calldata stakeTokens) external;
/// @notice Claims accrued incentives for a list of RushPools that msg.sender has staked in.
/// @param params The list of RushPools to claim the incentives for and the incentive tokens to claim.
/// @param recipient The address that will receive the claimed incentive tokens.
function claimRushPool(RushClaimParams[] calldata params, address recipient) external;
/// @notice Claims accrued incentives for a list of RecurPools that msg.sender has staked in.
/// @param params The list of RecurPools to claim the incentives for and the incentive tokens to claim.
/// @param recipient The address that will receive the claimed incentive tokens.
function claimRecurPool(RecurClaimParams[] calldata params, address recipient) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @title LibMulticaller
* @author vectorized.eth
* @notice Library to read the `msg.sender` of the multicaller with sender contract.
*
* @dev Note:
* The functions in this library do NOT guard against reentrancy.
* A single transaction can recurse through different Multicallers
* (e.g. `MulticallerWithSender -> contract -> MulticallerWithSigner -> contract`).
*
* Think of these functions like `msg.sender`.
*
* If your contract `C` can handle reentrancy safely with plain old `msg.sender`
* for any `A -> C -> B -> C`, you should be fine substituting `msg.sender` with these functions.
*/
library LibMulticaller {
/**
* @dev The address of the multicaller contract.
*/
address internal constant MULTICALLER = 0x0000000000002Bdbf1Bf3279983603Ec279CC6dF;
/**
* @dev The address of the multicaller with sender contract.
*/
address internal constant MULTICALLER_WITH_SENDER = 0x00000000002Fd5Aeb385D324B580FCa7c83823A0;
/**
* @dev The address of the multicaller with signer contract.
*/
address internal constant MULTICALLER_WITH_SIGNER = 0x000000000000D9ECebf3C23529de49815Dac1c4c;
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`.
*/
function multicallerSender() internal view returns (address result) {
return at(MULTICALLER_WITH_SENDER);
}
/**
* @dev Returns the signer of `aggregateWithSigner` on `MULTICALLER_WITH_SIGNER`.
*/
function multicallerSigner() internal view returns (address result) {
return at(MULTICALLER_WITH_SIGNER);
}
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SENDER`.
* Otherwise, returns `msg.sender`.
*/
function sender() internal view returns (address result) {
return resolve(MULTICALLER_WITH_SENDER);
}
/**
* @dev Returns the caller of `aggregateWithSigner` on `MULTICALLER_WITH_SIGNER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SIGNER`.
* Otherwise, returns `msg.sender`.
*/
function signer() internal view returns (address) {
return resolve(MULTICALLER_WITH_SIGNER);
}
/**
* @dev Returns the caller or signer at `a`.
* @param a The multicaller with sender / signer.
*/
function at(address a) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x00)
if iszero(staticcall(gas(), a, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
result := mload(0x00)
}
}
/**
* @dev Returns the caller or signer at `a`, if the caller is `a`.
* @param a The multicaller with sender / signer.
*/
function resolve(address a) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, caller())
if eq(caller(), a) {
if iszero(staticcall(gas(), a, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
}
result := mload(0x00)
}
}
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SENDER`.
* Returns the signer of `aggregateWithSigner` on `MULTICALLER_WITH_SIGNER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SIGNER`.
* Otherwise, returns `msg.sender`.
*/
function senderOrSigner() internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, caller())
let withSender := MULTICALLER_WITH_SENDER
if eq(caller(), withSender) {
if iszero(staticcall(gas(), withSender, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
}
let withSigner := MULTICALLER_WITH_SIGNER
if eq(caller(), withSigner) {
if iszero(staticcall(gas(), withSigner, codesize(), 0x00, 0x00, 0x20)) {
revert(codesize(), codesize()) // For better gas estimation.
}
}
result := mload(0x00)
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.4;
import {LibMulticaller} from "multicaller/LibMulticaller.sol";
import {ERC20} from "solady/tokens/ERC20.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {RushPoolId} from "./types/RushPoolId.sol";
import {RushPoolKey} from "./types/RushPoolKey.sol";
import {RecurPoolId} from "./types/RecurPoolId.sol";
import {RecurPoolKey} from "./types/RecurPoolKey.sol";
import {ReentrancyGuard} from "./lib/ReentrancyGuard.sol";
import {IMasterBunni} from "./interfaces/IMasterBunni.sol";
import {IERC20Unlocker} from "./external/IERC20Unlocker.sol";
import {IERC20Lockable} from "./external/IERC20Lockable.sol";
contract MasterBunni is IMasterBunni, ReentrancyGuard {
using FixedPointMathLib for *;
using SafeTransferLib for address;
uint256 internal constant PRECISION = 1e36;
uint256 internal constant MAX_DURATION = 36500 days; // needed to avoid block.timestamp + duration overflowing uint64
uint256 internal constant REWARD_RATE_PRECISION = 1e6;
uint256 internal constant PRECISION_DIV_REWARD_RATE_PRECISION = PRECISION / REWARD_RATE_PRECISION;
mapping(address user => mapping(IERC20Lockable stakeToken => uint256)) public userPoolCounts;
mapping(RushPoolId id => RushStakeState) public rushPoolStates;
mapping(RushPoolId id => mapping(address incentiveToken => uint256)) public rushPoolIncentiveAmounts;
mapping(RushPoolId id => mapping(address incentiveToken => mapping(address depositor => uint256))) public
rushPoolIncentiveDeposits;
mapping(RushPoolId id => mapping(address user => RushStakeState)) public rushPoolUserStates;
mapping(RushPoolId id => mapping(address user => mapping(address incentiveToken => uint256))) public
rushPoolUserRewardPaid;
mapping(RecurPoolId id => RecurPoolState) public recurPoolStates;
/// -----------------------------------------------------------------------
/// Incentivizer actions
/// -----------------------------------------------------------------------
/// @inheritdoc IMasterBunni
function depositIncentive(RushIncentiveParams[] calldata params, address incentiveToken, address recipient)
external
nonReentrant
returns (uint256 totalIncentiveAmount)
{
if (recipient == address(0)) revert MasterBunni__InvalidRecipient();
address msgSender = LibMulticaller.senderOrSigner();
// record incentive in each pool
for (uint256 i; i < params.length; i++) {
if (
!isValidRushPoolKey(params[i].key) || block.timestamp >= params[i].key.startTimestamp
|| params[i].incentiveAmount == 0
) {
// key is invalid or program is already active or zero incentive amount, skip
continue;
}
// sum up incentive amount
totalIncentiveAmount += params[i].incentiveAmount;
RushPoolId id = params[i].key.toId();
// add incentive to pool
rushPoolIncentiveAmounts[id][incentiveToken] += params[i].incentiveAmount;
// add incentive to depositor
rushPoolIncentiveDeposits[id][incentiveToken][recipient] += params[i].incentiveAmount;
}
// transfer incentive tokens to this contract
if (totalIncentiveAmount != 0) {
incentiveToken.safeTransferFrom2(msgSender, address(this), totalIncentiveAmount);
}
// emit event
emit DepositIncentive(msgSender, incentiveToken, recipient, params, totalIncentiveAmount);
}
/// @inheritdoc IMasterBunni
function withdrawIncentive(RushIncentiveParams[] calldata params, address incentiveToken, address recipient)
external
nonReentrant
returns (uint256 totalWithdrawnAmount)
{
if (recipient == address(0)) revert MasterBunni__InvalidRecipient();
address msgSender = LibMulticaller.senderOrSigner();
// subtract incentive tokens from each pool
for (uint256 i; i < params.length; i++) {
if (!isValidRushPoolKey(params[i].key) || block.timestamp >= params[i].key.startTimestamp) {
// key is invalid or program is already active, skip
continue;
}
// sum up withdrawn amount
totalWithdrawnAmount += params[i].incentiveAmount;
RushPoolId id = params[i].key.toId();
// subtract incentive from pool
rushPoolIncentiveAmounts[id][incentiveToken] -= params[i].incentiveAmount;
// subtract incentive from sender
rushPoolIncentiveDeposits[id][incentiveToken][msgSender] -= params[i].incentiveAmount;
}
// transfer incentive tokens to recipient
if (totalWithdrawnAmount != 0) {
incentiveToken.safeTransfer(recipient, totalWithdrawnAmount);
}
// emit event
emit WithdrawIncentive(msgSender, incentiveToken, recipient, params, totalWithdrawnAmount);
}
/// @inheritdoc IMasterBunni
function refundIncentive(RushClaimParams[] calldata params, address recipient) external nonReentrant {
if (recipient == address(0)) revert MasterBunni__InvalidRecipient();
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < params.length; i++) {
address incentiveToken = params[i].incentiveToken;
uint256 totalRefundAmount;
for (uint256 j; j < params[i].keys.length; j++) {
// the program should be over
RushPoolKey calldata key = params[i].keys[j];
if (!isValidRushPoolKey(key) || block.timestamp <= key.startTimestamp + key.programLength) {
continue;
}
// load state
RushPoolId id = key.toId();
RushStakeState memory poolState = rushPoolStates[id];
uint256 incentiveAmount = rushPoolIncentiveDeposits[id][incentiveToken][msgSender]; // the incentives added by msgSender
if (incentiveAmount == 0) {
continue;
}
// compute refund amount
// refund amount is the provided incentive amount minus the reward paid to stakers
uint256 stakeXTimeUpdated = _computeStakeXTime(
key, poolState.stakeXTimeStored, poolState.stakeAmount, poolState.lastStakeAmountUpdateTimestamp
);
uint256 rewardAccrued = incentiveAmount.mulDiv(stakeXTimeUpdated, PRECISION);
uint256 refundAmount = incentiveAmount - rewardAccrued;
// delete incentive deposit to mark the incentive as refunded
delete rushPoolIncentiveDeposits[id][incentiveToken][msgSender];
// accumulate refund amount
totalRefundAmount += refundAmount;
}
// transfer refund amount to recipient
if (totalRefundAmount != 0) {
incentiveToken.safeTransfer(recipient, totalRefundAmount);
}
// emit event
emit RefundIncentive(msgSender, incentiveToken, recipient, params[i].keys, totalRefundAmount);
}
}
/// @inheritdoc IMasterBunni
function incentivizeRecurPool(RecurIncentiveParams[] calldata params, address incentiveToken)
external
nonReentrant
returns (uint256 totalIncentiveAmount)
{
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < params.length; i++) {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (params[i].incentiveAmount == 0) continue;
RecurPoolKey calldata key = params[i].key;
if (!isValidRecurPoolKey(key)) continue;
// ensure incentiveToken matches key.rewardToken
if (incentiveToken != key.rewardToken) continue;
/// -----------------------------------------------------------------------
/// Storage loads
/// -----------------------------------------------------------------------
RecurPoolId id = key.toId();
RecurPoolState storage state = recurPoolStates[id];
uint64 lastUpdateTime = state.lastUpdateTime;
uint64 periodFinish = state.periodFinish;
uint256 rewardRate = state.rewardRate;
uint256 totalSupply = state.totalSupply;
uint256 zeroStakeRewardAccrued = state.zeroStakeRewardAccrued;
uint64 lastTimeRewardApplicable = block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish;
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue rewards
uint256 zeroStakeRewardIncrease;
if (totalSupply == 0) {
zeroStakeRewardIncrease = _zeroStakeRewardIncrease(lastTimeRewardApplicable, lastUpdateTime, rewardRate);
// only update the local var, need to update state later
zeroStakeRewardAccrued += zeroStakeRewardIncrease;
} else {
state.rewardPerTokenStored = _rewardPerToken(
state.rewardPerTokenStored, totalSupply, lastTimeRewardApplicable, lastUpdateTime, rewardRate
);
}
// record new reward
uint256 newRewardRate;
if (block.timestamp >= periodFinish) {
// current period is over
// add zero stake reward to the new reward
newRewardRate =
(params[i].incentiveAmount + zeroStakeRewardAccrued).mulDiv(REWARD_RATE_PRECISION, key.duration);
state.rewardRate = newRewardRate;
state.lastUpdateTime = uint64(block.timestamp);
state.periodFinish = uint64(block.timestamp + key.duration);
delete state.zeroStakeRewardAccrued; // clear the accrued zero stake period reward since it's used up
} else {
// period is still active
// add the new reward to the existing period
uint256 remaining = periodFinish - block.timestamp;
newRewardRate = rewardRate + params[i].incentiveAmount.mulDiv(REWARD_RATE_PRECISION, remaining);
// ensure reward rate is actually updated
if (newRewardRate == rewardRate) {
revert MasterBunni__RewardTooSmall();
}
state.rewardRate = newRewardRate;
state.lastUpdateTime = uint64(block.timestamp);
if (zeroStakeRewardIncrease != 0) {
// update accrued rewards during the zero stake period
state.zeroStakeRewardAccrued = zeroStakeRewardAccrued;
}
}
// prevent overflow when computing rewardPerToken
if (newRewardRate >= ((type(uint256).max / PRECISION_DIV_REWARD_RATE_PRECISION) / key.duration)) {
revert MasterBunni__AmountTooLarge();
}
totalIncentiveAmount += params[i].incentiveAmount;
}
// transfer incentive tokens from msgSender to this contract
if (totalIncentiveAmount != 0) {
incentiveToken.safeTransferFrom2(msgSender, address(this), totalIncentiveAmount);
}
// emit event
emit IncentivizeRecurPool(msgSender, incentiveToken, params, totalIncentiveAmount);
}
/// -----------------------------------------------------------------------
/// Staker actions
/// -----------------------------------------------------------------------
/// @inheritdoc IMasterBunni
function joinRushPool(RushPoolKey[] calldata keys) external nonReentrant {
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < keys.length; i++) {
// pool needs to be active
if (
!isValidRushPoolKey(keys[i]) || block.timestamp < keys[i].startTimestamp
|| block.timestamp > keys[i].startTimestamp + keys[i].programLength
) {
continue;
}
// msgSender should be locked with address(this) as the unlocker
if (
!keys[i].stakeToken.isLocked(msgSender)
|| keys[i].stakeToken.unlockerOf(msgSender) != IERC20Unlocker(address(this))
) {
continue;
}
RushPoolId id = keys[i].toId();
RushStakeState memory userState = rushPoolUserStates[id][msgSender];
RushStakeState memory poolState = rushPoolStates[id];
uint256 remainderStakeAmount = poolState.stakeAmount - userState.stakeAmount; // stake in pool minus the user's existing stake
uint256 stakeAmountUpdated;
{
uint256 balance = ERC20(address(keys[i].stakeToken)).balanceOf(msgSender);
stakeAmountUpdated = remainderStakeAmount + balance > keys[i].stakeCap
? keys[i].stakeCap - remainderStakeAmount
: balance;
}
// ensure there is capacity left and that we're increasing the user's stake
// the user's stake may increase when either
// 1) the user isn't staked yet or
// 2) the user staked & hit the stake cap but more capacity has opened up since then
if (stakeAmountUpdated == 0 || stakeAmountUpdated <= userState.stakeAmount) {
continue;
}
// update user state
// block.timestamp is at most endTimestamp
// since we already checked that the program is active
uint256 userStakeXTimeUpdated = _computeStakeXTime(
keys[i], userState.stakeXTimeStored, userState.stakeAmount, userState.lastStakeAmountUpdateTimestamp
);
rushPoolUserStates[id][msgSender] = RushStakeState({
stakeAmount: stakeAmountUpdated,
stakeXTimeStored: userStakeXTimeUpdated,
lastStakeAmountUpdateTimestamp: block.timestamp
});
if (userState.stakeAmount == 0) {
// user didn't have any stake in this pool before
unchecked {
++userPoolCounts[msgSender][keys[i].stakeToken];
}
}
// update pool state
// poolState.lastStakeAmountUpdateTimestamp might be 0 if the pool has never had stakers
// so we bound it by the start timestamp of the program
uint256 poolStakeXTimeUpdated = _computeStakeXTime(
keys[i],
poolState.stakeXTimeStored,
poolState.stakeAmount,
FixedPointMathLib.max(poolState.lastStakeAmountUpdateTimestamp, keys[i].startTimestamp)
);
rushPoolStates[id] = RushStakeState({
stakeAmount: remainderStakeAmount + stakeAmountUpdated,
stakeXTimeStored: poolStakeXTimeUpdated,
lastStakeAmountUpdateTimestamp: block.timestamp
});
// emit event
emit JoinRushPool(msgSender, keys[i]);
}
}
/// @inheritdoc IMasterBunni
function exitRushPool(RushPoolKey[] calldata keys) external nonReentrant {
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < keys.length; i++) {
// should be past pool's start timestamp
// if lockedUntilEnd is true, then the pool is locked until the end of the program
if (
!isValidRushPoolKey(keys[i]) || block.timestamp < keys[i].startTimestamp
|| (keys[i].lockedUntilEnd && block.timestamp <= keys[i].startTimestamp + keys[i].programLength)
) {
continue;
}
RushPoolId id = keys[i].toId();
RushStakeState memory userState = rushPoolUserStates[id][msgSender];
// user should have staked in the pool
if (userState.stakeAmount == 0) {
continue;
}
// update user state
uint256 endTimestamp = keys[i].startTimestamp + keys[i].programLength;
uint256 latestActiveTimestamp = FixedPointMathLib.min(block.timestamp, endTimestamp);
uint256 userStakeXTimeUpdated = _computeStakeXTime(
keys[i], userState.stakeXTimeStored, userState.stakeAmount, userState.lastStakeAmountUpdateTimestamp
);
rushPoolUserStates[id][msgSender] = RushStakeState({
stakeAmount: 0,
stakeXTimeStored: userStakeXTimeUpdated,
lastStakeAmountUpdateTimestamp: latestActiveTimestamp
});
unchecked {
--userPoolCounts[msgSender][keys[i].stakeToken];
}
// update pool state
RushStakeState memory poolState = rushPoolStates[id];
uint256 poolStakeXTimeUpdated = _computeStakeXTime(
keys[i], poolState.stakeXTimeStored, poolState.stakeAmount, poolState.lastStakeAmountUpdateTimestamp
);
rushPoolStates[id] = RushStakeState({
stakeAmount: poolState.stakeAmount - userState.stakeAmount,
stakeXTimeStored: poolStakeXTimeUpdated,
lastStakeAmountUpdateTimestamp: latestActiveTimestamp
});
// emit event
emit ExitRushPool(msgSender, keys[i]);
}
}
/// @inheritdoc IMasterBunni
function joinRecurPool(RecurPoolKey[] calldata keys) external nonReentrant {
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < keys.length; i++) {
RecurPoolKey calldata key = keys[i];
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
// key should be valid
if (!isValidRecurPoolKey(key)) continue;
// user should have non-zero balance
uint256 balance = ERC20(address(key.stakeToken)).balanceOf(msgSender);
if (balance == 0) {
continue;
}
// user's balance should be locked with this contract as the unlocker
if (
!key.stakeToken.isLocked(msgSender)
|| key.stakeToken.unlockerOf(msgSender) != IERC20Unlocker(address(this))
) {
continue;
}
/// -----------------------------------------------------------------------
/// Storage loads
/// -----------------------------------------------------------------------
RecurPoolId id = key.toId();
RecurPoolState storage state = recurPoolStates[id];
uint256 stakedBalance = state.balanceOf[msgSender];
// can't stake in a pool twice
if (balance <= stakedBalance) {
continue;
}
uint64 lastUpdateTime = state.lastUpdateTime;
uint64 periodFinish = state.periodFinish;
uint64 lastTimeRewardApplicable = block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish;
uint256 totalSupply = state.totalSupply;
uint256 rewardPerTokenUpdated = state.rewardPerTokenStored; // load the stored value in the var for now
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue rewards
if (totalSupply == 0) {
state.zeroStakeRewardAccrued +=
_zeroStakeRewardIncrease(lastTimeRewardApplicable, lastUpdateTime, state.rewardRate);
} else {
rewardPerTokenUpdated = _rewardPerToken(
rewardPerTokenUpdated, totalSupply, lastTimeRewardApplicable, lastUpdateTime, state.rewardRate
);
}
state.rewardPerTokenStored = rewardPerTokenUpdated;
state.lastUpdateTime = lastTimeRewardApplicable;
state.rewards[msgSender] = _earned(
state.userRewardPerTokenPaid[msgSender], stakedBalance, rewardPerTokenUpdated, state.rewards[msgSender]
);
state.userRewardPerTokenPaid[msgSender] = rewardPerTokenUpdated;
// stake
state.totalSupply = totalSupply - stakedBalance + balance;
state.balanceOf[msgSender] = balance;
// increment user pool count only if the previous staked balance is 0
if (stakedBalance == 0) {
unchecked {
++userPoolCounts[msgSender][key.stakeToken];
}
}
// emit event
emit JoinRecurPool(msgSender, keys[i]);
}
}
/// @inheritdoc IMasterBunni
function exitRecurPool(RecurPoolKey[] calldata keys) external nonReentrant {
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < keys.length; i++) {
RecurPoolKey calldata key = keys[i];
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
// key should be valid
if (!isValidRecurPoolKey(key)) continue;
RecurPoolId id = key.toId();
RecurPoolState storage state = recurPoolStates[id];
uint256 stakedBalance = state.balanceOf[msgSender];
// user should have staked in the pool
if (stakedBalance == 0) {
continue;
}
/// -----------------------------------------------------------------------
/// Storage loads
/// -----------------------------------------------------------------------
uint64 lastUpdateTime = state.lastUpdateTime;
uint64 periodFinish = state.periodFinish;
uint64 lastTimeRewardApplicable = block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish;
uint256 totalSupply = state.totalSupply;
uint256 rewardPerTokenUpdated = _rewardPerToken(
state.rewardPerTokenStored, totalSupply, lastTimeRewardApplicable, lastUpdateTime, state.rewardRate
);
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue rewards
// since we already checked stakedBalance != 0, we know totalSupply != 0
// so there's no need to update zeroStakeRewardAccrued
state.rewardPerTokenStored = rewardPerTokenUpdated;
state.lastUpdateTime = lastTimeRewardApplicable;
state.rewards[msgSender] = _earned(
state.userRewardPerTokenPaid[msgSender], stakedBalance, rewardPerTokenUpdated, state.rewards[msgSender]
);
state.userRewardPerTokenPaid[msgSender] = rewardPerTokenUpdated;
// remove stake
delete state.balanceOf[msgSender];
// total supply has 1:1 relationship with staked amounts
// so can't ever underflow
unchecked {
state.totalSupply = totalSupply - stakedBalance;
}
// decrement user pool count
unchecked {
--userPoolCounts[msgSender][key.stakeToken];
}
// emit event
emit ExitRecurPool(msgSender, keys[i]);
}
}
/// @inheritdoc IMasterBunni
function unlock(IERC20Lockable[] calldata stakeTokens) external nonReentrant {
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < stakeTokens.length; i++) {
// pool count should be 0
if (userPoolCounts[msgSender][stakeTokens[i]] != 0) {
continue;
}
// address(this) should be the unlocker of msgSender
// and msgSender should be locked
if (
stakeTokens[i].unlockerOf(msgSender) != IERC20Unlocker(address(this))
|| !stakeTokens[i].isLocked(msgSender)
) {
continue;
}
// unlock stake token
stakeTokens[i].unlock(msgSender);
// emit event
emit Unlock(msgSender, stakeTokens[i]);
}
}
/// @inheritdoc IMasterBunni
function claimRushPool(RushClaimParams[] calldata params, address recipient) external nonReentrant {
if (recipient == address(0)) revert MasterBunni__InvalidRecipient();
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < params.length; i++) {
address incentiveToken = params[i].incentiveToken;
uint256 totalClaimableAmount;
for (uint256 j; j < params[i].keys.length; j++) {
RushPoolKey calldata key = params[i].keys[j];
RushPoolId id = key.toId();
// key should be valid
if (!isValidRushPoolKey(key)) continue;
// load state
RushStakeState memory userState = rushPoolUserStates[id][msgSender];
uint256 incentiveAmount = rushPoolIncentiveAmounts[id][incentiveToken];
uint256 rewardPaid = rushPoolUserRewardPaid[id][msgSender][incentiveToken];
// compute claimable reward
uint256 stakeXTimeUpdated = _computeStakeXTime(
key, userState.stakeXTimeStored, userState.stakeAmount, userState.lastStakeAmountUpdateTimestamp
);
uint256 rewardAccrued = incentiveAmount.mulDiv(stakeXTimeUpdated, PRECISION);
uint256 claimableReward = rewardAccrued - rewardPaid;
// update claim state
rushPoolUserRewardPaid[id][msgSender][incentiveToken] = rewardAccrued;
// accumulate claimable reward
totalClaimableAmount += claimableReward;
if (claimableReward != 0) {
// emit event
emit ClaimRushPoolReward(msgSender, incentiveToken, recipient, claimableReward, params[i].keys[j]);
}
}
// transfer incentive tokens to user
if (totalClaimableAmount != 0) {
incentiveToken.safeTransfer(recipient, totalClaimableAmount);
}
}
}
/// @inheritdoc IMasterBunni
function claimRecurPool(RecurClaimParams[] calldata params, address recipient) external nonReentrant {
if (recipient == address(0)) revert MasterBunni__InvalidRecipient();
address msgSender = LibMulticaller.senderOrSigner();
for (uint256 i; i < params.length; i++) {
address incentiveToken = params[i].incentiveToken;
uint256 totalClaimableAmount;
for (uint256 j; j < params[i].keys.length; j++) {
RecurPoolKey calldata key = params[i].keys[j];
RecurPoolId id = key.toId();
// key should be valid
if (!isValidRecurPoolKey(key)) continue;
// incentiveToken should equal key.rewardToken
if (incentiveToken != key.rewardToken) continue;
/// -----------------------------------------------------------------------
/// Storage loads
/// -----------------------------------------------------------------------
// load state
RecurPoolState storage state = recurPoolStates[id];
uint64 lastUpdateTime = state.lastUpdateTime;
uint64 periodFinish = state.periodFinish;
uint64 lastTimeRewardApplicable =
block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish;
uint256 rewardRate = state.rewardRate;
uint256 totalSupply = state.totalSupply;
uint256 rewardPerTokenUpdated = state.rewardPerTokenStored; // load the stored value in the var for now
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue rewards
if (totalSupply == 0) {
state.zeroStakeRewardAccrued +=
_zeroStakeRewardIncrease(lastTimeRewardApplicable, lastUpdateTime, rewardRate);
} else {
rewardPerTokenUpdated = _rewardPerToken(
rewardPerTokenUpdated, totalSupply, lastTimeRewardApplicable, lastUpdateTime, rewardRate
);
}
uint256 reward = _earned(
state.userRewardPerTokenPaid[msgSender],
state.balanceOf[msgSender],
rewardPerTokenUpdated,
state.rewards[msgSender]
);
state.rewardPerTokenStored = rewardPerTokenUpdated;
state.lastUpdateTime = lastTimeRewardApplicable;
state.userRewardPerTokenPaid[msgSender] = rewardPerTokenUpdated;
if (reward != 0) {
// delete accrued rewards
delete state.rewards[msgSender];
// accumulate claimable amount
totalClaimableAmount += reward;
// emit event
emit ClaimRecurPoolReward(msgSender, incentiveToken, recipient, reward, params[i].keys[j]);
}
}
// transfer incentive tokens to user
if (totalClaimableAmount != 0) {
incentiveToken.safeTransfer(recipient, totalClaimableAmount);
}
}
}
/// -----------------------------------------------------------------------
/// Getters
/// -----------------------------------------------------------------------
/// @inheritdoc IMasterBunni
function getRushPoolClaimableReward(RushPoolKey calldata key, address user, address incentiveToken)
external
view
returns (uint256 claimableReward)
{
// no need to validate key since we just return 0 if it's invalid
// load state
RushPoolId id = key.toId();
RushStakeState memory userState = rushPoolUserStates[id][user];
uint256 incentiveAmount = rushPoolIncentiveAmounts[id][incentiveToken];
uint256 rewardPaid = rushPoolUserRewardPaid[id][user][incentiveToken];
// compute claimable reward
uint256 stakeXTimeUpdated = _computeStakeXTime(
key, userState.stakeXTimeStored, userState.stakeAmount, userState.lastStakeAmountUpdateTimestamp
);
uint256 rewardAccrued = incentiveAmount.mulDiv(stakeXTimeUpdated, PRECISION);
return rewardAccrued - rewardPaid;
}
/// @inheritdoc IMasterBunni
function getRecurPoolClaimableReward(RecurPoolKey calldata key, address user)
external
view
returns (uint256 claimableReward)
{
// no need to validate key since we just return 0 if it's invalid
RecurPoolId id = key.toId();
RecurPoolState storage state = recurPoolStates[id];
uint64 lastUpdateTime = state.lastUpdateTime;
uint64 periodFinish = state.periodFinish;
uint64 lastTimeRewardApplicable = block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish;
uint256 rewardPerTokenStored = state.rewardPerTokenStored;
uint256 totalSupply = state.totalSupply;
uint256 rewardPerTokenUpdated = totalSupply == 0
? rewardPerTokenStored
: _rewardPerToken(rewardPerTokenStored, totalSupply, lastTimeRewardApplicable, lastUpdateTime, state.rewardRate);
return _earned(
state.userRewardPerTokenPaid[user], state.balanceOf[user], rewardPerTokenUpdated, state.rewards[user]
);
}
/// @inheritdoc IMasterBunni
function recurPoolStakeBalanceOf(RecurPoolId id, address user) external view returns (uint256) {
return recurPoolStates[id].balanceOf[user];
}
/// @inheritdoc IMasterBunni
function recurPoolUserRewardPerTokenPaid(RecurPoolId id, address user) external view returns (uint256) {
return recurPoolStates[id].userRewardPerTokenPaid[user];
}
/// @inheritdoc IMasterBunni
function recurPoolRewards(RecurPoolId id, address user) external view returns (uint256) {
return recurPoolStates[id].rewards[user];
}
/// @inheritdoc IMasterBunni
function isValidRushPoolKey(RushPoolKey memory key) public pure returns (bool) {
return address(key.stakeToken) != address(0) && key.stakeCap != 0 && key.startTimestamp != 0
&& key.programLength != 0;
}
/// @inheritdoc IMasterBunni
function isValidRecurPoolKey(RecurPoolKey memory key) public pure returns (bool) {
return address(key.stakeToken) != address(0) && key.rewardToken != address(0) && key.duration != 0
&& key.duration <= MAX_DURATION;
}
/// -----------------------------------------------------------------------
/// Callbacks
/// -----------------------------------------------------------------------
/// @inheritdoc IERC20Unlocker
/// @dev Should initialize the user's stake position.
function lockCallback(address account, uint256 balance, bytes calldata data) external nonReentrant {
LockCallbackData memory callbackData = abi.decode(data, (LockCallbackData));
IERC20Lockable stakeToken = IERC20Lockable(msg.sender);
for (uint256 i; i < callbackData.rushKeys.length; i++) {
RushPoolKey memory key = callbackData.rushKeys[i];
uint256 endTimestamp = key.startTimestamp + key.programLength;
// validate key
// - key should be valid
// - pool should be active
// - stakeToken of key should be msg.sender
if (
!isValidRushPoolKey(key) || key.stakeToken != stakeToken || block.timestamp < key.startTimestamp
|| block.timestamp > endTimestamp
) {
continue;
}
RushPoolId id = key.toId();
uint256 userStakeAmount = rushPoolUserStates[id][account].stakeAmount;
// can't stake in a pool twice
if (userStakeAmount != 0) {
continue;
}
RushStakeState memory poolState = rushPoolStates[id];
uint256 stakeAmount =
poolState.stakeAmount + balance > key.stakeCap ? key.stakeCap - poolState.stakeAmount : balance;
// ensure there is capacity left
if (stakeAmount == 0) {
continue;
}
// update user state
// leave stakeXTime unchanged since stakeAmount was zero since the last update
// block.timestamp is at most endTimestamp
// since we already checked that the program is active
rushPoolUserStates[id][account].stakeAmount = stakeAmount;
rushPoolUserStates[id][account].lastStakeAmountUpdateTimestamp = block.timestamp;
unchecked {
++userPoolCounts[account][key.stakeToken];
}
// update pool state
// poolState.lastStakeAmountUpdateTimestamp might be 0 if the pool has never had stakers
// so we bound it by the start timestamp of the program
uint256 stakeXTimeUpdated = _computeStakeXTime(
key,
poolState.stakeXTimeStored,
poolState.stakeAmount,
FixedPointMathLib.max(poolState.lastStakeAmountUpdateTimestamp, key.startTimestamp)
);
rushPoolStates[id] = RushStakeState({
stakeAmount: poolState.stakeAmount + stakeAmount,
stakeXTimeStored: stakeXTimeUpdated,
lastStakeAmountUpdateTimestamp: block.timestamp
});
// emit event
emit JoinRushPool(account, key);
}
for (uint256 i; i < callbackData.recurKeys.length; i++) {
RecurPoolKey memory key = callbackData.recurKeys[i];
// validate key
// - key should be valid
// - stakeToken of key should be msg.sender
if (!isValidRecurPoolKey(key) || key.stakeToken != stakeToken) {
continue;
}
/// -----------------------------------------------------------------------
/// Storage loads
/// -----------------------------------------------------------------------
RecurPoolId id = key.toId();
RecurPoolState storage state = recurPoolStates[id];
uint256 stakedBalance = state.balanceOf[account];
// can't stake in a pool twice
if (stakedBalance != 0) {
continue;
}
uint64 lastUpdateTime = state.lastUpdateTime;
uint64 periodFinish = state.periodFinish;
uint64 lastTimeRewardApplicable = block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish;
uint256 rewardRate = state.rewardRate;
uint256 totalSupply = state.totalSupply;
uint256 rewardPerTokenUpdated = state.rewardPerTokenStored; // load the stored value in the var for now
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue rewards
if (totalSupply == 0) {
state.zeroStakeRewardAccrued +=
_zeroStakeRewardIncrease(lastTimeRewardApplicable, lastUpdateTime, rewardRate);
} else {
rewardPerTokenUpdated = _rewardPerToken(
rewardPerTokenUpdated, totalSupply, lastTimeRewardApplicable, lastUpdateTime, rewardRate
);
}
// stakedBalance has been 0 so no need to update state.rewards[account]
state.rewardPerTokenStored = rewardPerTokenUpdated;
state.lastUpdateTime = lastTimeRewardApplicable;
state.userRewardPerTokenPaid[account] = rewardPerTokenUpdated;
// stake
state.totalSupply = totalSupply + balance;
state.balanceOf[account] = balance;
// increment user pool count
unchecked {
++userPoolCounts[account][key.stakeToken];
}
// emit event
emit JoinRecurPool(account, key);
}
}
/// @inheritdoc IERC20Unlocker
function lockedUserReceiveCallback(address account, uint256 receiveAmount) external {}
/// -----------------------------------------------------------------------
/// Internal utilities
/// -----------------------------------------------------------------------
/// @dev Computes the updated (normalized stake amount) x (normalized time since program start) value. This value is useful
/// since (stake x time) x (incentive amount) is the incentive amount accrued for the user / pool so far.
/// Example: If a user has staked 0.5 x stakeCap tokens for 0.3 x programLength seconds, the stake x time value is 0.15 which is
/// the proportion of the total incentive amount that the user has accrued so far.
/// @param key The rush pool key.
/// @param stakeXTimeStored The stake x time value stored in the state.
/// @param stakeAmount The stake amount of the user between the last update and now.
/// @param lastStakeAmountUpdateTimestamp The timestamp of the last update. Should be at most the end timestamp of the program.
/// @return The updated stake x time value.
function _computeStakeXTime(
RushPoolKey memory key,
uint256 stakeXTimeStored,
uint256 stakeAmount,
uint256 lastStakeAmountUpdateTimestamp
) internal view returns (uint256) {
if (block.timestamp < key.startTimestamp) {
return 0;
}
uint256 endTimestamp = key.startTimestamp + key.programLength;
uint256 timeElapsedSinceLastUpdate =
FixedPointMathLib.min(block.timestamp, endTimestamp) - lastStakeAmountUpdateTimestamp;
return stakeXTimeStored
+ PRECISION.mulDiv(stakeAmount, key.stakeCap).mulDiv(timeElapsedSinceLastUpdate, key.programLength);
}
function _earned(
uint256 userRewardPerTokenPaid,
uint256 accountBalance,
uint256 rewardPerToken,
uint256 accountRewards
) internal pure returns (uint256) {
return FixedPointMathLib.fullMulDiv(accountBalance, rewardPerToken - userRewardPerTokenPaid, PRECISION)
+ accountRewards;
}
/// @dev Need to ensure totalSupply != 0 before calling this function
function _rewardPerToken(
uint256 rewardPerTokenStored,
uint256 totalSupply,
uint256 lastTimeRewardApplicable,
uint256 lastUpdateTime,
uint256 rewardRate
) internal pure returns (uint256) {
// mulDiv won't overflow since we check that rewardRate is less than (type(uint256).max / PRECISION_DIV_REWARD_RATE_PRECISION / duration)
return rewardPerTokenStored
+ FixedPointMathLib.mulDiv(
(lastTimeRewardApplicable - lastUpdateTime) * PRECISION_DIV_REWARD_RATE_PRECISION, rewardRate, totalSupply
);
}
function _zeroStakeRewardIncrease(uint256 lastTimeRewardApplicable, uint256 lastUpdateTime, uint256 rewardRate)
internal
pure
returns (uint256)
{
return (lastTimeRewardApplicable - lastUpdateTime).mulDiv(rewardRate, REWARD_RATE_PRECISION);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.4;
import {RecurPoolKey} from "./RecurPoolKey.sol";
type RecurPoolId is bytes32;
library RecurPoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(key))
function toId(RecurPoolKey memory key) internal pure returns (RecurPoolId poolId) {
assembly ("memory-safe") {
// 0x60 represents the total size of the RecurPoolKey struct (3 slots of 32 bytes)
poolId := keccak256(key, 0x60)
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.4;
import {RecurPoolIdLibrary} from "./RecurPoolId.sol";
import {IERC20Lockable} from "../external/IERC20Lockable.sol";
using RecurPoolIdLibrary for RecurPoolKey global;
struct RecurPoolKey {
IERC20Lockable stakeToken;
address rewardToken;
uint256 duration;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.19;
abstract contract ReentrancyGuard {
error ReentrancyGuard__ReentrantCall();
uint256 private constant STATUS_SLOT = uint256(keccak256("STATUS")) - 1;
uint256 private constant NOT_ENTERED = 0;
uint256 private constant ENTERED = 1;
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() internal {
uint256 statusSlot = STATUS_SLOT;
uint256 status;
/// @solidity memory-safe-assembly
assembly {
status := tload(statusSlot)
}
if (status == ENTERED) revert ReentrancyGuard__ReentrantCall();
uint256 entered = ENTERED;
/// @solidity memory-safe-assembly
assembly {
tstore(statusSlot, entered)
}
}
function _nonReentrantAfter() internal {
uint256 statusSlot = STATUS_SLOT;
uint256 notEntered = NOT_ENTERED;
/// @solidity memory-safe-assembly
assembly {
tstore(statusSlot, notEntered)
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.4;
import {RushPoolKey} from "./RushPoolKey.sol";
type RushPoolId is bytes32;
library RushPoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(key))
function toId(RushPoolKey memory key) internal pure returns (RushPoolId poolId) {
assembly ("memory-safe") {
// 0xA0 represents the total size of the RushPoolKey struct (5 slots of 32 bytes)
poolId := keccak256(key, 0xA0)
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.4;
import {RushPoolIdLibrary} from "./RushPoolId.sol";
import {IERC20Lockable} from "../external/IERC20Lockable.sol";
using RushPoolIdLibrary for RushPoolKey global;
struct RushPoolKey {
IERC20Lockable stakeToken;
uint256 stakeCap;
uint256 startTimestamp;
uint256 programLength;
bool lockedUntilEnd;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
{
"compilationTarget": {
"src/MasterBunni.sol": "MasterBunni"
},
"evmVersion": "cancun",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 1000000
},
"remappings": [
":create3-factory/=lib/create3-factory/",
":ds-test/=lib/solmate/lib/ds-test/src/",
":forge-std/=lib/forge-std/src/",
":multicaller/=lib/multicaller/src/",
":solady/=lib/solady/src/",
":solmate/=lib/solmate/src/"
],
"viaIR": true
}
[{"inputs":[],"name":"MasterBunni__AmountTooLarge","type":"error"},{"inputs":[],"name":"MasterBunni__InvalidRecipient","type":"error"},{"inputs":[],"name":"MasterBunni__RewardTooSmall","type":"error"},{"inputs":[],"name":"ReentrancyGuard__ReentrantCall","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"incentiveToken","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"indexed":false,"internalType":"struct RecurPoolKey","name":"key","type":"tuple"}],"name":"ClaimRecurPoolReward","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"incentiveToken","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"claimableReward","type":"uint256"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"indexed":false,"internalType":"struct RushPoolKey","name":"key","type":"tuple"}],"name":"ClaimRushPoolReward","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"incentiveToken","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"components":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"incentiveAmount","type":"uint256"}],"indexed":false,"internalType":"struct IMasterBunni.RushIncentiveParams[]","name":"params","type":"tuple[]"},{"indexed":false,"internalType":"uint256","name":"totalIncentiveAmount","type":"uint256"}],"name":"DepositIncentive","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"indexed":false,"internalType":"struct RecurPoolKey","name":"key","type":"tuple"}],"name":"ExitRecurPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"indexed":false,"internalType":"struct RushPoolKey","name":"key","type":"tuple"}],"name":"ExitRushPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"incentiveToken","type":"address"},{"components":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"internalType":"struct RecurPoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"incentiveAmount","type":"uint256"}],"indexed":false,"internalType":"struct IMasterBunni.RecurIncentiveParams[]","name":"params","type":"tuple[]"},{"indexed":false,"internalType":"uint256","name":"totalIncentiveAmount","type":"uint256"}],"name":"IncentivizeRecurPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"indexed":false,"internalType":"struct RecurPoolKey","name":"key","type":"tuple"}],"name":"JoinRecurPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"indexed":false,"internalType":"struct RushPoolKey","name":"key","type":"tuple"}],"name":"JoinRushPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"incentiveToken","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"indexed":false,"internalType":"struct RushPoolKey[]","name":"keys","type":"tuple[]"},{"indexed":false,"internalType":"uint256","name":"totalRefundAmount","type":"uint256"}],"name":"RefundIncentive","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"}],"name":"Unlock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"incentiveToken","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"components":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"incentiveAmount","type":"uint256"}],"indexed":false,"internalType":"struct IMasterBunni.RushIncentiveParams[]","name":"params","type":"tuple[]"},{"indexed":false,"internalType":"uint256","name":"totalWithdrawnAmount","type":"uint256"}],"name":"WithdrawIncentive","type":"event"},{"inputs":[{"components":[{"internalType":"address","name":"incentiveToken","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"internalType":"struct RecurPoolKey[]","name":"keys","type":"tuple[]"}],"internalType":"struct IMasterBunni.RecurClaimParams[]","name":"params","type":"tuple[]"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claimRecurPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"incentiveToken","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey[]","name":"keys","type":"tuple[]"}],"internalType":"struct IMasterBunni.RushClaimParams[]","name":"params","type":"tuple[]"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claimRushPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"incentiveAmount","type":"uint256"}],"internalType":"struct IMasterBunni.RushIncentiveParams[]","name":"params","type":"tuple[]"},{"internalType":"address","name":"incentiveToken","type":"address"},{"internalType":"address","name":"recipient","type":"address"}],"name":"depositIncentive","outputs":[{"internalType":"uint256","name":"totalIncentiveAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"internalType":"struct RecurPoolKey[]","name":"keys","type":"tuple[]"}],"name":"exitRecurPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey[]","name":"keys","type":"tuple[]"}],"name":"exitRushPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"internalType":"struct RecurPoolKey","name":"key","type":"tuple"},{"internalType":"address","name":"user","type":"address"}],"name":"getRecurPoolClaimableReward","outputs":[{"internalType":"uint256","name":"claimableReward","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey","name":"key","type":"tuple"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"incentiveToken","type":"address"}],"name":"getRushPoolClaimableReward","outputs":[{"internalType":"uint256","name":"claimableReward","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"internalType":"struct RecurPoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"incentiveAmount","type":"uint256"}],"internalType":"struct IMasterBunni.RecurIncentiveParams[]","name":"params","type":"tuple[]"},{"internalType":"address","name":"incentiveToken","type":"address"}],"name":"incentivizeRecurPool","outputs":[{"internalType":"uint256","name":"totalIncentiveAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"internalType":"struct RecurPoolKey","name":"key","type":"tuple"}],"name":"isValidRecurPoolKey","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey","name":"key","type":"tuple"}],"name":"isValidRushPoolKey","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"address","name":"rewardToken","type":"address"},{"internalType":"uint256","name":"duration","type":"uint256"}],"internalType":"struct RecurPoolKey[]","name":"keys","type":"tuple[]"}],"name":"joinRecurPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey[]","name":"keys","type":"tuple[]"}],"name":"joinRushPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"lockCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"receiveAmount","type":"uint256"}],"name":"lockedUserReceiveCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"RecurPoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"user","type":"address"}],"name":"recurPoolRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"RecurPoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"user","type":"address"}],"name":"recurPoolStakeBalanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"RecurPoolId","name":"id","type":"bytes32"}],"name":"recurPoolStates","outputs":[{"internalType":"uint64","name":"lastUpdateTime","type":"uint64"},{"internalType":"uint64","name":"periodFinish","type":"uint64"},{"internalType":"uint256","name":"rewardRate","type":"uint256"},{"internalType":"uint256","name":"rewardPerTokenStored","type":"uint256"},{"internalType":"uint256","name":"totalSupply","type":"uint256"},{"internalType":"uint256","name":"zeroStakeRewardAccrued","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"RecurPoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"user","type":"address"}],"name":"recurPoolUserRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"incentiveToken","type":"address"},{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey[]","name":"keys","type":"tuple[]"}],"internalType":"struct IMasterBunni.RushClaimParams[]","name":"params","type":"tuple[]"},{"internalType":"address","name":"recipient","type":"address"}],"name":"refundIncentive","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"RushPoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"incentiveToken","type":"address"}],"name":"rushPoolIncentiveAmounts","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"RushPoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"incentiveToken","type":"address"},{"internalType":"address","name":"depositor","type":"address"}],"name":"rushPoolIncentiveDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"RushPoolId","name":"id","type":"bytes32"}],"name":"rushPoolStates","outputs":[{"internalType":"uint256","name":"stakeAmount","type":"uint256"},{"internalType":"uint256","name":"stakeXTimeStored","type":"uint256"},{"internalType":"uint256","name":"lastStakeAmountUpdateTimestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"RushPoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"incentiveToken","type":"address"}],"name":"rushPoolUserRewardPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"RushPoolId","name":"id","type":"bytes32"},{"internalType":"address","name":"user","type":"address"}],"name":"rushPoolUserStates","outputs":[{"internalType":"uint256","name":"stakeAmount","type":"uint256"},{"internalType":"uint256","name":"stakeXTimeStored","type":"uint256"},{"internalType":"uint256","name":"lastStakeAmountUpdateTimestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20Lockable[]","name":"stakeTokens","type":"address[]"}],"name":"unlock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"}],"name":"userPoolCounts","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"contract IERC20Lockable","name":"stakeToken","type":"address"},{"internalType":"uint256","name":"stakeCap","type":"uint256"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"programLength","type":"uint256"},{"internalType":"bool","name":"lockedUntilEnd","type":"bool"}],"internalType":"struct RushPoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"incentiveAmount","type":"uint256"}],"internalType":"struct IMasterBunni.RushIncentiveParams[]","name":"params","type":"tuple[]"},{"internalType":"address","name":"incentiveToken","type":"address"},{"internalType":"address","name":"recipient","type":"address"}],"name":"withdrawIncentive","outputs":[{"internalType":"uint256","name":"totalWithdrawnAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]