// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
// Common.sol
//
// Common mathematical functions needed by both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.
/*//////////////////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);
/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);
/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();
/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;
/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;
/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;
/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;
/*//////////////////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
//
// 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
// 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
// a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
// we know that `x & 0xFF` is also 1.
if (x & 0xFF00000000000000 > 0) {
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
}
if (x & 0xFF000000000000 > 0) {
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
}
if (x & 0xFF0000000000 > 0) {
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
}
if (x & 0xFF00000000 > 0) {
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
}
if (x & 0xFF000000 > 0) {
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
}
if (x & 0xFF0000 > 0) {
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
}
if (x & 0xFF00 > 0) {
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
}
if (x & 0xFF > 0) {
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
}
// In the code snippet below, two operations are executed simultaneously:
//
// 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
// accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
// 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
//
// The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
// integer part, $2^n$.
result *= UNIT;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
/// x >>= 128;
/// result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
// 2^128
assembly ("memory-safe") {
let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^64
assembly ("memory-safe") {
let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^32
assembly ("memory-safe") {
let factor := shl(5, gt(x, 0xFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^16
assembly ("memory-safe") {
let factor := shl(4, gt(x, 0xFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^8
assembly ("memory-safe") {
let factor := shl(3, gt(x, 0xFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^4
assembly ("memory-safe") {
let factor := shl(2, gt(x, 0xF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^2
assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
// 2^1
// No need to shift x any more.
assembly ("memory-safe") {
let factor := gt(x, 0x1)
result := or(result, factor)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
return prod0 / denominator;
}
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath_MulDiv_Overflow(x, y, denominator);
}
////////////////////////////////////////////////////////////////////////////
// 512 by 256 division
////////////////////////////////////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using the mulmod Yul instruction.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512-bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
// Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
// because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
// For more detail, see https://cs.stackexchange.com/q/138556/92363.
uint256 lpotdod = denominator & (~denominator + 1);
uint256 flippedLpotdod;
assembly ("memory-safe") {
// Factor powers of two out of denominator.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
// `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
// However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * flippedLpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
}
}
/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
/// x * y = MAX\_UINT256 * UNIT \\
/// (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
unchecked {
return prod0 / UNIT;
}
}
if (prod1 >= UNIT) {
revert PRBMath_MulDiv18_Overflow(x, y);
}
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(x, y, UNIT)
result :=
mul(
or(
div(sub(prod0, remainder), UNIT_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
),
UNIT_INVERSE
)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath_MulDivSigned_InputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 xAbs;
uint256 yAbs;
uint256 dAbs;
unchecked {
xAbs = x < 0 ? uint256(-x) : uint256(x);
yAbs = y < 0 ? uint256(-y) : uint256(y);
dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of x*y÷denominator. The result must fit in int256.
uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
if (resultAbs > uint256(type(int256).max)) {
revert PRBMath_MulDivSigned_Overflow(x, y);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly ("memory-safe") {
// "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
// If there are, the result should be negative. Otherwise, it should be positive.
unchecked {
result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
//
// We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
//
// $$
// msb(x) <= x <= 2*msb(x)$
// $$
//
// We write $msb(x)$ as $2^k$, and we get:
//
// $$
// k = log_2(x)
// $$
//
// Thus, we can write the initial inequality as:
//
// $$
// 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
// sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
// 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
// $$
//
// Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 2 ** 128) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 2 ** 64) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 2 ** 32) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 2 ** 16) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 2 ** 8) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 2 ** 4) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 2 ** 2) {
result <<= 1;
}
// At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
// most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision
// doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of
// precision into the expected uint128 result.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
// If x is not a perfect square, round the result toward zero.
uint256 roundedResult = x / result;
if (result >= roundedResult) {
result = roundedResult;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// 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 = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// 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 *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBAllowanceTerminal3_1 {
function useAllowanceOf(
uint256 projectId,
uint256 amount,
uint256 currency,
address token,
uint256 minReturnedTokens,
address payable beneficiary,
string calldata memo,
bytes calldata metadata
) external returns (uint256 netDistributedAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IJBPayDelegate3_1_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPayDelegate3_1_1.sol";
import {IJBFundingCycleDataSource3_1_1} from
"@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBFundingCycleDataSource3_1_1.sol";
import {IJBDirectory} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBDirectory.sol";
import {IJBController3_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBController3_1.sol";
import {IJBProjects} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBProjects.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IUniswapV3SwapCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import {IWETH9} from "./external/IWETH9.sol";
interface IJBBuybackDelegate is IJBPayDelegate3_1_1, IJBFundingCycleDataSource3_1_1, IUniswapV3SwapCallback {
/////////////////////////////////////////////////////////////////////
// Errors //
/////////////////////////////////////////////////////////////////////
error JuiceBuyback_MaximumSlippage();
error JuiceBuyback_InsufficientPayAmount();
error JuiceBuyback_NotEnoughTokensReceived();
error JuiceBuyback_NewSecondsAgoTooLow();
error JuiceBuyback_NoProjectToken();
error JuiceBuyback_PoolAlreadySet();
error JuiceBuyback_TransferFailed();
error JuiceBuyback_InvalidTwapSlippageTolerance();
error JuiceBuyback_InvalidTwapWindow();
error JuiceBuyback_Unauthorized();
/////////////////////////////////////////////////////////////////////
// Events //
/////////////////////////////////////////////////////////////////////
event BuybackDelegate_Swap(uint256 indexed projectId, uint256 amountIn, IUniswapV3Pool pool, uint256 amountOut, address caller);
event BuybackDelegate_Mint(uint256 indexed projectId, uint256 amountIn, uint256 tokenCount, address caller);
event BuybackDelegate_TwapWindowChanged(uint256 indexed projectId, uint256 oldSecondsAgo, uint256 newSecondsAgo, address caller);
event BuybackDelegate_TwapSlippageToleranceChanged(uint256 indexed projectId, uint256 oldTwapDelta, uint256 newTwapDelta, address caller);
event BuybackDelegate_PoolAdded(uint256 indexed projectId, address indexed terminalToken, address newPool, address caller);
/////////////////////////////////////////////////////////////////////
// Getters //
/////////////////////////////////////////////////////////////////////
function SLIPPAGE_DENOMINATOR() external view returns (uint256);
function MIN_TWAP_SLIPPAGE_TOLERANCE() external view returns (uint256);
function MAX_TWAP_SLIPPAGE_TOLERANCE() external view returns (uint256);
function MIN_TWAP_WINDOW() external view returns (uint256);
function MAX_TWAP_WINDOW() external view returns (uint256);
function UNISWAP_V3_FACTORY() external view returns (address);
function DIRECTORY() external view returns (IJBDirectory);
function CONTROLLER() external view returns (IJBController3_1);
function PROJECTS() external view returns (IJBProjects);
function WETH() external view returns (IWETH9);
function DELEGATE_ID() external view returns (bytes4);
function poolOf(uint256 projectId, address terminalToken) external view returns (IUniswapV3Pool pool);
function twapWindowOf(uint256 projectId) external view returns (uint32 window);
function twapSlippageToleranceOf(uint256 projectId) external view returns (uint256 slippageTolerance);
function projectTokenOf(uint256 projectId) external view returns (address projectTokenOf);
/////////////////////////////////////////////////////////////////////
// State-changing functions //
/////////////////////////////////////////////////////////////////////
function setPoolFor(uint256 projectId, uint24 fee, uint32 twapWindow, uint256 twapSlippageTolerance, address terminalToken)
external
returns (IUniswapV3Pool newPool);
function setTwapWindowOf(uint256 projectId, uint32 newWindow) external;
function setTwapSlippageToleranceOf(uint256 projectId, uint256 newSlippageTolerance) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBController3_0_1 {
function reservedTokenBalanceOf(uint256 projectId) external view returns (uint256);
function totalOutstandingTokensOf(uint256 projectId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBBallotState} from './../enums/JBBallotState.sol';
import {JBFundAccessConstraints} from './../structs/JBFundAccessConstraints.sol';
import {JBFundingCycle} from './../structs/JBFundingCycle.sol';
import {JBFundingCycleData} from './../structs/JBFundingCycleData.sol';
import {JBFundingCycleMetadata} from './../structs/JBFundingCycleMetadata.sol';
import {JBGroupedSplits} from './../structs/JBGroupedSplits.sol';
import {JBProjectMetadata} from './../structs/JBProjectMetadata.sol';
import {JBSplit} from './../structs/JBSplit.sol';
import {IJBController3_0_1} from './IJBController3_0_1.sol';
import {IJBDirectory} from './IJBDirectory.sol';
import {IJBFundAccessConstraintsStore} from './IJBFundAccessConstraintsStore.sol';
import {IJBFundingCycleStore} from './IJBFundingCycleStore.sol';
import {IJBMigratable} from './IJBMigratable.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';
import {IJBProjects} from './IJBProjects.sol';
import {IJBSplitsStore} from './IJBSplitsStore.sol';
import {IJBTokenStore} from './IJBTokenStore.sol';
interface IJBController3_1 is IJBController3_0_1, IERC165 {
event LaunchProject(uint256 configuration, uint256 projectId, string memo, address caller);
event LaunchFundingCycles(uint256 configuration, uint256 projectId, string memo, address caller);
event ReconfigureFundingCycles(
uint256 configuration,
uint256 projectId,
string memo,
address caller
);
event DistributeReservedTokens(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address beneficiary,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
address caller
);
event DistributeToReservedTokenSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
uint256 tokenCount,
address caller
);
event MintTokens(
address indexed beneficiary,
uint256 indexed projectId,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
uint256 reservedRate,
address caller
);
event BurnTokens(
address indexed holder,
uint256 indexed projectId,
uint256 tokenCount,
string memo,
address caller
);
event Migrate(uint256 indexed projectId, IJBMigratable to, address caller);
event PrepMigration(uint256 indexed projectId, address from, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function tokenStore() external view returns (IJBTokenStore);
function splitsStore() external view returns (IJBSplitsStore);
function fundAccessConstraintsStore() external view returns (IJBFundAccessConstraintsStore);
function directory() external view returns (IJBDirectory);
function reservedTokenBalanceOf(uint256 projectId) external view returns (uint256);
function totalOutstandingTokensOf(uint256 projectId) external view returns (uint256);
function getFundingCycleOf(
uint256 projectId,
uint256 configuration
)
external
view
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function latestConfiguredFundingCycleOf(
uint256 projectId
)
external
view
returns (JBFundingCycle memory, JBFundingCycleMetadata memory metadata, JBBallotState);
function currentFundingCycleOf(
uint256 projectId
)
external
view
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function queuedFundingCycleOf(
uint256 projectId
)
external
view
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function launchProjectFor(
address owner,
JBProjectMetadata calldata projectMetadata,
JBFundingCycleData calldata data,
JBFundingCycleMetadata calldata metadata,
uint256 mustStartAtOrAfter,
JBGroupedSplits[] memory groupedSplits,
JBFundAccessConstraints[] memory fundAccessConstraints,
IJBPaymentTerminal[] memory terminals,
string calldata memo
) external returns (uint256 projectId);
function launchFundingCyclesFor(
uint256 projectId,
JBFundingCycleData calldata data,
JBFundingCycleMetadata calldata metadata,
uint256 mustStartAtOrAfter,
JBGroupedSplits[] memory groupedSplits,
JBFundAccessConstraints[] memory fundAccessConstraints,
IJBPaymentTerminal[] memory terminals,
string calldata memo
) external returns (uint256 configuration);
function reconfigureFundingCyclesOf(
uint256 projectId,
JBFundingCycleData calldata data,
JBFundingCycleMetadata calldata metadata,
uint256 mustStartAtOrAfter,
JBGroupedSplits[] memory groupedSplits,
JBFundAccessConstraints[] memory fundAccessConstraints,
string calldata memo
) external returns (uint256);
function mintTokensOf(
uint256 projectId,
uint256 tokenCount,
address beneficiary,
string calldata memo,
bool preferClaimedTokens,
bool useReservedRate
) external returns (uint256 beneficiaryTokenCount);
function burnTokensOf(
address holder,
uint256 projectId,
uint256 tokenCount,
string calldata memo,
bool preferClaimedTokens
) external;
function distributeReservedTokensOf(
uint256 projectId,
string memory memo
) external returns (uint256);
function migrate(uint256 projectId, IJBMigratable to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBFundingCycleStore} from './IJBFundingCycleStore.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';
import {IJBProjects} from './IJBProjects.sol';
interface IJBDirectory {
event SetController(uint256 indexed projectId, address indexed controller, address caller);
event AddTerminal(uint256 indexed projectId, IJBPaymentTerminal indexed terminal, address caller);
event SetTerminals(uint256 indexed projectId, IJBPaymentTerminal[] terminals, address caller);
event SetPrimaryTerminal(
uint256 indexed projectId,
address indexed token,
IJBPaymentTerminal indexed terminal,
address caller
);
event SetIsAllowedToSetFirstController(address indexed addr, bool indexed flag, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function controllerOf(uint256 projectId) external view returns (address);
function isAllowedToSetFirstController(address account) external view returns (bool);
function terminalsOf(uint256 projectId) external view returns (IJBPaymentTerminal[] memory);
function isTerminalOf(
uint256 projectId,
IJBPaymentTerminal terminal
) external view returns (bool);
function primaryTerminalOf(
uint256 projectId,
address token
) external view returns (IJBPaymentTerminal);
function setControllerOf(uint256 projectId, address controller) external;
function setTerminalsOf(uint256 projectId, IJBPaymentTerminal[] calldata terminals) external;
function setPrimaryTerminalOf(
uint256 projectId,
address token,
IJBPaymentTerminal terminal
) external;
function setIsAllowedToSetFirstController(address account, bool flag) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBFeeHoldingTerminal {
function addToBalanceOf(
uint256 projectId,
uint256 amount,
address token,
bool shouldRefundHeldFees,
string calldata memo,
bytes calldata metadata
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBFundAccessConstraints} from './../structs/JBFundAccessConstraints.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';
interface IJBFundAccessConstraintsStore is IERC165 {
event SetFundAccessConstraints(
uint256 indexed fundingCycleConfiguration,
uint256 indexed projectId,
JBFundAccessConstraints constraints,
address caller
);
function distributionLimitOf(
uint256 projectId,
uint256 configuration,
IJBPaymentTerminal terminal,
address token
) external view returns (uint256 distributionLimit, uint256 distributionLimitCurrency);
function overflowAllowanceOf(
uint256 projectId,
uint256 configuration,
IJBPaymentTerminal terminal,
address token
) external view returns (uint256 overflowAllowance, uint256 overflowAllowanceCurrency);
function setFor(
uint256 projectId,
uint256 configuration,
JBFundAccessConstraints[] memory fundAccessConstaints
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBBallotState} from './../enums/JBBallotState.sol';
interface IJBFundingCycleBallot is IERC165 {
function duration() external view returns (uint256);
function stateOf(
uint256 projectId,
uint256 configuration,
uint256 start
) external view returns (JBBallotState);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBPayDelegateAllocation3_1_1} from './../structs/JBPayDelegateAllocation3_1_1.sol';
import {JBPayParamsData} from './../structs/JBPayParamsData.sol';
import {JBRedeemParamsData} from './../structs/JBRedeemParamsData.sol';
import {JBRedemptionDelegateAllocation3_1_1} from './../structs/JBRedemptionDelegateAllocation3_1_1.sol';
/// @title Datasource
/// @notice The datasource is called by JBPayoutRedemptionPaymentTerminals on pay and redemption, and provide an extra layer of logic to use a custom weight, a custom memo and/or a pay/redeem delegate
interface IJBFundingCycleDataSource3_1_1 is IERC165 {
/// @notice The datasource implementation for JBPaymentTerminal.pay(..)
/// @param data the data passed to the data source in terminal.pay(..), as a JBPayParamsData struct:
/// @return weight the weight to use to override the funding cycle weight
/// @return memo the memo to override the pay(..) memo
/// @return delegateAllocations The amount to send to delegates instead of adding to the local balance.
function payParams(
JBPayParamsData calldata data
)
external
view
returns (
uint256 weight,
string memory memo,
JBPayDelegateAllocation3_1_1[] memory delegateAllocations
);
/// @notice The datasource implementation for JBPaymentTerminal.redeemTokensOf(..)
/// @param data the data passed to the data source in terminal.redeemTokensOf(..), as a JBRedeemParamsData struct:
/// @return reclaimAmount The amount to claim, overriding the terminal logic.
/// @return memo The memo to override the redeemTokensOf(..) memo.
/// @return delegateAllocations The amount to send to delegates instead of adding to the beneficiary.
function redeemParams(
JBRedeemParamsData calldata data
)
external
view
returns (
uint256 reclaimAmount,
string memory memo,
JBRedemptionDelegateAllocation3_1_1[] memory delegateAllocations
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBBallotState} from './../enums/JBBallotState.sol';
import {JBFundingCycle} from './../structs/JBFundingCycle.sol';
import {JBFundingCycleData} from './../structs/JBFundingCycleData.sol';
interface IJBFundingCycleStore {
event Configure(
uint256 indexed configuration,
uint256 indexed projectId,
JBFundingCycleData data,
uint256 metadata,
uint256 mustStartAtOrAfter,
address caller
);
event Init(uint256 indexed configuration, uint256 indexed projectId, uint256 indexed basedOn);
function latestConfigurationOf(uint256 projectId) external view returns (uint256);
function get(
uint256 projectId,
uint256 configuration
) external view returns (JBFundingCycle memory);
function latestConfiguredOf(
uint256 projectId
) external view returns (JBFundingCycle memory fundingCycle, JBBallotState ballotState);
function queuedOf(uint256 projectId) external view returns (JBFundingCycle memory fundingCycle);
function currentOf(uint256 projectId) external view returns (JBFundingCycle memory fundingCycle);
function currentBallotStateOf(uint256 projectId) external view returns (JBBallotState);
function configureFor(
uint256 projectId,
JBFundingCycleData calldata data,
uint256 metadata,
uint256 mustStartAtOrAfter
) external returns (JBFundingCycle memory fundingCycle);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBMigratable {
function prepForMigrationOf(uint256 projectId, address from) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBOperatorStore} from './IJBOperatorStore.sol';
interface IJBOperatable {
function operatorStore() external view returns (IJBOperatorStore);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBOperatorData} from './../structs/JBOperatorData.sol';
interface IJBOperatorStore {
event SetOperator(
address indexed operator,
address indexed account,
uint256 indexed domain,
uint256[] permissionIndexes,
uint256 packed
);
function permissionsOf(
address operator,
address account,
uint256 domain
) external view returns (uint256);
function hasPermission(
address operator,
address account,
uint256 domain,
uint256 permissionIndex
) external view returns (bool);
function hasPermissions(
address operator,
address account,
uint256 domain,
uint256[] calldata permissionIndexes
) external view returns (bool);
function setOperator(JBOperatorData calldata operatorData) external;
function setOperators(JBOperatorData[] calldata operatorData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidPayData} from './../structs/JBDidPayData.sol';
/// @title Pay delegate
/// @notice Delegate called after JBTerminal.pay(..) logic completion (if passed by the funding cycle datasource)
interface IJBPayDelegate is IERC165 {
/// @notice This function is called by JBPaymentTerminal.pay(..), after the execution of its logic
/// @dev Critical business logic should be protected by an appropriate access control
/// @param data the data passed by the terminal, as a JBDidPayData struct:
function didPay(JBDidPayData calldata data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidPayData3_1_1} from './../structs/JBDidPayData3_1_1.sol';
/// @title Pay delegate
/// @notice Delegate called after JBTerminal.pay(..) logic completion (if passed by the funding cycle datasource)
interface IJBPayDelegate3_1_1 is IERC165 {
/// @notice This function is called by JBPaymentTerminal.pay(..), after the execution of its logic
/// @dev Critical business logic should be protected by an appropriate access control
/// @param data the data passed by the terminal, as a JBDidPayData3_1_1 struct:
function didPay(JBDidPayData3_1_1 calldata data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
interface IJBPaymentTerminal is IERC165 {
function acceptsToken(address token, uint256 projectId) external view returns (bool);
function currencyForToken(address token) external view returns (uint256);
function decimalsForToken(address token) external view returns (uint256);
// Return value must be a fixed point number with 18 decimals.
function currentEthOverflowOf(uint256 projectId) external view returns (uint256);
function pay(
uint256 projectId,
uint256 amount,
address token,
address beneficiary,
uint256 minReturnedTokens,
bool preferClaimedTokens,
string calldata memo,
bytes calldata metadata
) external payable returns (uint256 beneficiaryTokenCount);
function addToBalanceOf(
uint256 projectId,
uint256 amount,
address token,
string calldata memo,
bytes calldata metadata
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBFee} from './../structs/JBFee.sol';
import {IJBAllowanceTerminal3_1} from './IJBAllowanceTerminal3_1.sol';
import {IJBDirectory} from './IJBDirectory.sol';
import {IJBFeeHoldingTerminal} from './IJBFeeHoldingTerminal.sol';
import {IJBPayDelegate} from './IJBPayDelegate.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';
import {IJBPayoutTerminal3_1} from './IJBPayoutTerminal3_1.sol';
import {IJBPrices} from './IJBPrices.sol';
import {IJBProjects} from './IJBProjects.sol';
import {IJBRedemptionDelegate} from './IJBRedemptionDelegate.sol';
import {IJBRedemptionTerminal} from './IJBRedemptionTerminal.sol';
import {IJBSplitsStore} from './IJBSplitsStore.sol';
import {JBDidPayData} from './../structs/JBDidPayData.sol';
import {JBDidRedeemData} from './../structs/JBDidRedeemData.sol';
import {JBSplit} from './../structs/JBSplit.sol';
interface IJBPayoutRedemptionPaymentTerminal3_1 is
IJBPaymentTerminal,
IJBPayoutTerminal3_1,
IJBAllowanceTerminal3_1,
IJBRedemptionTerminal,
IJBFeeHoldingTerminal
{
event AddToBalance(
uint256 indexed projectId,
uint256 amount,
uint256 refundedFees,
string memo,
bytes metadata,
address caller
);
event Migrate(
uint256 indexed projectId,
IJBPaymentTerminal indexed to,
uint256 amount,
address caller
);
event DistributePayouts(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address beneficiary,
uint256 amount,
uint256 distributedAmount,
uint256 fee,
uint256 beneficiaryDistributionAmount,
bytes metadata,
address caller
);
event UseAllowance(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address beneficiary,
uint256 amount,
uint256 distributedAmount,
uint256 netDistributedamount,
string memo,
bytes metadata,
address caller
);
event HoldFee(
uint256 indexed projectId,
uint256 indexed amount,
uint256 indexed fee,
uint256 feeDiscount,
address beneficiary,
address caller
);
event ProcessFee(
uint256 indexed projectId,
uint256 indexed amount,
bool indexed wasHeld,
address beneficiary,
address caller
);
event RefundHeldFees(
uint256 indexed projectId,
uint256 indexed amount,
uint256 indexed refundedFees,
uint256 leftoverAmount,
address caller
);
event Pay(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address payer,
address beneficiary,
uint256 amount,
uint256 beneficiaryTokenCount,
string memo,
bytes metadata,
address caller
);
event DelegateDidPay(
IJBPayDelegate indexed delegate,
JBDidPayData data,
uint256 delegatedAmount,
address caller
);
event RedeemTokens(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address holder,
address beneficiary,
uint256 tokenCount,
uint256 reclaimedAmount,
string memo,
bytes metadata,
address caller
);
event DelegateDidRedeem(
IJBRedemptionDelegate indexed delegate,
JBDidRedeemData data,
uint256 delegatedAmount,
address caller
);
event DistributeToPayoutSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
uint256 amount,
uint256 netAmount,
address caller
);
event SetFee(uint256 fee, address caller);
event SetFeeGauge(address indexed feeGauge, address caller);
event SetFeelessAddress(address indexed addrs, bool indexed flag, address caller);
event PayoutReverted(
uint256 indexed projectId,
JBSplit split,
uint256 amount,
bytes reason,
address caller
);
event FeeReverted(
uint256 indexed projectId,
uint256 indexed feeProjectId,
uint256 amount,
bytes reason,
address caller
);
function projects() external view returns (IJBProjects);
function splitsStore() external view returns (IJBSplitsStore);
function directory() external view returns (IJBDirectory);
function prices() external view returns (IJBPrices);
function store() external view returns (address);
function baseWeightCurrency() external view returns (uint256);
function payoutSplitsGroup() external view returns (uint256);
function heldFeesOf(uint256 projectId) external view returns (JBFee[] memory);
function fee() external view returns (uint256);
function feeGauge() external view returns (address);
function isFeelessAddress(address account) external view returns (bool);
function migrate(uint256 projectId, IJBPaymentTerminal to) external returns (uint256 balance);
function processFees(uint256 projectId) external;
function setFee(uint256 fee) external;
function setFeeGauge(address feeGauge) external;
function setFeelessAddress(address account, bool flag) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBFee} from './../structs/JBFee.sol';
import {JBDidRedeemData3_1_1} from './../structs/JBDidRedeemData3_1_1.sol';
import {JBDidPayData3_1_1} from './../structs/JBDidPayData3_1_1.sol';
import {IJBPayDelegate3_1_1} from './IJBPayDelegate3_1_1.sol';
import {IJBRedemptionDelegate3_1_1} from './IJBRedemptionDelegate3_1_1.sol';
import {IJBPayoutRedemptionPaymentTerminal3_1} from './IJBPayoutRedemptionPaymentTerminal3_1.sol';
interface IJBPayoutRedemptionPaymentTerminal3_1_1 is IJBPayoutRedemptionPaymentTerminal3_1 {
event DelegateDidRedeem(
IJBRedemptionDelegate3_1_1 indexed delegate,
JBDidRedeemData3_1_1 data,
uint256 delegatedAmount,
uint256 fee,
address caller
);
event DelegateDidPay(
IJBPayDelegate3_1_1 indexed delegate,
JBDidPayData3_1_1 data,
uint256 delegatedAmount,
address caller
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBPayoutTerminal3_1 {
function distributePayoutsOf(
uint256 projectId,
uint256 amount,
uint256 currency,
address token,
uint256 minReturnedTokens,
bytes calldata metadata
) external returns (uint256 netLeftoverDistributionAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBPriceFeed {
function currentPrice(uint256 targetDecimals) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBPriceFeed} from './IJBPriceFeed.sol';
interface IJBPrices {
event AddFeed(uint256 indexed currency, uint256 indexed base, IJBPriceFeed feed);
function feedFor(uint256 currency, uint256 base) external view returns (IJBPriceFeed);
function priceFor(
uint256 currency,
uint256 base,
uint256 decimals
) external view returns (uint256);
function addFeedFor(uint256 currency, uint256 base, IJBPriceFeed priceFeed) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {JBProjectMetadata} from './../structs/JBProjectMetadata.sol';
import {IJBTokenUriResolver} from './IJBTokenUriResolver.sol';
interface IJBProjects is IERC721 {
event Create(
uint256 indexed projectId,
address indexed owner,
JBProjectMetadata metadata,
address caller
);
event SetMetadata(uint256 indexed projectId, JBProjectMetadata metadata, address caller);
event SetTokenUriResolver(IJBTokenUriResolver indexed resolver, address caller);
function count() external view returns (uint256);
function metadataContentOf(
uint256 projectId,
uint256 domain
) external view returns (string memory);
function tokenUriResolver() external view returns (IJBTokenUriResolver);
function createFor(
address owner,
JBProjectMetadata calldata metadata
) external returns (uint256 projectId);
function setMetadataOf(uint256 projectId, JBProjectMetadata calldata metadata) external;
function setTokenUriResolver(IJBTokenUriResolver newResolver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidRedeemData} from './../structs/JBDidRedeemData.sol';
/// @title Redemption delegate
/// @notice Delegate called after JBTerminal.redeemTokensOf(..) logic completion (if passed by the funding cycle datasource)
interface IJBRedemptionDelegate is IERC165 {
/// @notice This function is called by JBPaymentTerminal.redeemTokensOf(..), after the execution of its logic
/// @dev Critical business logic should be protected by an appropriate access control
/// @param data the data passed by the terminal, as a JBDidRedeemData struct:
function didRedeem(JBDidRedeemData calldata data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidRedeemData3_1_1} from './../structs/JBDidRedeemData3_1_1.sol';
/// @title Redemption delegate
/// @notice Delegate called after JBTerminal.redeemTokensOf(..) logic completion (if passed by the funding cycle datasource)
interface IJBRedemptionDelegate3_1_1 is IERC165 {
/// @notice This function is called by JBPaymentTerminal.redeemTokensOf(..), after the execution of its logic
/// @dev Critical business logic should be protected by an appropriate access control
/// @param data the data passed by the terminal, as a JBDidRedeemData struct:
function didRedeem(JBDidRedeemData3_1_1 calldata data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBRedemptionTerminal {
function redeemTokensOf(
address holder,
uint256 projectId,
uint256 tokenCount,
address token,
uint256 minReturnedTokens,
address payable beneficiary,
string calldata memo,
bytes calldata metadata
) external returns (uint256 reclaimAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBSplitAllocationData} from '../structs/JBSplitAllocationData.sol';
/// @title Split allocator
/// @notice Provide a way to process a single split with extra logic
/// @dev The contract address should be set as an allocator in the adequate split
interface IJBSplitAllocator is IERC165 {
/// @notice This function is called by JBPaymentTerminal.distributePayoutOf(..), during the processing of the split including it
/// @dev Critical business logic should be protected by an appropriate access control. The token and/or eth are optimistically transfered to the allocator for its logic.
/// @param data the data passed by the terminal, as a JBSplitAllocationData struct:
function allocate(JBSplitAllocationData calldata data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBGroupedSplits} from './../structs/JBGroupedSplits.sol';
import {JBSplit} from './../structs/JBSplit.sol';
import {IJBDirectory} from './IJBDirectory.sol';
import {IJBProjects} from './IJBProjects.sol';
interface IJBSplitsStore {
event SetSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
address caller
);
function projects() external view returns (IJBProjects);
function directory() external view returns (IJBDirectory);
function splitsOf(
uint256 projectId,
uint256 domain,
uint256 group
) external view returns (JBSplit[] memory);
function set(uint256 projectId, uint256 domain, JBGroupedSplits[] memory groupedSplits) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBToken {
function projectId() external view returns (uint256);
function decimals() external view returns (uint8);
function totalSupply(uint256 projectId) external view returns (uint256);
function balanceOf(address account, uint256 projectId) external view returns (uint256);
function mint(uint256 projectId, address account, uint256 amount) external;
function burn(uint256 projectId, address account, uint256 amount) external;
function approve(uint256, address spender, uint256 amount) external;
function transfer(uint256 projectId, address to, uint256 amount) external;
function transferFrom(uint256 projectId, address from, address to, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBFundingCycleStore} from './IJBFundingCycleStore.sol';
import {IJBProjects} from './IJBProjects.sol';
import {IJBToken} from './IJBToken.sol';
interface IJBTokenStore {
event Issue(
uint256 indexed projectId,
IJBToken indexed token,
string name,
string symbol,
address caller
);
event Mint(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
bool tokensWereClaimed,
bool preferClaimedTokens,
address caller
);
event Burn(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
uint256 initialUnclaimedBalance,
uint256 initialClaimedBalance,
bool preferClaimedTokens,
address caller
);
event Claim(
address indexed holder,
uint256 indexed projectId,
uint256 initialUnclaimedBalance,
uint256 amount,
address caller
);
event Set(uint256 indexed projectId, IJBToken indexed newToken, address caller);
event Transfer(
address indexed holder,
uint256 indexed projectId,
address indexed recipient,
uint256 amount,
address caller
);
function tokenOf(uint256 projectId) external view returns (IJBToken);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function unclaimedBalanceOf(address holder, uint256 projectId) external view returns (uint256);
function unclaimedTotalSupplyOf(uint256 projectId) external view returns (uint256);
function totalSupplyOf(uint256 projectId) external view returns (uint256);
function balanceOf(address holder, uint256 projectId) external view returns (uint256 result);
function issueFor(
uint256 projectId,
string calldata name,
string calldata symbol
) external returns (IJBToken token);
function setFor(uint256 projectId, IJBToken token) external;
function burnFrom(
address holder,
uint256 projectId,
uint256 amount,
bool preferClaimedTokens
) external;
function mintFor(
address holder,
uint256 projectId,
uint256 amount,
bool preferClaimedTokens
) external;
function claimFor(address holder, uint256 projectId, uint256 amount) external;
function transferFrom(
address holder,
uint256 projectId,
address recipient,
uint256 amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IJBTokenUriResolver {
function getUri(uint256 projectId) external view returns (string memory tokenUri);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolErrors,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
error LOK();
error TLU();
error TLM();
error TUM();
error AI();
error M0();
error M1();
error AS();
error IIA();
error L();
error F0();
error F1();
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
/// @return The liquidity at the current price of the pool
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper
/// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
/// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
/// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return liquidity The amount of liquidity in the position,
/// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// @return initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
enum JBBallotState {
Active,
Approved,
Failed
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IJBPaymentTerminal} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPaymentTerminal.sol";
import {IJBPayoutRedemptionPaymentTerminal3_1_1} from
"@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPayoutRedemptionPaymentTerminal3_1_1.sol";
import {JBDidPayData3_1_1} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBDidPayData3_1_1.sol";
import {JBOperatable} from "@jbx-protocol/juice-contracts-v3/contracts/abstract/JBOperatable.sol";
import {IJBDirectory} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBDirectory.sol";
import {IJBController3_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBController3_1.sol";
import {IJBProjects} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBController3_1.sol";
import {IJBOperatable} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBOperatable.sol";
import {IJBFundingCycleDataSource3_1_1} from
"@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBFundingCycleDataSource3_1_1.sol";
import {IJBPayDelegate3_1_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPayDelegate3_1_1.sol";
import {JBPayDelegateAllocation3_1_1} from
"@jbx-protocol/juice-contracts-v3/contracts/structs/JBPayDelegateAllocation3_1_1.sol";
import {JBPayParamsData} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBPayParamsData.sol";
import {JBRedeemParamsData} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBRedeemParamsData.sol";
import {JBRedemptionDelegateAllocation3_1_1} from
"@jbx-protocol/juice-contracts-v3/contracts/structs/JBRedemptionDelegateAllocation3_1_1.sol";
import {JBTokens} from "@jbx-protocol/juice-contracts-v3/contracts/libraries/JBTokens.sol";
import {JBDelegateMetadataLib} from "@jbx-protocol/juice-delegate-metadata-lib/src/JBDelegateMetadataLib.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {ERC165, IERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {mulDiv} from "@prb/math/src/Common.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {JBBuybackDelegateOperations} from "./libraries/JBBuybackDelegateOperations.sol";
import {IJBBuybackDelegate} from "./interfaces/IJBBuybackDelegate.sol";
import {IWETH9} from "./interfaces/external/IWETH9.sol";
/// @custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
/// @title JBBuybackDelegate
/// @notice Generic Buyback Delegate compatible with any Juicebox payment terminal and any project token that can be pooled.
/// @notice Functions as a Data Source and Delegate allowing beneficiaries of payments to get the highest amount
/// of a project's token between minting using the project weight and swapping in a given Uniswap V3 pool.
contract JBBuybackDelegate is ERC165, JBOperatable, IJBBuybackDelegate {
//*********************************************************************//
// --------------------- internal stored properties ------------------ //
//*********************************************************************//
/// @notice The TWAP max deviation acepted and timeframe to use for the pool twap, packed in a uint256.
/// @custom:param _projectId The ID of the project to which the TWAP params apply.
mapping(uint256 _projectId => uint256) internal _twapParamsOf;
//*********************************************************************//
// --------------------- public constant properties ------------------ //
//*********************************************************************//
/// @notice The unit of the max slippage.
uint256 public constant SLIPPAGE_DENOMINATOR = 10_000;
/// @notice The minimum twap deviation allowed, out of MAX_SLIPPAGE.
/// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
uint256 public constant MIN_TWAP_SLIPPAGE_TOLERANCE = 100;
/// @notice The maximum twap deviation allowed, out of MAX_SLIPPAGE.
/// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
uint256 public constant MAX_TWAP_SLIPPAGE_TOLERANCE = 9000;
/// @notice The smallest TWAP period allowed, in seconds.
/// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
uint256 public constant MIN_TWAP_WINDOW = 2 minutes;
/// @notice The largest TWAP period allowed, in seconds.
/// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
uint256 public constant MAX_TWAP_WINDOW = 2 days;
//*********************************************************************//
// -------------------- public immutable properties ------------------ //
//*********************************************************************//
/// @notice The uniswap v3 factory used to reference pools from.
address public immutable UNISWAP_V3_FACTORY;
/// @notice The directory of terminals and controllers.
IJBDirectory public immutable DIRECTORY;
/// @notice The controller used to mint and burn tokens from.
IJBController3_1 public immutable CONTROLLER;
/// @notice The project registry.
IJBProjects public immutable PROJECTS;
/// @notice The WETH contract.
IWETH9 public immutable WETH;
/// @notice The 4bytes ID of this delegate, used for metadata parsing.
bytes4 public immutable DELEGATE_ID;
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/// @notice The uniswap pool corresponding to the project token <-> terminal token pair.
/// @custom:param _projectId The ID of the project to which the pool applies.
/// @custom:param _terminalToken The address of the token being used to make payments in.
mapping(uint256 _projectId => mapping(address _terminalToken => IUniswapV3Pool)) public poolOf;
/// @notice Each project's token.
/// @custom:param _projectId The ID of the project to which the token belongs.
mapping(uint256 _projectId => address) public projectTokenOf;
//*********************************************************************//
// ---------------------------- constructor -------------------------- //
//*********************************************************************//
/// @param _weth The WETH contract.
/// @param _factory The uniswap v3 factory used to reference pools from.
/// @param _directory The directory of terminals and controllers.
/// @param _controller The controller used to mint and burn tokens from.
/// @param _delegateId The 4bytes ID of this delegate, used for metadata parsing.
constructor(
IWETH9 _weth,
address _factory,
IJBDirectory _directory,
IJBController3_1 _controller,
bytes4 _delegateId
) JBOperatable(IJBOperatable(address(_controller)).operatorStore()) {
WETH = _weth;
DIRECTORY = _directory;
CONTROLLER = _controller;
UNISWAP_V3_FACTORY = _factory;
DELEGATE_ID = _delegateId;
PROJECTS = _controller.projects();
}
//*********************************************************************//
// ------------------------- external views -------------------------- //
//*********************************************************************//
/// @notice The DataSource implementation that determines if a swap path and/or a mint path should be taken.
/// @param _data The data passed to the data source in terminal.pay(..). _data.metadata can have a Uniswap quote and specify how much of the payment should be used to swap, otherwise a quote will be determined from a TWAP and use the full amount paid in.
/// @return weight The weight to use, which is the original weight passed in if no swap path is taken, 0 if only the swap path is taken, and an adjusted weight if the both the swap and mint paths are taken.
/// @return memo the original memo passed
/// @return delegateAllocations The amount to send to delegates instead of adding to the local balance. This is empty if only the mint path is taken.
function payParams(JBPayParamsData calldata _data)
external
view
override
returns (uint256 weight, string memory memo, JBPayDelegateAllocation3_1_1[] memory delegateAllocations)
{
// Keep a reference to the payment total
uint256 _totalPaid = _data.amount.value;
// Keep a reference to the weight
uint256 _weight = _data.weight;
// Keep a reference to the minimum number of tokens expected to be swapped for.
uint256 _minimumSwapAmountOut;
// Keep a reference to the amount from the payment to allocate towards a swap.
uint256 _amountToSwapWith;
// Keep a reference to a flag indicating if the quote passed into the metadata exists.
bool _quoteExists;
// Scoped section to prevent Stack Too Deep.
{
bytes memory _metadata;
// Unpack the quote from the pool, given by the frontend.
(_quoteExists, _metadata) = JBDelegateMetadataLib.getMetadata(DELEGATE_ID, _data.metadata);
if (_quoteExists) (_amountToSwapWith, _minimumSwapAmountOut) = abi.decode(_metadata, (uint256, uint256));
}
// If no amount was specified to swap with, default to the full amount of the payment.
if (_amountToSwapWith == 0) _amountToSwapWith = _totalPaid;
// Find the default total number of tokens to mint as if no Buyback Delegate were installed, as a fixed point number with 18 decimals
uint256 _tokenCountWithoutDelegate = mulDiv(_amountToSwapWith, _weight, 10 ** _data.amount.decimals);
// Keep a reference to the project's token.
address _projectToken = projectTokenOf[_data.projectId];
// Keep a reference to the token being used by the terminal that is calling this delegate. Use weth is ETH.
address _terminalToken = _data.amount.token == JBTokens.ETH ? address(WETH) : _data.amount.token;
// If a minimum amount of tokens to swap for wasn't specified, resolve a value as good as possible using a TWAP.
if (_minimumSwapAmountOut == 0) {
_minimumSwapAmountOut = _getQuote(_data.projectId, _projectToken, _amountToSwapWith, _terminalToken);
}
// If the minimum amount received from swapping is greather than received when minting, use the swap path.
if (_tokenCountWithoutDelegate < _minimumSwapAmountOut) {
// Make sure the amount to swap with is at most the full amount being paid.
if (_amountToSwapWith > _totalPaid) revert JuiceBuyback_InsufficientPayAmount();
// Keep a reference to a flag indicating if the pool will reference the project token as the first in the pair.
bool _projectTokenIs0 = address(_projectToken) < _terminalToken;
// Return this delegate as the one to use, while forwarding the amount to swap with. Speficy metadata that allows the swap to be executed.
delegateAllocations = new JBPayDelegateAllocation3_1_1[](1);
delegateAllocations[0] = JBPayDelegateAllocation3_1_1({
delegate: IJBPayDelegate3_1_1(this),
amount: _amountToSwapWith,
metadata: abi.encode(_quoteExists, _projectTokenIs0, _totalPaid == _amountToSwapWith ? 0 : _totalPaid - _amountToSwapWith, _minimumSwapAmountOut, _weight)
});
// All the mint will be done in didPay, return 0 as weight to avoid minting via the terminal
return (
0,
_data.memo,
delegateAllocations
);
}
// If only minting, delegateAllocations is left uninitialised and the full weight is returned for the terminal to mint.
return (_data.weight, _data.memo, delegateAllocations);
}
/// @notice The timeframe to use for the pool TWAP.
/// @param _projectId The ID of the project for which the value applies.
/// @return _secondsAgo The period over which the TWAP is computed.
function twapWindowOf(uint256 _projectId) external view returns (uint32) {
return uint32(_twapParamsOf[_projectId]);
}
/// @notice The TWAP max deviation acepted, out of SLIPPAGE_DENOMINATOR.
/// @param _projectId The ID of the project for which the value applies.
/// @return _delta the maximum deviation allowed between the token amount received and the TWAP quote.
function twapSlippageToleranceOf(uint256 _projectId) external view returns (uint256) {
return _twapParamsOf[_projectId] >> 128;
}
/// @notice Generic redeem params, for interface completion.
/// @dev This is a passthrough of the redemption parameters
/// @param _data The redeem data passed by the terminal.
function redeemParams(JBRedeemParamsData calldata _data)
external
pure
override
returns (uint256, string memory, JBRedemptionDelegateAllocation3_1_1[] memory delegateAllocations)
{
return (_data.reclaimAmount.value, _data.memo, delegateAllocations);
}
//*********************************************************************//
// -------------------------- public views --------------------------- //
//*********************************************************************//
function supportsInterface(bytes4 _interfaceId) public view override(ERC165, IERC165) returns (bool) {
return _interfaceId == type(IJBFundingCycleDataSource3_1_1).interfaceId
|| _interfaceId == type(IJBPayDelegate3_1_1).interfaceId
|| _interfaceId == type(IJBBuybackDelegate).interfaceId
|| super.supportsInterface(_interfaceId);
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/// @notice Delegate used to swap a provided amount to the beneficiary, using any leftover amount to mint.
/// @dev This delegate is called only if the quote for the swap is bigger than the quote when minting.
/// If the swap reverts (slippage, liquidity, etc), the delegate will then mint the same amount of token as if the delegate was not used.
/// @param _data The delegate data passed by the terminal.
function didPay(JBDidPayData3_1_1 calldata _data) external payable override {
// Make sure only a payment terminal belonging to the project can access this functionality.
if (!DIRECTORY.isTerminalOf(_data.projectId, IJBPaymentTerminal(msg.sender))) {
revert JuiceBuyback_Unauthorized();
}
// Parse the metadata passed in from the data source.
(
bool _quoteExists,
bool _projectTokenIs0,
uint256 _amountToMintWith,
uint256 _minimumSwapAmountOut,
uint256 _weight
) = abi.decode(_data.dataSourceMetadata, (bool, bool, uint256, uint256, uint256));
// Get a reference to the amount of tokens that was swapped for.
uint256 _exactSwapAmountOut = _swap(_data, _projectTokenIs0);
// Make sure the slippage is tolerable if passed in via an explicit quote.
if (_quoteExists && _exactSwapAmountOut < _minimumSwapAmountOut) revert JuiceBuyback_MaximumSlippage();
// Get a reference to any amount of tokens paid in remaining in this contract.
uint256 _terminalTokenInThisContract = _data.forwardedAmount.token == JBTokens.ETH
? address(this).balance
: IERC20(_data.forwardedAmount.token).balanceOf(address(this));
// Use any leftover amount of tokens paid in remaining to mint.
// Keep a reference to the number of tokens being minted.
uint256 _partialMintTokenCount;
if (_terminalTokenInThisContract != 0) {
_partialMintTokenCount = mulDiv(_terminalTokenInThisContract, _weight, 10 ** _data.amount.decimals);
// If the token paid in wasn't ETH, give the terminal permission to pull them back into its balance.
if (_data.forwardedAmount.token != JBTokens.ETH) {
IERC20(_data.forwardedAmount.token).approve(msg.sender, _terminalTokenInThisContract);
}
// Add the paid amount back to the project's terminal balance.
IJBPayoutRedemptionPaymentTerminal3_1_1(msg.sender).addToBalanceOf{
value: _data.forwardedAmount.token == JBTokens.ETH ? _terminalTokenInThisContract : 0
}(_data.projectId, _terminalTokenInThisContract, _data.forwardedAmount.token, "", "");
emit BuybackDelegate_Mint(_data.projectId, _terminalTokenInThisContract, _partialMintTokenCount, msg.sender);
}
// Add amount to mint to leftover mint amount (avoiding stack too deep here)
_partialMintTokenCount += mulDiv(_amountToMintWith, _weight, 10 ** _data.amount.decimals);
// Mint the whole amount of tokens again together with the (optional partial mint), such that the correct portion of reserved tokens get taken into account.
CONTROLLER.mintTokensOf({
projectId: _data.projectId,
tokenCount: _exactSwapAmountOut + _partialMintTokenCount,
beneficiary: address(_data.beneficiary),
memo: _data.memo,
preferClaimedTokens: _data.preferClaimedTokens,
useReservedRate: true
});
}
/// @notice The Uniswap V3 pool callback where the token transfer is expected to happen.
/// @param _amount0Delta The amount of token 0 being used for the swap.
/// @param _amount1Delta The amount of token 1 being used for the swap.
/// @param _data Data passed in by the swap operation.
function uniswapV3SwapCallback(int256 _amount0Delta, int256 _amount1Delta, bytes calldata _data)
external
override
{
// Unpack the data passed in through the swap hook.
(uint256 _projectId, address _terminalToken) = abi.decode(_data, (uint256, address));
// Get the terminal token, using WETH if the token paid in is ETH.
address _terminalTokenWithWETH = _terminalToken == JBTokens.ETH ? address(WETH) : _terminalToken;
// Make sure this call is being made from within the swap execution.
if (msg.sender != address(poolOf[_projectId][_terminalTokenWithWETH])) revert JuiceBuyback_Unauthorized();
// Keep a reference to the amount of tokens that should be sent to fulfill the swap (the positive delta)
uint256 _amountToSendToPool = _amount0Delta < 0 ? uint256(_amount1Delta) : uint256(_amount0Delta);
// Wrap ETH into WETH if relevant (do not rely on ETH delegate balance to support pure WETH terminals)
if (_terminalToken == JBTokens.ETH) WETH.deposit{value: _amountToSendToPool}();
// Transfer the token to the pool.
IERC20(_terminalTokenWithWETH).transfer(msg.sender, _amountToSendToPool);
}
/// @notice Add a pool for a given project. This pool the becomes the default for a given token project <--> terminal token pair.
/// @dev Uses create2 for callback auth and allows adding a pool not deployed yet.
/// This can be called by the project owner or an address having the SET_POOL permission in JBOperatorStore
/// @param _projectId The ID of the project having its pool set.
/// @param _fee The fee that is used in the pool being set.
/// @param _twapWindow The period over which the TWAP is computed.
/// @param _twapSlippageTolerance The maximum deviation allowed between amount received and TWAP.
/// @param _terminalToken The terminal token that payments are made in.
/// @return newPool The pool that was created.
function setPoolFor(uint256 _projectId, uint24 _fee, uint32 _twapWindow, uint256 _twapSlippageTolerance, address _terminalToken)
external
requirePermission(PROJECTS.ownerOf(_projectId), _projectId, JBBuybackDelegateOperations.CHANGE_POOL)
returns (IUniswapV3Pool newPool)
{
// Make sure the provided delta is within sane bounds.
if (_twapSlippageTolerance < MIN_TWAP_SLIPPAGE_TOLERANCE || _twapSlippageTolerance > MAX_TWAP_SLIPPAGE_TOLERANCE) revert JuiceBuyback_InvalidTwapSlippageTolerance();
// Make sure the provided period is within sane bounds.
if (_twapWindow < MIN_TWAP_WINDOW || _twapWindow > MAX_TWAP_WINDOW) revert JuiceBuyback_InvalidTwapWindow();
// Keep a reference to the project's token.
address _projectToken = address(CONTROLLER.tokenStore().tokenOf(_projectId));
// Make sure the project has issued a token.
if (_projectToken == address(0)) revert JuiceBuyback_NoProjectToken();
// If the terminal token specified in ETH, use WETH instead.
if (_terminalToken == JBTokens.ETH) _terminalToken = address(WETH);
// Keep a reference to a flag indicating if the pool will reference the project token as the first in the pair.
bool _projectTokenIs0 = address(_projectToken) < _terminalToken;
// Compute the corresponding pool's address, which is a function of both tokens and the specified fee.
newPool = IUniswapV3Pool(
address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
UNISWAP_V3_FACTORY,
keccak256(
abi.encode(
_projectTokenIs0 ? _projectToken : _terminalToken,
_projectTokenIs0 ? _terminalToken : _projectToken,
_fee
)
),
// POOL_INIT_CODE_HASH from https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/PoolAddress.sol
bytes32(0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54)
)
)
)
)
)
);
// Make sure this pool has yet to be specified in this delegate.
if (poolOf[_projectId][_terminalToken] == newPool) revert JuiceBuyback_PoolAlreadySet();
// Store the pool.
poolOf[_projectId][_terminalToken] = newPool;
// Store the twap period and max slipage.
_twapParamsOf[_projectId] = _twapSlippageTolerance << 128 | _twapWindow;
projectTokenOf[_projectId] = address(_projectToken);
emit BuybackDelegate_TwapWindowChanged(_projectId, 0, _twapWindow, msg.sender);
emit BuybackDelegate_TwapSlippageToleranceChanged(_projectId, 0, _twapSlippageTolerance, msg.sender);
emit BuybackDelegate_PoolAdded(_projectId, _terminalToken, address(newPool), msg.sender);
}
/// @notice Increase the period over which the TWAP is computed.
/// @dev This can be called by the project owner or an address having the SET_TWAP_PERIOD permission in JBOperatorStore.
/// @param _projectId The ID for which the new value applies.
/// @param _newWindow The new TWAP period.
function setTwapWindowOf(uint256 _projectId, uint32 _newWindow)
external
requirePermission(PROJECTS.ownerOf(_projectId), _projectId, JBBuybackDelegateOperations.SET_POOL_PARAMS)
{
// Make sure the provided period is within sane bounds.
if (_newWindow < MIN_TWAP_WINDOW || _newWindow > MAX_TWAP_WINDOW) {
revert JuiceBuyback_InvalidTwapWindow();
}
// Keep a reference to the currently stored TWAP params.
uint256 _twapParams = _twapParamsOf[_projectId];
// Keep a reference to the old window value.
uint256 _oldWindow = uint128(_twapParams);
// Store the new packed value of the TWAP params.
_twapParamsOf[_projectId] = uint256(_newWindow) | ((_twapParams >> 128) << 128);
emit BuybackDelegate_TwapWindowChanged(_projectId, _oldWindow, _newWindow, msg.sender);
}
/// @notice Set the maximum deviation allowed between amount received and TWAP.
/// @dev This can be called by the project owner or an address having the SET_POOL permission in JBOperatorStore.
/// @param _projectId The ID for which the new value applies.
/// @param _newSlippageTolerance the new delta, out of SLIPPAGE_DENOMINATOR.
function setTwapSlippageToleranceOf(uint256 _projectId, uint256 _newSlippageTolerance)
external
requirePermission(PROJECTS.ownerOf(_projectId), _projectId, JBBuybackDelegateOperations.SET_POOL_PARAMS)
{
// Make sure the provided delta is within sane bounds.
if (_newSlippageTolerance < MIN_TWAP_SLIPPAGE_TOLERANCE || _newSlippageTolerance > MAX_TWAP_SLIPPAGE_TOLERANCE) revert JuiceBuyback_InvalidTwapSlippageTolerance();
// Keep a reference to the currently stored TWAP params.
uint256 _twapParams = _twapParamsOf[_projectId];
// Keep a reference to the old slippage value.
uint256 _oldSlippageTolerance = _twapParams >> 128;
// Store the new packed value of the TWAP params.
_twapParamsOf[_projectId] = _newSlippageTolerance << 128 | ((_twapParams << 128) >> 128);
emit BuybackDelegate_TwapSlippageToleranceChanged(_projectId, _oldSlippageTolerance, _newSlippageTolerance, msg.sender);
}
//*********************************************************************//
// ---------------------- internal functions ------------------------- //
//*********************************************************************//
/// @notice Get a quote based on TWAP over a secondsAgo period, taking into account a twapDelta max deviation.
/// @param _projectId The ID of the project for which the swap is being made.
/// @param _projectToken The project's token being swapped for.
/// @param _amountIn The amount being used to swap.
/// @param _terminalToken The token paid in being used to swap.
/// @return amountOut the minimum amount received according to the TWAP.
function _getQuote(uint256 _projectId, address _projectToken, uint256 _amountIn, address _terminalToken)
internal
view
returns (uint256 amountOut)
{
// Get a reference to the pool that'll be used to make the swap.
IUniswapV3Pool _pool = poolOf[_projectId][address(_terminalToken)];
// Make sure the pool exists.
try _pool.slot0() returns (uint160, int24, uint16, uint16, uint16, uint8, bool unlocked) {
// If the pool hasn't been initialized, return an empty quote.
if (!unlocked) return 0;
} catch {
// If the address is invalid or if the pool has not yet been deployed, return an empty quote.
return 0;
}
// Unpack the TWAP params and get a reference to the period and slippage.
uint256 _twapParams = _twapParamsOf[_projectId];
uint32 _quotePeriod = uint32(_twapParams);
uint256 _maxDelta = _twapParams >> 128;
// Keep a reference to the TWAP tick.
(int24 arithmeticMeanTick,) = OracleLibrary.consult(address(_pool), _quotePeriod);
// Get a quote based on this TWAP tick.
amountOut = OracleLibrary.getQuoteAtTick({
tick: arithmeticMeanTick,
baseAmount: uint128(_amountIn),
baseToken: _terminalToken,
quoteToken: address(_projectToken)
});
// Return the lowest TWAP tolerable.
amountOut -= (amountOut * _maxDelta) / SLIPPAGE_DENOMINATOR;
}
/// @notice Swap the terminal token to receive the project token.
/// @param _data The didPayData passed by the terminal.
/// @param _projectTokenIs0 A flag indicating if the pool will reference the project token as the first in the pair.
/// @return amountReceived The amount of tokens received from the swap.
function _swap(
JBDidPayData3_1_1 calldata _data,
bool _projectTokenIs0
) internal returns (uint256 amountReceived) {
// The amount of tokens that are being used with which to make the swap.
uint256 _amountToSwapWith = _data.forwardedAmount.value;
// Get the terminal token, using WETH if the token paid in is ETH.
address _terminalTokenWithWETH = _data.forwardedAmount.token == JBTokens.ETH ? address(WETH) : _data.forwardedAmount.token;
// Get a reference to the pool that'll be used to make the swap.
IUniswapV3Pool _pool = poolOf[_data.projectId][_terminalTokenWithWETH];
// Try swapping.
try _pool.swap({
recipient: address(this),
zeroForOne: !_projectTokenIs0,
amountSpecified: int256(_amountToSwapWith),
sqrtPriceLimitX96: _projectTokenIs0 ? TickMath.MAX_SQRT_RATIO - 1 : TickMath.MIN_SQRT_RATIO + 1,
data: abi.encode(_data.projectId, _data.forwardedAmount.token)
}) returns (int256 amount0, int256 amount1) {
// If the swap succeded, take note of the amount of tokens received. This will return as negative since it is an exact input.
amountReceived = uint256(-(_projectTokenIs0 ? amount0 : amount1));
} catch {
// If the swap failed, return.
return 0;
}
// Burn the whole amount received.
CONTROLLER.burnTokensOf({
holder: address(this),
projectId: _data.projectId,
tokenCount: amountReceived,
memo: "",
preferClaimedTokens: true
});
// We return the amount we received/burned and we will mint them to the user later
emit BuybackDelegate_Swap(_data.projectId, _amountToSwapWith, _pool, amountReceived, msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title JBBuybackDelegateOperations
/// @notice JB specific operation indexes for the JBBuybackDelegate
library JBBuybackDelegateOperations {
// [0..18] - JBOperations
// 19 - JBOperations2 (ENS/Handle)
// 20 - JBUriOperations (Set token URI)
// [21..23] - JB721Operations
uint256 public constant SET_POOL_PARAMS = 24;
uint256 public constant CHANGE_POOL = 25;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// The various sizes used in bytes.
uint256 constant ID_SIZE = 4;
uint256 constant ID_OFFSET_SIZE = 1;
uint256 constant WORD_SIZE = 32;
// The size that a delegate takes in the lookup table (Identifier + Offset).
uint256 constant TOTAL_ID_SIZE = 5; // ID_SIZE + ID_OFFSET_SIZE;
// The amount of bytes to go forward to get to the offset of the next delegate (aka. the end of the offset of the current delegate).
uint256 constant NEXT_DELEGATE_OFFSET = 9; // TOTAL_ID_SIZE + ID_SIZE;
// 1 word (32B) is reserved for the protocol .
uint256 constant RESERVED_SIZE = 32; // 1 * WORD_SIZE;
uint256 constant MIN_METADATA_LENGTH = 37; // RESERVED_SIZE + ID_SIZE + ID_OFFSET_SIZE;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import './JBDelegateMetadataConstants.sol';
/**
* @notice Library to parse and create delegate metadata
*
* @dev Metadata are built as:
* - 32B of reserved space for the protocol
* - a lookup table `delegateId: offset`, defining the offset of the metadata for each delegate.
* The offset fits 1 bytes, the ID 4 bytes. This table is padded to 32B.
* - the metadata for each delegate, padded to 32B each
*
* +-----------------------+ offset: 0
* | 32B reserved |
* +-----------------------+ offset: 1 = end of first 32B
* | (delegate1 ID,offset1)|
* | (delegate2 ID,offset2)|
* | 0's padding |
* +-----------------------+ offset: offset1 = 1 + number of words taken by the padded table
* | delegate 1 metadata1 |
* | 0's padding |
* +-----------------------+ offset: offset2 = offset1 + number of words taken by the metadata1
* | delegate 2 metadata2 |
* | 0's padding |
* +-----------------------+
*/
library JBDelegateMetadataLib {
/**
* @notice Parse the metadata to find the metadata for a specific delegate
*
* @dev Returns false and an empty bytes if no metadata is found
*
* @param _id The delegate id to find
* @param _metadata The metadata to parse
*
* @return _found Whether the metadata was found
* @return _targetMetadata The metadata for the delegate
*/
function getMetadata(bytes4 _id, bytes calldata _metadata) internal pure returns (bool _found, bytes memory _targetMetadata) {
// Either no metadata or empty one with only one selector (32+4+1)
if (_metadata.length <= MIN_METADATA_LENGTH) return (false, "");
// Get the first data offset - upcast to avoid overflow (same for other offset)
uint256 _firstOffset = uint8(_metadata[RESERVED_SIZE + ID_SIZE]);
// Parse the id's to find _id, stop when next offset == 0 or current = first offset
for (uint256 _i = RESERVED_SIZE; _metadata[_i + ID_SIZE] != bytes1(0) && _i < _firstOffset * WORD_SIZE;) {
uint256 _currentOffset = uint256(uint8(_metadata[_i + ID_SIZE]));
// _id found?
if (bytes4(_metadata[_i:_i + ID_SIZE]) == _id) {
// Are we at the end of the lookup table (either at the start of data's or next offset is 0/in the padding)
// If not, only return until from this offset to the begining of the next offset
uint256 _end = (_i + NEXT_DELEGATE_OFFSET >= _firstOffset * WORD_SIZE || _metadata[_i + NEXT_DELEGATE_OFFSET] == 0)
? _metadata.length
: uint256(uint8(_metadata[_i + NEXT_DELEGATE_OFFSET])) * WORD_SIZE;
return (true, _metadata[_currentOffset * WORD_SIZE:_end]);
}
unchecked {
_i += TOTAL_ID_SIZE;
}
}
}
/**
* @notice Add a delegate to an existing metadata
*
* @param _idToAdd The id of the delegate to add
* @param _dataToAdd The metadata of the delegate to add
* @param _originalMetadata The original metadata
*
* @return _newMetadata The new metadata with the delegate added
*/
function addToMetadata(bytes4 _idToAdd, bytes calldata _dataToAdd, bytes calldata _originalMetadata) public pure returns (bytes memory _newMetadata) {
// Get the first data offset - upcast to avoid overflow (same for other offset)...
uint256 _firstOffset = uint8(_originalMetadata[RESERVED_SIZE + ID_SIZE]);
// ...go back to the beginning of the previous word (ie the last word of the table, as it can be padded)
uint256 _lastWordOfTable = _firstOffset - 1;
// The last offset stored in the table and its index
uint256 _lastOffset;
uint256 _lastOffsetIndex;
// The number of words taken by the last data stored
uint256 _numberOfWordslastData;
// Iterate to find the last entry of the table, _lastOffset - we start from the end as the first value encountered
// will be the last offset
for(uint256 _i = _firstOffset * WORD_SIZE - 1; _i > _lastWordOfTable * WORD_SIZE - 1;) {
// If the byte is not 0, this is the last offset we're looking for
if (_originalMetadata[_i] != 0) {
_lastOffset = uint8(_originalMetadata[_i]);
_lastOffsetIndex = _i;
// No rounding as this should be padded to 32B
_numberOfWordslastData = (_originalMetadata.length - _lastOffset * WORD_SIZE) / WORD_SIZE;
// Copy the reserved word and the table and remove the previous padding
_newMetadata = _originalMetadata[0 : _lastOffsetIndex + 1];
// Check if the new entry is still fitting in this word
if(_i + TOTAL_ID_SIZE >= _firstOffset * WORD_SIZE) {
// Increment every offset by 1 (as the table now takes one more word)
for (uint256 _j = RESERVED_SIZE + ID_SIZE; _j < _lastOffsetIndex + 1; _j += TOTAL_ID_SIZE) {
_newMetadata[_j] = bytes1(uint8(_originalMetadata[_j]) + 1);
}
// Increment the last offset so the new offset will be properly set too
_lastOffset++;
}
break;
}
unchecked {
_i -= 1;
}
}
// Add the new entry after the last entry of the table, the new offset is the last offset + the number of words taken by the last data
_newMetadata = abi.encodePacked(_newMetadata, _idToAdd, bytes1(uint8(_lastOffset + _numberOfWordslastData)));
// Pad as needed - inlined for gas saving
uint256 _paddedLength =
_newMetadata.length % WORD_SIZE == 0 ? _newMetadata.length : (_newMetadata.length / WORD_SIZE + 1) * WORD_SIZE;
assembly {
mstore(_newMetadata, _paddedLength)
}
// Add existing data at the end
_newMetadata = abi.encodePacked(_newMetadata, _originalMetadata[_firstOffset * WORD_SIZE : _originalMetadata.length]);
// Pad as needed
_paddedLength =
_newMetadata.length % WORD_SIZE == 0 ? _newMetadata.length : (_newMetadata.length / WORD_SIZE + 1) * WORD_SIZE;
assembly {
mstore(_newMetadata, _paddedLength)
}
// Append new data at the end
_newMetadata = abi.encodePacked(_newMetadata, _dataToAdd);
// Pad again again as needed
_paddedLength =
_newMetadata.length % WORD_SIZE == 0 ? _newMetadata.length : (_newMetadata.length / WORD_SIZE + 1) * WORD_SIZE;
assembly {
mstore(_newMetadata, _paddedLength)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from './JBTokenAmount.sol';
/// @custom:member payer The address from which the payment originated.
/// @custom:member projectId The ID of the project for which the payment was made.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the payment is being made.
/// @custom:member amount The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member projectTokenCount The number of project tokens minted for the beneficiary.
/// @custom:member beneficiary The address to which the tokens were minted.
/// @custom:member preferClaimedTokens A flag indicating whether the request prefered to mint project tokens into the beneficiaries wallet rather than leaving them unclaimed. This is only possible if the project has an attached token contract.
/// @custom:member memo The memo that is being emitted alongside the payment.
/// @custom:member metadata Extra data to send to the delegate.
struct JBDidPayData {
address payer;
uint256 projectId;
uint256 currentFundingCycleConfiguration;
JBTokenAmount amount;
JBTokenAmount forwardedAmount;
uint256 projectTokenCount;
address beneficiary;
bool preferClaimedTokens;
string memo;
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from './JBTokenAmount.sol';
/// @custom:member payer The address from which the payment originated.
/// @custom:member projectId The ID of the project for which the payment was made.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the payment is being made.
/// @custom:member amount The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member projectTokenCount The number of project tokens minted for the beneficiary.
/// @custom:member beneficiary The address to which the tokens were minted.
/// @custom:member preferClaimedTokens A flag indicating whether the request prefered to mint project tokens into the beneficiaries wallet rather than leaving them unclaimed. This is only possible if the project has an attached token contract.
/// @custom:member memo The memo that is being emitted alongside the payment.
/// @custom:member dataSourceMetadata Extra data to send to the delegate sent by the data source.
/// @custom:member payerMetadata Extra data to send to the delegate sent by the payer.
struct JBDidPayData3_1_1 {
address payer;
uint256 projectId;
uint256 currentFundingCycleConfiguration;
JBTokenAmount amount;
JBTokenAmount forwardedAmount;
uint256 projectTokenCount;
address beneficiary;
bool preferClaimedTokens;
string memo;
bytes dataSourceMetadata;
bytes payerMetadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from './JBTokenAmount.sol';
/// @custom:member holder The holder of the tokens being redeemed.
/// @custom:member projectId The ID of the project with which the redeemed tokens are associated.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the redemption is being made.
/// @custom:member projectTokenCount The number of project tokens being redeemed.
/// @custom:member reclaimedAmount The amount reclaimed from the treasury. Includes the token being reclaimed, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member beneficiary The address to which the reclaimed amount will be sent.
/// @custom:member memo The memo that is being emitted alongside the redemption.
/// @custom:member metadata Extra data to send to the delegate.
struct JBDidRedeemData {
address holder;
uint256 projectId;
uint256 currentFundingCycleConfiguration;
uint256 projectTokenCount;
JBTokenAmount reclaimedAmount;
JBTokenAmount forwardedAmount;
address payable beneficiary;
string memo;
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from './JBTokenAmount.sol';
/// @custom:member holder The holder of the tokens being redeemed.
/// @custom:member projectId The ID of the project with which the redeemed tokens are associated.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the redemption is being made.
/// @custom:member projectTokenCount The number of project tokens being redeemed.
/// @custom:member reclaimedAmount The amount reclaimed from the treasury. Includes the token being reclaimed, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member beneficiary The address to which the reclaimed amount will be sent.
/// @custom:member memo The memo that is being emitted alongside the redemption.
/// @custom:member dataSourceMetadata Extra data to send to the delegate sent by the data source.
/// @custom:member redeemerMetadata Extra data to send to the delegate sent by the redeemer.
struct JBDidRedeemData3_1_1 {
address holder;
uint256 projectId;
uint256 currentFundingCycleConfiguration;
uint256 projectTokenCount;
JBTokenAmount reclaimedAmount;
JBTokenAmount forwardedAmount;
address payable beneficiary;
string memo;
bytes dataSourceMetadata;
bytes redeemerMetadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @custom:member amount The total amount the fee was taken from, as a fixed point number with the same number of decimals as the terminal in which this struct was created.
/// @custom:member fee The percent of the fee, out of MAX_FEE.
/// @custom:member feeDiscount The discount of the fee.
/// @custom:member beneficiary The address that will receive the tokens that are minted as a result of the fee payment.
struct JBFee {
uint256 amount;
uint32 fee;
uint32 feeDiscount;
address beneficiary;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBPaymentTerminal} from './../interfaces/IJBPaymentTerminal.sol';
/// @custom:member terminal The terminal within which the distribution limit and the overflow allowance applies.
/// @custom:member token The token for which the fund access constraints apply.
/// @custom:member distributionLimit The amount of the distribution limit, as a fixed point number with the same number of decimals as the terminal within which the limit applies.
/// @custom:member distributionLimitCurrency The currency of the distribution limit.
/// @custom:member overflowAllowance The amount of the allowance, as a fixed point number with the same number of decimals as the terminal within which the allowance applies.
/// @custom:member overflowAllowanceCurrency The currency of the overflow allowance.
struct JBFundAccessConstraints {
IJBPaymentTerminal terminal;
address token;
uint256 distributionLimit;
uint256 distributionLimitCurrency;
uint256 overflowAllowance;
uint256 overflowAllowanceCurrency;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBFundingCycleBallot} from './../interfaces/IJBFundingCycleBallot.sol';
/// @custom:member number The funding cycle number for the cycle's project. Each funding cycle has a number that is an increment of the cycle that directly preceded it. Each project's first funding cycle has a number of 1.
/// @custom:member configuration The timestamp when the parameters for this funding cycle were configured. This value will stay the same for subsequent funding cycles that roll over from an originally configured cycle.
/// @custom:member basedOn The `configuration` of the funding cycle that was active when this cycle was created.
/// @custom:member start The timestamp marking the moment from which the funding cycle is considered active. It is a unix timestamp measured in seconds.
/// @custom:member duration The number of seconds the funding cycle lasts for, after which a new funding cycle will start. A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties. If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle. If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
/// @custom:member weight A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on. For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
/// @custom:member discountRate A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`. If it's 0, each funding cycle will have equal weight. If the number is 90%, the next funding cycle will have a 10% smaller weight. This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
/// @custom:member ballot An address of a contract that says whether a proposed reconfiguration should be accepted or rejected. It can be used to create rules around how a project owner can change funding cycle parameters over time.
/// @custom:member metadata Extra data that can be associated with a funding cycle.
struct JBFundingCycle {
uint256 number;
uint256 configuration;
uint256 basedOn;
uint256 start;
uint256 duration;
uint256 weight;
uint256 discountRate;
IJBFundingCycleBallot ballot;
uint256 metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBFundingCycleBallot} from './../interfaces/IJBFundingCycleBallot.sol';
/// @custom:member duration The number of seconds the funding cycle lasts for, after which a new funding cycle will start. A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties. If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle. If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
/// @custom:member weight A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on. For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
/// @custom:member discountRate A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`. If it's 0, each funding cycle will have equal weight. If the number is 90%, the next funding cycle will have a 10% smaller weight. This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
/// @custom:member ballot An address of a contract that says whether a proposed reconfiguration should be accepted or rejected. It can be used to create rules around how a project owner can change funding cycle parameters over time.
struct JBFundingCycleData {
uint256 duration;
uint256 weight;
uint256 discountRate;
IJBFundingCycleBallot ballot;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBGlobalFundingCycleMetadata} from './JBGlobalFundingCycleMetadata.sol';
/// @custom:member global Data used globally in non-migratable ecosystem contracts.
/// @custom:member reservedRate The reserved rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_RESERVED_RATE`.
/// @custom:member redemptionRate The redemption rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
/// @custom:member ballotRedemptionRate The redemption rate to use during an active ballot of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
/// @custom:member pausePay A flag indicating if the pay functionality should be paused during the funding cycle.
/// @custom:member pauseDistributions A flag indicating if the distribute functionality should be paused during the funding cycle.
/// @custom:member pauseRedeem A flag indicating if the redeem functionality should be paused during the funding cycle.
/// @custom:member pauseBurn A flag indicating if the burn functionality should be paused during the funding cycle.
/// @custom:member allowMinting A flag indicating if minting tokens should be allowed during this funding cycle.
/// @custom:member allowTerminalMigration A flag indicating if migrating terminals should be allowed during this funding cycle.
/// @custom:member allowControllerMigration A flag indicating if migrating controllers should be allowed during this funding cycle.
/// @custom:member holdFees A flag indicating if fees should be held during this funding cycle.
/// @custom:member preferClaimedTokenOverride A flag indicating if claimed tokens should always be prefered to unclaimed tokens when minting.
/// @custom:member useTotalOverflowForRedemptions A flag indicating if redemptions should use the project's balance held in all terminals instead of the project's local terminal balance from which the redemption is being fulfilled.
/// @custom:member useDataSourceForPay A flag indicating if the data source should be used for pay transactions during this funding cycle.
/// @custom:member useDataSourceForRedeem A flag indicating if the data source should be used for redeem transactions during this funding cycle.
/// @custom:member dataSource The data source to use during this funding cycle.
/// @custom:member metadata Metadata of the metadata, up to uint8 in size.
struct JBFundingCycleMetadata {
JBGlobalFundingCycleMetadata global;
uint256 reservedRate;
uint256 redemptionRate;
uint256 ballotRedemptionRate;
bool pausePay;
bool pauseDistributions;
bool pauseRedeem;
bool pauseBurn;
bool allowMinting;
bool allowTerminalMigration;
bool allowControllerMigration;
bool holdFees;
bool preferClaimedTokenOverride;
bool useTotalOverflowForRedemptions;
bool useDataSourceForPay;
bool useDataSourceForRedeem;
address dataSource;
uint256 metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @custom:member allowSetTerminals A flag indicating if setting terminals should be allowed during this funding cycle.
/// @custom:member allowSetController A flag indicating if setting a new controller should be allowed during this funding cycle.
/// @custom:member pauseTransfers A flag indicating if the project token transfer functionality should be paused during the funding cycle.
struct JBGlobalFundingCycleMetadata {
bool allowSetTerminals;
bool allowSetController;
bool pauseTransfers;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBSplit} from './JBSplit.sol';
/// @custom:member group The group indentifier.
/// @custom:member splits The splits to associate with the group.
struct JBGroupedSplits {
uint256 group;
JBSplit[] splits;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import {IJBOperatable} from './../interfaces/IJBOperatable.sol';
import {IJBOperatorStore} from './../interfaces/IJBOperatorStore.sol';
/// @notice Modifiers to allow access to functions based on the message sender's operator status.
abstract contract JBOperatable is IJBOperatable {
//*********************************************************************//
// --------------------------- custom errors -------------------------- //
//*********************************************************************//
error UNAUTHORIZED();
//*********************************************************************//
// ---------------------------- modifiers ---------------------------- //
//*********************************************************************//
/// @notice Only allows the speficied account or an operator of the account to proceed.
/// @param _account The account to check for.
/// @param _domain The domain namespace to look for an operator within.
/// @param _permissionIndex The index of the permission to check for.
modifier requirePermission(
address _account,
uint256 _domain,
uint256 _permissionIndex
) {
_requirePermission(_account, _domain, _permissionIndex);
_;
}
/// @notice Only allows the speficied account, an operator of the account to proceed, or a truthy override flag.
/// @param _account The account to check for.
/// @param _domain The domain namespace to look for an operator within.
/// @param _permissionIndex The index of the permission to check for.
/// @param _override A condition to force allowance for.
modifier requirePermissionAllowingOverride(
address _account,
uint256 _domain,
uint256 _permissionIndex,
bool _override
) {
_requirePermissionAllowingOverride(_account, _domain, _permissionIndex, _override);
_;
}
//*********************************************************************//
// ---------------- public immutable stored properties --------------- //
//*********************************************************************//
/// @notice A contract storing operator assignments.
IJBOperatorStore public immutable override operatorStore;
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/// @param _operatorStore A contract storing operator assignments.
constructor(IJBOperatorStore _operatorStore) {
operatorStore = _operatorStore;
}
//*********************************************************************//
// -------------------------- internal views ------------------------- //
//*********************************************************************//
/// @notice Require the message sender is either the account or has the specified permission.
/// @param _account The account to allow.
/// @param _domain The domain namespace within which the permission index will be checked.
/// @param _permissionIndex The permission index that an operator must have within the specified domain to be allowed.
function _requirePermission(
address _account,
uint256 _domain,
uint256 _permissionIndex
) internal view {
if (
msg.sender != _account &&
!operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
!operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
) revert UNAUTHORIZED();
}
/// @notice Require the message sender is either the account, has the specified permission, or the override condition is true.
/// @param _account The account to allow.
/// @param _domain The domain namespace within which the permission index will be checked.
/// @param _domain The permission index that an operator must have within the specified domain to be allowed.
/// @param _override The override condition to allow.
function _requirePermissionAllowingOverride(
address _account,
uint256 _domain,
uint256 _permissionIndex,
bool _override
) internal view {
if (
!_override &&
msg.sender != _account &&
!operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
!operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
) revert UNAUTHORIZED();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @custom:member operator The address of the operator.
/// @custom:member domain The domain within which the operator is being given permissions. A domain of 0 is a wildcard domain, which gives an operator access to all domains.
/// @custom:member permissionIndexes The indexes of the permissions the operator is being given.
struct JBOperatorData {
address operator;
uint256 domain;
uint256[] permissionIndexes;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBPayDelegate3_1_1} from '../interfaces/IJBPayDelegate3_1_1.sol';
/// @custom:member delegate A delegate contract to use for subsequent calls.
/// @custom:member amount The amount to send to the delegate.
/// @custom:member metadata Metadata to pass the delegate.
struct JBPayDelegateAllocation3_1_1 {
IJBPayDelegate3_1_1 delegate;
uint256 amount;
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBPaymentTerminal} from './../interfaces/IJBPaymentTerminal.sol';
import {JBTokenAmount} from './JBTokenAmount.sol';
/// @custom:member terminal The terminal that is facilitating the payment.
/// @custom:member payer The address from which the payment originated.
/// @custom:member amount The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member projectId The ID of the project being paid.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the payment is being made.
/// @custom:member beneficiary The specified address that should be the beneficiary of anything that results from the payment.
/// @custom:member weight The weight of the funding cycle during which the payment is being made.
/// @custom:member reservedRate The reserved rate of the funding cycle during which the payment is being made.
/// @custom:member memo The memo that was sent alongside the payment.
/// @custom:member metadata Extra data provided by the payer.
struct JBPayParamsData {
IJBPaymentTerminal terminal;
address payer;
JBTokenAmount amount;
uint256 projectId;
uint256 currentFundingCycleConfiguration;
address beneficiary;
uint256 weight;
uint256 reservedRate;
string memo;
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @custom:member content The metadata content.
/// @custom:member domain The domain within which the metadata applies.
struct JBProjectMetadata {
string content;
uint256 domain;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBPaymentTerminal} from './../interfaces/IJBPaymentTerminal.sol';
import {JBTokenAmount} from './JBTokenAmount.sol';
/// @custom:member terminal The terminal that is facilitating the redemption.
/// @custom:member holder The holder of the tokens being redeemed.
/// @custom:member projectId The ID of the project whos tokens are being redeemed.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the redemption is being made.
/// @custom:member tokenCount The proposed number of tokens being redeemed, as a fixed point number with 18 decimals.
/// @custom:member totalSupply The total supply of tokens used in the calculation, as a fixed point number with 18 decimals.
/// @custom:member overflow The amount of overflow used in the reclaim amount calculation.
/// @custom:member reclaimAmount The amount that should be reclaimed by the redeemer using the protocol's standard bonding curve redemption formula. Includes the token being reclaimed, the reclaim value, the number of decimals included, and the currency of the reclaim amount.
/// @custom:member useTotalOverflow If overflow across all of a project's terminals is being used when making redemptions.
/// @custom:member redemptionRate The redemption rate of the funding cycle during which the redemption is being made.
/// @custom:member memo The proposed memo that is being emitted alongside the redemption.
/// @custom:member metadata Extra data provided by the redeemer.
struct JBRedeemParamsData {
IJBPaymentTerminal terminal;
address holder;
uint256 projectId;
uint256 currentFundingCycleConfiguration;
uint256 tokenCount;
uint256 totalSupply;
uint256 overflow;
JBTokenAmount reclaimAmount;
bool useTotalOverflow;
uint256 redemptionRate;
string memo;
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBRedemptionDelegate3_1_1} from '../interfaces/IJBRedemptionDelegate3_1_1.sol';
/// @custom:member delegate A delegate contract to use for subsequent calls.
/// @custom:member amount The amount to send to the delegate.
/// @custom:member metadata Metadata to pass the delegate.
struct JBRedemptionDelegateAllocation3_1_1 {
IJBRedemptionDelegate3_1_1 delegate;
uint256 amount;
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBSplitAllocator} from './../interfaces/IJBSplitAllocator.sol';
/// @custom:member preferClaimed A flag that only has effect if a projectId is also specified, and the project has a token contract attached. If so, this flag indicates if the tokens that result from making a payment to the project should be delivered claimed into the beneficiary's wallet, or unclaimed to save gas.
/// @custom:member preferAddToBalance A flag indicating if a distribution to a project should prefer triggering it's addToBalance function instead of its pay function.
/// @custom:member percent The percent of the whole group that this split occupies. This number is out of `JBConstants.SPLITS_TOTAL_PERCENT`.
/// @custom:member projectId The ID of a project. If an allocator is not set but a projectId is set, funds will be sent to the protocol treasury belonging to the project who's ID is specified. Resulting tokens will be routed to the beneficiary with the claimed token preference respected.
/// @custom:member beneficiary An address. The role the of the beneficary depends on whether or not projectId is specified, and whether or not an allocator is specified. If allocator is set, the beneficiary will be forwarded to the allocator for it to use. If allocator is not set but projectId is set, the beneficiary is the address to which the project's tokens will be sent that result from a payment to it. If neither allocator or projectId are set, the beneficiary is where the funds from the split will be sent.
/// @custom:member lockedUntil Specifies if the split should be unchangeable until the specified time, with the exception of extending the locked period.
/// @custom:member allocator If an allocator is specified, funds will be sent to the allocator contract along with all properties of this split.
struct JBSplit {
bool preferClaimed;
bool preferAddToBalance;
uint256 percent;
uint256 projectId;
address payable beneficiary;
uint256 lockedUntil;
IJBSplitAllocator allocator;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBSplit} from './JBSplit.sol';
/// @custom:member token The token being sent to the split allocator.
/// @custom:member amount The amount being sent to the split allocator, as a fixed point number.
/// @custom:member decimals The number of decimals in the amount.
/// @custom:member projectId The project to which the split belongs.
/// @custom:member group The group to which the split belongs.
/// @custom:member split The split that caused the allocation.
struct JBSplitAllocationData {
address token;
uint256 amount;
uint256 decimals;
uint256 projectId;
uint256 group;
JBSplit split;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @custom:member token The token the payment was made in.
/// @custom:member value The amount of tokens that was paid, as a fixed point number.
/// @custom:member decimals The number of decimals included in the value fixed point number.
/// @custom:member currency The expected currency of the value.
struct JBTokenAmount {
address token;
uint256 value;
uint256 decimals;
uint256 currency;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library JBTokens {
/// @notice The ETH token address in Juicebox is represented by 0x000000000000000000000000000000000000EEEe.
address public constant ETH = address(0x000000000000000000000000000000000000EEEe);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
/// @param pool Address of the pool that we want to observe
/// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
/// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
/// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
function consult(address pool, uint32 secondsAgo)
internal
view
returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
{
require(secondsAgo != 0, 'BP');
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool)
.observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] -
secondsPerLiquidityCumulativeX128s[0];
arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;
// We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
/// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
(, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 0, 'NI');
(uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations(
(observationIndex + 1) % observationCardinality
);
// The next index might not be initialized if the cardinality is in the process of increasing
// In this case the oldest observation is always in index 0
if (!initialized) {
(observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
}
unchecked {
secondsAgo = uint32(block.timestamp) - observationTimestamp;
}
}
/// @notice Given a pool, it returns the tick value as of the start of the current block
/// @param pool Address of Uniswap V3 pool
/// @return The tick that the pool was in at the start of the current block
function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {
(, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
// 2 observations are needed to reliably calculate the block starting tick
require(observationCardinality > 1, 'NEO');
// If the latest observation occurred in the past, then no tick-changing trades have happened in this block
// therefore the tick in `slot0` is the same as at the beginning of the current block.
// We don't need to check if this observation is initialized - it is guaranteed to be.
(
uint32 observationTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
) = IUniswapV3Pool(pool).observations(observationIndex);
if (observationTimestamp != uint32(block.timestamp)) {
return (tick, IUniswapV3Pool(pool).liquidity());
}
uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
(
uint32 prevObservationTimestamp,
int56 prevTickCumulative,
uint160 prevSecondsPerLiquidityCumulativeX128,
bool prevInitialized
) = IUniswapV3Pool(pool).observations(prevIndex);
require(prevInitialized, 'ONI');
uint32 delta = observationTimestamp - prevObservationTimestamp;
tick = int24((tickCumulative - int56(uint56(prevTickCumulative))) / int56(uint56(delta)));
uint128 liquidity = uint128(
(uint192(delta) * type(uint160).max) /
(uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)
);
return (tick, liquidity);
}
/// @notice Information for calculating a weighted arithmetic mean tick
struct WeightedTickData {
int24 tick;
uint128 weight;
}
/// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick
/// @param weightedTickData An array of ticks and weights
/// @return weightedArithmeticMeanTick The weighted arithmetic mean tick
/// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,
/// extreme care must be taken to ensure that ticks are comparable (including decimal differences).
/// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.
function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)
internal
pure
returns (int24 weightedArithmeticMeanTick)
{
// Accumulates the sum of products between each tick and its weight
int256 numerator;
// Accumulates the sum of the weights
uint256 denominator;
// Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic
for (uint256 i; i < weightedTickData.length; i++) {
numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));
denominator += weightedTickData[i].weight;
}
weightedArithmeticMeanTick = int24(numerator / int256(denominator));
// Always round to negative infinity
if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;
}
/// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last
/// @dev Useful for calculating relative prices along routes.
/// @dev There must be one tick for each pairwise set of tokens.
/// @param tokens The token contract addresses
/// @param ticks The ticks, representing the price of each token pair in `tokens`
/// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`
function getChainedPrice(address[] memory tokens, int24[] memory ticks)
internal
pure
returns (int256 syntheticTick)
{
require(tokens.length - 1 == ticks.length, 'DL');
for (uint256 i = 1; i <= ticks.length; i++) {
// check the tokens for address sort order, then accumulate the
// ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out"
tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
error T();
error R();
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
if (absTick > uint256(int256(MAX_TICK))) revert T();
uint256 ratio = absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// second inequality must be < because the price can never reach the price at the max tick
if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
{
"compilationTarget": {
"contracts/JBBuybackDelegate.sol": "JBBuybackDelegate"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@chainlink/=node_modules/@chainlink/",
":@ensdomains/=node_modules/@ensdomains/",
":@exhausted-pigeon/=node_modules/@exhausted-pigeon/",
":@jbx-protocol/=node_modules/@jbx-protocol/",
":@openzeppelin/=node_modules/@openzeppelin/",
":@paulrberg/=node_modules/@paulrberg/",
":@prb/=node_modules/@prb/",
":@uniswap/=node_modules/@uniswap/",
":base64-sol/=node_modules/base64-sol/",
":ds-test/=node_modules/ds-test/src/",
":forge-std/=node_modules/forge-std/src/",
":prb-math/=node_modules/prb-math/"
]
}
[{"inputs":[{"internalType":"contract IWETH9","name":"_weth","type":"address"},{"internalType":"address","name":"_factory","type":"address"},{"internalType":"contract IJBDirectory","name":"_directory","type":"address"},{"internalType":"contract IJBController3_1","name":"_controller","type":"address"},{"internalType":"bytes4","name":"_delegateId","type":"bytes4"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"JuiceBuyback_InsufficientPayAmount","type":"error"},{"inputs":[],"name":"JuiceBuyback_InvalidTwapSlippageTolerance","type":"error"},{"inputs":[],"name":"JuiceBuyback_InvalidTwapWindow","type":"error"},{"inputs":[],"name":"JuiceBuyback_MaximumSlippage","type":"error"},{"inputs":[],"name":"JuiceBuyback_NewSecondsAgoTooLow","type":"error"},{"inputs":[],"name":"JuiceBuyback_NoProjectToken","type":"error"},{"inputs":[],"name":"JuiceBuyback_NotEnoughTokensReceived","type":"error"},{"inputs":[],"name":"JuiceBuyback_PoolAlreadySet","type":"error"},{"inputs":[],"name":"JuiceBuyback_TransferFailed","type":"error"},{"inputs":[],"name":"JuiceBuyback_Unauthorized","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[],"name":"T","type":"error"},{"inputs":[],"name":"UNAUTHORIZED","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokenCount","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":true,"internalType":"address","name":"terminalToken","type":"address"},{"indexed":false,"internalType":"address","name":"newPool","type":"address"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_PoolAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldTwapDelta","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTwapDelta","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_TwapSlippageToleranceChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldSecondsAgo","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newSecondsAgo","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_TwapWindowChanged","type":"event"},{"inputs":[],"name":"CONTROLLER","outputs":[{"internalType":"contract IJBController3_1","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DELEGATE_ID","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DIRECTORY","outputs":[{"internalType":"contract IJBDirectory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_TWAP_SLIPPAGE_TOLERANCE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_TWAP_WINDOW","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_TWAP_SLIPPAGE_TOLERANCE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_TWAP_WINDOW","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PROJECTS","outputs":[{"internalType":"contract IJBProjects","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SLIPPAGE_DENOMINATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNISWAP_V3_FACTORY","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"contract IWETH9","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"payer","type":"address"},{"internalType":"uint256","name":"projectId","type":"uint256"},{"internalType":"uint256","name":"currentFundingCycleConfiguration","type":"uint256"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"amount","type":"tuple"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"forwardedAmount","type":"tuple"},{"internalType":"uint256","name":"projectTokenCount","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bool","name":"preferClaimedTokens","type":"bool"},{"internalType":"string","name":"memo","type":"string"},{"internalType":"bytes","name":"dataSourceMetadata","type":"bytes"},{"internalType":"bytes","name":"payerMetadata","type":"bytes"}],"internalType":"struct JBDidPayData3_1_1","name":"_data","type":"tuple"}],"name":"didPay","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"operatorStore","outputs":[{"internalType":"contract IJBOperatorStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IJBPaymentTerminal","name":"terminal","type":"address"},{"internalType":"address","name":"payer","type":"address"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"amount","type":"tuple"},{"internalType":"uint256","name":"projectId","type":"uint256"},{"internalType":"uint256","name":"currentFundingCycleConfiguration","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"weight","type":"uint256"},{"internalType":"uint256","name":"reservedRate","type":"uint256"},{"internalType":"string","name":"memo","type":"string"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBPayParamsData","name":"_data","type":"tuple"}],"name":"payParams","outputs":[{"internalType":"uint256","name":"weight","type":"uint256"},{"internalType":"string","name":"memo","type":"string"},{"components":[{"internalType":"contract IJBPayDelegate3_1_1","name":"delegate","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBPayDelegateAllocation3_1_1[]","name":"delegateAllocations","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"address","name":"_terminalToken","type":"address"}],"name":"poolOf","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"}],"name":"projectTokenOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IJBPaymentTerminal","name":"terminal","type":"address"},{"internalType":"address","name":"holder","type":"address"},{"internalType":"uint256","name":"projectId","type":"uint256"},{"internalType":"uint256","name":"currentFundingCycleConfiguration","type":"uint256"},{"internalType":"uint256","name":"tokenCount","type":"uint256"},{"internalType":"uint256","name":"totalSupply","type":"uint256"},{"internalType":"uint256","name":"overflow","type":"uint256"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"reclaimAmount","type":"tuple"},{"internalType":"bool","name":"useTotalOverflow","type":"bool"},{"internalType":"uint256","name":"redemptionRate","type":"uint256"},{"internalType":"string","name":"memo","type":"string"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBRedeemParamsData","name":"_data","type":"tuple"}],"name":"redeemParams","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"string","name":"","type":"string"},{"components":[{"internalType":"contract IJBRedemptionDelegate3_1_1","name":"delegate","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBRedemptionDelegateAllocation3_1_1[]","name":"delegateAllocations","type":"tuple[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"uint24","name":"_fee","type":"uint24"},{"internalType":"uint32","name":"_twapWindow","type":"uint32"},{"internalType":"uint256","name":"_twapSlippageTolerance","type":"uint256"},{"internalType":"address","name":"_terminalToken","type":"address"}],"name":"setPoolFor","outputs":[{"internalType":"contract IUniswapV3Pool","name":"newPool","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"uint256","name":"_newSlippageTolerance","type":"uint256"}],"name":"setTwapSlippageToleranceOf","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"uint32","name":"_newWindow","type":"uint32"}],"name":"setTwapWindowOf","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"_interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"}],"name":"twapSlippageToleranceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"}],"name":"twapWindowOf","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"_amount0Delta","type":"int256"},{"internalType":"int256","name":"_amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"}]