Проверенный контрактТочноеBUSL-1.1
ReserveMigrationViewLib
Адрес0xd666cc0f9f04a4e02cb9770932e91dcafdafec7d
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.30
- Тот же код
ещё 1 контракт
Подробности
- Компилятор
- solc 0.8.30+commit.73712a01
- Язык
- solidity
- Оптимизация
- Да, 100 прогонов
- Версия EVM
- cancun
- Лицензия
- BUSL-1.1
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 459 486
- Транзакция создания
- 0xf5c475fc4c…97975ca9e0
12 файлов
- src/libraries/ReserveMigrationViewLib.solглавный1,14 КБ
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1,97 КБ
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32,15 КБ
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34,94 КБ
- src/interfaces/IAccrualMigration.sol2,22 КБ
- src/interfaces/IContinuousAccrual.sol4,69 КБ
- src/libraries/AccrualBook.sol23,61 КБ
- src/libraries/AccrualLoans.sol49,12 КБ
- src/libraries/AccrualMath.sol8,76 КБ
- src/libraries/AccrualSchedule.sol10,13 КБ
- src/libraries/AccrualSegments.sol8,37 КБ
- src/libraries/ReserveAccrualStorageLib.sol5,04 КБ
src/libraries/ReserveMigrationViewLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IAccrualMigration} from "../interfaces/IAccrualMigration.sol";
import {ReserveAccrualStorageLib} from "./ReserveAccrualStorageLib.sol";
/// @title ReserveMigrationViewLib
/// @notice Read-only encoding of the bounded continuous-accrual import session.
library ReserveMigrationViewLib {
/// @notice Compiler-encoded preparation status, forwarded by the host's view-only return helper.
function progressData() public view returns (bytes memory) {
ReserveAccrualStorageLib.Migration storage m = ReserveAccrualStorageLib.state().migration;
return abi.encode(
IAccrualMigration.Progress({
nonce: m.nonce,
sessionKey: m.sessionKey,
cutoff: m.cutoff,
expected: m.expected,
imported: m.imported,
originalFace: m.originalFace,
importedOriginalFace: m.importedOriginalFace,
nextFacilityId: m.imported < m.expected ? m.facilityIds[m.imported] : 0,
active: m.active
})
);
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/interfaces/IAccrualMigration.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @notice One governed, attested transition from recorded legacy debt to continuous accrual.
interface IAccrualMigration {
/// @notice Contractual debt and its original current-period cursor at the migration cutoff.
/// @dev Terms, asset, identity and recorded face come from the frozen native records.
/// nextCapitalization is zero for cash or for PIK with no further signed capitalization.
struct Opening {
uint256 facilityId;
uint256 principal;
uint256 interest;
uint256 frozenPikBasis;
uint64 periodStart;
uint64 nextCapitalization;
// A replacement approval can authorize identical balances after a revoked or mistimed fact.
// The session roster still admits the facility once, regardless of this signed reference.
bytes32 approvalRef;
}
/// @notice Constant-time preparation status; nextFacilityId is zero when all rows are imported.
struct Progress {
uint256 nonce;
bytes32 sessionKey;
uint64 cutoff;
uint32 expected;
uint32 imported;
uint256 originalFace;
uint256 importedOriginalFace;
uint256 nextFacilityId;
bool active;
}
/// @notice Begins or advances a governed migration, or cancels it before its first import.
/// @dev step = abi.encode(uint8 action, bytes body). Actions: 0 begins with
/// abi.encode(uint256[] sortedFacilityIds); 1 imports abi.encode(Opening[]);
/// 2 cancels with an empty body. Imports contain at most eight rows.
function prepareContinuousAccrualMigration(bytes calldata step) external;
/// @notice Returns preparation progress without quoting or advancing a partially imported book.
function accrualMigration() external view returns (Progress memory);
}
/// @notice Reserve-only continuation that installs opening risk after native face has been posted.
interface IAccrualMigrationRisk {
/// @return marked True even for a marked facility whose previous recorded contribution was zero.
function onAccrualOpening(uint256 facilityId, uint256 income) external returns (bool marked);
}
src/interfaces/IContinuousAccrual.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IContinuousAccrual
/// @notice Reserve-owned accounting and exact delivery of previously accrued interest.
/// @dev Separate from the legacy reserve interface so activation is explicit. Amounts are
/// normalized to 18 decimals. Delivery changes physical balances, never economic ownership.
interface IContinuousAccrual {
/// @notice Modules bound to one independently backed chain instance.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Modules {
address token;
address controller;
address vault;
address waterfall;
address bridge;
address registry;
address defaultManager;
}
/// @notice Constant-time accounting, capped at the first unprocessed schedule boundary.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Snapshot {
uint256 gross;
uint256 unposted;
uint256 unissued;
uint256 seniorUnissued;
uint256 feeUnissued;
address feeRecipient;
uint64 accruedThrough;
bool enabled;
bool fresh;
}
/// @notice Vault-computed prices and permission for a neutral physical delivery.
/// @dev entryAssets includes any unvested assets; assets is the ordinary share-price base.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct PricingState {
uint256 assets;
uint256 entryAssets;
uint256 redemptionAssets;
uint256 performanceAssets;
uint256 feeAdjustedShares;
bool materializationAllowed;
}
/// @notice One immutable, same-transaction permit and coherent public price snapshot.
/// @dev Unselected amounts are zero. A zero/default inactive record grants no authority.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Delivery {
uint256 nonce;
uint256 senior;
uint256 fee;
uint256 effectiveSupply;
uint256 backing;
uint256 recognizedBacking;
PricingState pricing;
address controller;
address vault;
address feeRecipient;
uint64 accruedThrough;
uint8 legs;
bool active;
}
/// @notice Reads the configured module identities, including before activation.
function accrualModules() external view returns (Modules memory);
/// @notice Reads recognized income and its outstanding physical posting/issuance.
function accrualSnapshot() external view returns (Snapshot memory);
/// @notice Reads the current delivery permit, or an inactive default record.
function accrualDelivery() external view returns (Delivery memory);
/// @notice Refuses a price-sensitive write at an unresolved accrual boundary or operation.
function requireAccrualFresh() external view;
/// @notice Delivers selected existing claims: senior=1, fee=2, both=3.
/// @dev No amount, destination, timestamp or fee rate is supplied by the caller.
function materializeAccrued(uint8 legs) external returns (uint256 senior, uint256 fee);
}
/// @notice Token continuation accepting only the bound reserve's current exact permit.
interface IAccrualToken {
/// @notice The immutable-once-configured accounting reserve, or zero before binding.
function accrualReserve() external view returns (address);
/// @notice Mints the selected legs of one unused, active delivery permit.
function mintAccrued(uint256 nonce) external;
}
/// @notice Controller continuation, callable only by its configured reserve.
interface IAccrualController {
/// @notice Relays one exact reserve-owned delivery permit to the token.
function mintAccrued(uint256 nonce) external;
}
/// @notice Vault views needed to admit a neutral delivery without a guarded write callback.
interface IAccrualVault {
/// @notice The immutable-once-configured accounting reserve, or zero before binding.
function accrualReserve() external view returns (address);
/// @notice Supplies a coherent price snapshot and current delivery admission state.
function accrualPricingState() external view returns (IContinuousAccrual.PricingState memory);
}
/// @title IReliefPricingCache
/// @notice Optional exact-discount preparation; it grants no financial authority.
interface IReliefPricingCache {
/// @notice Derives reusable discounts from current protocol state, without caller-supplied values.
function prepareReliefPricing() external;
}
src/libraries/AccrualBook.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {AccrualSchedule} from "./AccrualSchedule.sol";
/// @title AccrualBook
/// @notice Additive continuous loan-interest accounting, posting, issuance and risk cohorts.
/// @dev Embed Book in the reserve's ERC-7201 namespace. All methods are internal and perform no
/// external calls. The host validates funded contractual terms and owns authority, timestamps,
/// capacity admission, cash custody, registry posting and token issuance. Segment slopes are
/// integer normalized wei per second, so facility and aggregate amounts add exactly. The
/// remainder is recognized once at the scheduled endpoint, or cumulatively before an
/// authenticated lifecycle change. At most one year per technical segment bounds the interim
/// lag below 31,536,000 normalized wei per facility relative to its endpoint interpolation.
/// Technical segment boundaries do not themselves change a loan's contractual PIK basis.
library AccrualBook {
using AccrualSchedule for AccrualSchedule.Heap;
uint64 internal constant MAX_SEGMENT_SECONDS = 365 days;
uint32 internal constant MAX_FACILITIES = 100;
/// @notice An exactly additive integer rate and its settled value.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Clock {
uint256 value;
uint256 rate;
uint64 at;
}
/// @notice Recognition and posting totals for one exposure grouping.
struct Group {
Clock clock;
uint256 posted;
}
/// @notice A funded facility's cumulative recognition and current technical segment.
/// @dev keys are distinct domain-separated class, borrower and jurisdiction identifiers.
struct Entry {
Clock clock;
uint256 posted;
uint256 segmentAmount;
uint256 roundingCredited;
uint64 start;
uint64 end;
bytes32[3] keys;
bool known;
bool registered;
bool scheduled;
bool pastDue;
}
/// @notice The reserve-local authoritative book.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Book {
Clock total;
mapping(uint256 facilityId => Entry) entries;
mapping(bytes32 key => Group) groups;
mapping(bytes32 classKey => Clock) pastDueUnposted;
AccrualSchedule.Heap schedule;
uint256 posted;
uint256 seniorIssued;
uint256 feeIssued;
uint256 feeBaseGross;
uint256 feeBaseAmount;
uint32 registered;
uint16 feeBps;
bool initialized;
uint256 unearned;
}
/// @notice A coherent view capped at the first unprocessed boundary.
struct Snapshot {
uint256 gross;
uint256 fee;
uint256 unposted;
uint256 unissued;
uint256 seniorUnissued;
uint256 feeUnissued;
uint64 accruedThrough;
bool fresh;
}
/// @notice An uninitialized book cannot accept accounting changes.
error AccrualBook_NotInitialized();
/// @notice Reinitialization would discard existing obligations.
error AccrualBook_AlreadyInitialized();
/// @notice An interest fee cannot exceed the gross interest earned.
error AccrualBook_InvalidFee(uint16 feeBps);
/// @notice Issuance selects senior (1), protocol fee (2), or both (3), and no other mask.
error AccrualBook_InvalidIssuanceLegs(uint8 legs);
/// @notice The initial 100-facility admission envelope is full.
error AccrualBook_Capacity();
/// @notice Facility identifiers cannot be reused, including after retirement.
error AccrualBook_KnownFacility(uint256 facilityId);
/// @notice The facility is not registered in this book.
error AccrualBook_UnknownFacility(uint256 facilityId);
/// @notice A facility can have only one active technical segment.
error AccrualBook_AlreadyScheduled(uint256 facilityId);
/// @notice Technical segments must be positive and no longer than one year.
error AccrualBook_InvalidSegment(uint64 start, uint64 end);
/// @notice Exposure grouping identifiers must be nonzero and pairwise distinct.
error AccrualBook_InvalidKeys();
/// @notice An accounting clock cannot be read or changed backwards.
error AccrualBook_TimeReversed(uint64 previous, uint64 requested);
/// @notice Chronological maintenance must process the earliest boundary first.
error AccrualBook_BoundaryPending(uint64 boundary, uint64 requested);
/// @notice No scheduled boundary is due at the supplied time.
error AccrualBook_NoBoundaryDue();
/// @notice Retirement requires no scheduled segment and no unposted interest.
error AccrualBook_UnsettledFacility(uint256 facilityId);
/// @notice An arithmetic result would exceed uint256.
error AccrualBook_Overflow();
/// @notice Records the start of the book and the configured gross-interest fee.
function initialize(Book storage self, uint64 at, uint16 feeBps) internal {
if (self.initialized) revert AccrualBook_AlreadyInitialized();
_validateFee(feeBps);
self.total.at = at;
self.feeBps = feeBps;
self.initialized = true;
}
/// @notice Registers a proved funded facility and its immutable exposure identities.
/// @dev Does not itself create interest, change principal or install a contractual schedule.
function register(Book storage self, uint256 facilityId, bytes32[3] memory keys, uint64 at) internal {
_requireInitialized(self);
requireFresh(self, at);
Entry storage e = self.entries[facilityId];
if (e.known) revert AccrualBook_KnownFacility(facilityId);
if (self.registered == MAX_FACILITIES) revert AccrualBook_Capacity();
if (
keys[0] == 0 || keys[1] == 0 || keys[2] == 0 || keys[0] == keys[1] || keys[0] == keys[2]
|| keys[1] == keys[2]
) revert AccrualBook_InvalidKeys();
_settleTotal(self, at);
e.clock.at = at;
e.keys = keys;
e.known = true;
e.registered = true;
++self.registered;
}
/// @notice Starts a proved fixed-endpoint segment at the accounting frontier.
/// @dev A host may continue a completed segment at its historical boundary during catch-up.
/// It must install the successor atomically with finishNext; no external callback may see
/// a missing successor. The endpoint excludes amounts recognized by earlier segments.
function open(Book storage self, uint256 facilityId, uint256 amount, uint64 start, uint64 end) internal {
Entry storage e = _entry(self, facilityId);
_requireTime(self, start);
if (e.scheduled) revert AccrualBook_AlreadyScheduled(facilityId);
if (end <= start || end - start > MAX_SEGMENT_SECONDS) {
revert AccrualBook_InvalidSegment(start, end);
}
_settleTotal(self, start);
// Reserve the entire endpoint before admitting a slope. Otherwise several individually
// valid endpoints could make every future NAV read overflow, after admission succeeded.
if (amount > type(uint256).max - self.total.value - self.unearned) revert AccrualBook_Overflow();
self.unearned += amount;
uint256 rate = amount / (end - start);
_changeRate(self, e, rate, true, start);
e.start = start;
e.end = end;
e.segmentAmount = amount;
e.roundingCredited = 0;
e.scheduled = true;
self.schedule.insert(facilityId, end);
}
/// @notice Reads effective recognition and remaining obligations without a facility scan.
/// @dev A never-enabled book returns zero and fresh, for an explicit legacy/off state.
function snapshot(Book storage self, uint64 at) internal view returns (Snapshot memory s) {
s.accruedThrough = at;
s.fresh = true;
if (!self.initialized) return s;
if (self.schedule.count() != 0) {
uint64 boundary = self.schedule.peek().deadline;
if (boundary <= at) {
s.accruedThrough = boundary;
s.fresh = false;
}
}
s.gross = _preview(self.total, s.accruedThrough);
s.fee = _add(self.feeBaseAmount, Math.mulDiv(s.gross - self.feeBaseGross, self.feeBps, 10_000));
s.unposted = s.gross - self.posted;
s.feeUnissued = s.fee - self.feeIssued;
s.seniorUnissued = s.gross - s.fee - self.seniorIssued;
s.unissued = _add(s.feeUnissued, s.seniorUnissued);
}
/// @notice Rejects a price-sensitive mutation when a boundary is due but unprocessed.
function requireFresh(Book storage self, uint64 at) internal view {
_requireTime(self, at);
if (self.schedule.count() != 0 && self.schedule.peek().deadline == at) {
revert AccrualBook_BoundaryPending(at, at);
}
}
/// @notice Cumulative recognized interest for a single registered facility.
function earned(Book storage self, uint256 facilityId, uint64 at) internal view returns (uint256) {
Entry storage e = _entry(self, facilityId);
return _preview(e.clock, _frontier(self, at));
}
/// @notice Unposted gross interest for one class, borrower or jurisdiction, in O(1).
function groupUnposted(Book storage self, bytes32 key, uint64 at) internal view returns (uint256) {
Group storage g = self.groups[key];
return _preview(g.clock, _frontier(self, at)) - g.posted;
}
/// @notice Additional unposted interest on the live past-due cohort of one class.
/// @dev The default manager adds its existing recorded-face risk to this amount. Posting
/// transfers the identical amount to that recorded face; clearing a cohort removes it.
function pastDueInterest(Book storage self, bytes32 classKey, uint64 at) internal view returns (uint256) {
return _preview(self.pastDueUnposted[classKey], _frontier(self, at));
}
/// @notice Settles already streamed growth without recognizing a new rounding remainder.
function checkpoint(Book storage self, uint64 at) internal {
_requireInitialized(self);
_requireTime(self, at);
_settleTotal(self, at);
}
/// @notice Recognizes the exact cumulative segment interpolation before a lifecycle action.
/// @dev Idempotent at the same time and independent of earlier reconciliations. The host may
/// call this before an authenticated repayment/amendment/default. Ordinary keeper
/// checkpoints use checkpoint instead. This operation cannot change the segment's basis.
function reconcile(Book storage self, uint256 facilityId, uint64 at) internal returns (uint256 extra) {
Entry storage e = _entry(self, facilityId);
_requireTime(self, at);
if (!e.scheduled) return 0;
uint64 elapsed = at - e.start;
uint64 duration = e.end - e.start;
uint256 remainder = e.segmentAmount % duration;
uint256 cumulative = Math.mulDiv(remainder, elapsed, duration);
extra = cumulative - e.roundingCredited;
e.roundingCredited = cumulative;
_credit(self, e, extra, at);
}
/// @notice Finishes the earliest due technical segment and recognizes its endpoint exactly.
/// @return facilityId The facility whose successor the host must install or explicitly stop.
/// @return boundary The deterministic endpoint timestamp, which may precede the current clock.
/// @return extra The previously unrecognized rounding remainder credited at this boundary.
function finishNext(Book storage self, uint64 at)
internal
returns (uint256 facilityId, uint64 boundary, uint256 extra)
{
_requireInitialized(self);
if (self.schedule.count() == 0) revert AccrualBook_NoBoundaryDue();
AccrualSchedule.Event memory next = self.schedule.peek();
if (next.deadline > at) revert AccrualBook_NoBoundaryDue();
facilityId = next.facilityId;
boundary = next.deadline;
extra = reconcile(self, facilityId, boundary);
Entry storage e = self.entries[facilityId];
_changeRate(self, e, e.clock.rate, false, boundary);
self.schedule.pop();
e.scheduled = false;
}
/// @notice Stops future recognition at an authenticated lifecycle timestamp.
/// @dev Credits exact partial interpolation before removing the integer slope. Recognized
/// income is retained for posting and the native loss cascade; it is never cancelled.
function stop(Book storage self, uint256 facilityId, uint64 at) internal returns (uint256 extra) {
Entry storage e = _entry(self, facilityId);
_requireTime(self, at);
if (!e.scheduled) return 0;
extra = reconcile(self, facilityId, at);
uint256 remaining = e.segmentAmount - e.clock.rate * (at - e.start) - e.roundingCredited;
_changeRate(self, e, e.clock.rate, false, at);
self.unearned -= remaining;
self.schedule.remove(facilityId);
e.scheduled = false;
}
/// @notice Credits a proved positive contractual correction after a segment has stopped.
/// @dev The host must derive the canonical discrepancy, prove its applicable bound (including
/// the possible one-scale-unit positive difference), and prevent replay. This internal
/// accounting primitive grants no external authority and does not validate signed terms.
/// The entry must be registered and unscheduled. Reserve the correction against complete
/// portfolio commitments before consuming it through the ordinary global, facility,
/// exposure-group and past-due credit path. No historical counter is reduced or reset.
/// Zero is permitted and advances the shared accounting clock without recognizing income.
/// @param self The reserve-local book.
/// @param facilityId The registered facility with no active segment.
/// @param amount The independently proved additional gross entitlement.
/// @param at The chronological correction timestamp; an in-progress boundary may equal it.
function creditStoppedCorrection(Book storage self, uint256 facilityId, uint256 amount, uint64 at) internal {
Entry storage e = _entry(self, facilityId);
_requireTime(self, at);
if (e.scheduled) revert AccrualBook_AlreadyScheduled(facilityId);
_settleTotal(self, at);
if (amount > type(uint256).max - self.total.value - self.unearned) revert AccrualBook_Overflow();
self.unearned += amount;
_credit(self, e, amount, at);
}
/// @notice Transfers a facility's recognized income to its recorded reserve/registry face.
/// @dev The host must raise both recorded faces by returned amount in the same protected
/// operation. No token is minted here. This call does not reconcile new rounding income.
function takePosting(Book storage self, uint256 facilityId, uint64 at) internal returns (uint256 amount) {
Entry storage e = _entry(self, facilityId);
_requireTime(self, at);
_settleTotal(self, at);
_checkpoint(e.clock, at);
amount = e.clock.value - e.posted;
e.posted = e.clock.value;
self.posted = _add(self.posted, amount);
for (uint256 i; i < 3; ++i) {
Group storage g = self.groups[e.keys[i]];
g.posted = _add(g.posted, amount);
}
if (e.pastDue) {
Clock storage risk = self.pastDueUnposted[e.keys[0]];
_checkpoint(risk, at);
risk.value -= amount;
}
}
/// @notice Transfers outstanding senior/fee obligations to physical token issuance.
/// @dev The host must mint both returned amounts under its coherent snapshot/operation lock,
/// prove raw token deltas, and revert the entire operation on failure. Permission to call
/// this library is not permission to mint elsewhere. No rounding income is added here.
function takeIssuance(Book storage self, uint64 at) internal returns (uint256 senior, uint256 fee) {
return takeIssuance(self, 3, at);
}
/// @notice Transfers selected senior and/or protocol-fee obligations to physical issuance.
/// @dev Unselected obligations remain virtual and their issued counters do not change. The
/// host must mint exactly the returned amounts under its coherent operation lock and
/// prove raw token deltas. Selection neither forfeits nor redirects the other claim.
/// This method advances the shared accounting clock even if selected amounts are zero.
/// @param self The reserve-local book.
/// @param legs Senior only (1), protocol fee only (2), or both (3).
/// @param at The current chronological timestamp, with all due boundaries processed.
/// @return senior The selected senior entitlement to issue, otherwise zero.
/// @return fee The selected protocol-fee entitlement to issue, otherwise zero.
function takeIssuance(Book storage self, uint8 legs, uint64 at) internal returns (uint256 senior, uint256 fee) {
_requireInitialized(self);
if (legs == 0 || legs > 3) revert AccrualBook_InvalidIssuanceLegs(legs);
requireFresh(self, at);
Snapshot memory s = snapshot(self, at);
_settleTotal(self, at);
if ((legs & 1) != 0) {
senior = s.seniorUnissued;
self.seniorIssued = _add(self.seniorIssued, senior);
}
if ((legs & 2) != 0) {
fee = s.feeUnissued;
self.feeIssued = _add(self.feeIssued, fee);
}
}
/// @notice Changes the configured fee prospectively after settling the previous fee epoch.
/// @dev Keeping the same rate is a no-op and cannot reset fractional fee rounding. The existing
/// vault performance fee is separate and consumes the resulting senior entitlement.
function setFee(Book storage self, uint16 feeBps, uint64 at) internal {
_requireInitialized(self);
_validateFee(feeBps);
requireFresh(self, at);
if (self.feeBps == feeBps) return;
Snapshot memory s = snapshot(self, at);
_settleTotal(self, at);
self.feeBaseGross = s.gross;
self.feeBaseAmount = s.fee;
self.feeBps = feeBps;
}
/// @notice Adds or removes a facility from the class's continuously growing past-due cohort.
/// @dev Existing unposted interest joins/leaves along with the slope. The default-manager
/// host must keep recorded-face contributions synchronized with takePosting separately.
function setPastDue(Book storage self, uint256 facilityId, bool enabled, uint64 at) internal {
Entry storage e = _entry(self, facilityId);
_requireTime(self, at);
if (e.pastDue == enabled) return;
_settleTotal(self, at);
_checkpoint(e.clock, at);
Clock storage risk = self.pastDueUnposted[e.keys[0]];
_checkpoint(risk, at);
uint256 unposted = e.clock.value - e.posted;
if (enabled) {
risk.value = _add(risk.value, unposted);
risk.rate = _add(risk.rate, e.clock.rate);
} else {
risk.value -= unposted;
risk.rate -= e.clock.rate;
}
e.pastDue = enabled;
}
/// @notice Frees an admission slot after the host proves the facility has been fully resolved.
/// @dev Historical recognition, posting, exposure groups and the known-ID tombstone survive.
function retire(Book storage self, uint256 facilityId, uint64 at) internal {
Entry storage e = _entry(self, facilityId);
_requireTime(self, at);
if (e.scheduled || e.clock.value != e.posted) revert AccrualBook_UnsettledFacility(facilityId);
_settleTotal(self, at);
setPastDue(self, facilityId, false, at);
e.registered = false;
--self.registered;
}
function _changeRate(Book storage self, Entry storage e, uint256 rate, bool add, uint64 at) private {
_settleTotal(self, at);
self.total.rate = add ? _add(self.total.rate, rate) : self.total.rate - rate;
_rate(e.clock, rate, add, at);
for (uint256 i; i < 3; ++i) {
_rate(self.groups[e.keys[i]].clock, rate, add, at);
}
if (e.pastDue) _rate(self.pastDueUnposted[e.keys[0]], rate, add, at);
}
function _credit(Book storage self, Entry storage e, uint256 amount, uint64 at) private {
_settleTotal(self, at);
_checkpoint(e.clock, at);
self.unearned -= amount;
self.total.value = _add(self.total.value, amount);
e.clock.value = _add(e.clock.value, amount);
for (uint256 i; i < 3; ++i) {
Clock storage c = self.groups[e.keys[i]].clock;
_checkpoint(c, at);
c.value = _add(c.value, amount);
}
if (e.pastDue) {
Clock storage risk = self.pastDueUnposted[e.keys[0]];
_checkpoint(risk, at);
risk.value = _add(risk.value, amount);
}
}
function _rate(Clock storage c, uint256 amount, bool add, uint64 at) private {
_checkpoint(c, at);
c.rate = add ? _add(c.rate, amount) : c.rate - amount;
}
function _checkpoint(Clock storage c, uint64 at) private {
c.value = _preview(c, at);
c.at = at;
}
function _settleTotal(Book storage self, uint64 at) private {
uint256 previous = self.total.value;
_checkpoint(self.total, at);
self.unearned -= self.total.value - previous;
}
function _preview(Clock storage c, uint64 at) private view returns (uint256 value) {
if (at < c.at) revert AccrualBook_TimeReversed(c.at, at);
uint256 elapsed = at - c.at;
uint256 growth;
unchecked {
growth = c.rate * elapsed;
}
if (elapsed != 0 && growth / elapsed != c.rate) revert AccrualBook_Overflow();
value = _add(c.value, growth);
}
function _frontier(Book storage self, uint64 at) private view returns (uint64) {
if (self.schedule.count() != 0) {
uint64 boundary = self.schedule.peek().deadline;
if (boundary < at) return boundary;
}
return at;
}
function _requireTime(Book storage self, uint64 at) private view {
if (at < self.total.at) revert AccrualBook_TimeReversed(self.total.at, at);
if (self.schedule.count() != 0) {
uint64 boundary = self.schedule.peek().deadline;
if (boundary < at) revert AccrualBook_BoundaryPending(boundary, at);
}
}
function _entry(Book storage self, uint256 facilityId) private view returns (Entry storage e) {
_requireInitialized(self);
e = self.entries[facilityId];
if (!e.registered) revert AccrualBook_UnknownFacility(facilityId);
}
function _requireInitialized(Book storage self) private view {
if (!self.initialized) revert AccrualBook_NotInitialized();
}
function _validateFee(uint16 feeBps) private pure {
if (feeBps > 10_000) revert AccrualBook_InvalidFee(feeBps);
}
function _add(uint256 a, uint256 b) private pure returns (uint256 result) {
unchecked {
result = a + b;
}
if (result < a) revert AccrualBook_Overflow();
}
}
src/libraries/AccrualLoans.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {AccrualBook} from "./AccrualBook.sol";
import {AccrualMath} from "./AccrualMath.sol";
import {AccrualSchedule} from "./AccrualSchedule.sol";
import {AccrualSegments} from "./AccrualSegments.sol";
/// @title AccrualLoans
/// @notice Reserve-local coordination of proved fixed cash and PIK loan terms.
/// @dev All functions are internal. The host authenticates funding, amendments, payments and
/// declaration times; locks callback-visible accounting; executes returned native posting,
/// receipt, rounding-loss and bridge work atomically; and emits the corresponding events.
/// This library makes no external calls or token/custody/registry writes. A caller must never
/// expose an external arbitrary timestamp, term, correction or loss setter around these APIs.
library AccrualLoans {
using AccrualBook for AccrualBook.Book;
using AccrualSchedule for AccrualSchedule.Heap;
/// @notice Work reservations use an elapsed 365-day engineering year.
uint256 internal constant YEAR = 365 days;
/// @notice Conservative aggregate autonomous boundary envelope; no individual interval floor.
/// @dev The contract can close 32 boundaries per transaction. Cold mixed-state measurement
/// fixes the funded keeper at 24 and 128 maintenance transactions per day. At this cap,
/// normal maximum work needs 12 checkpoint transactions per day; seven completely missed
/// days create fewer than 1,920 boundaries and use at most 80 catch-up transactions.
/// The former `YEAR + 400` value admitted one boundary every second (86,400 per day),
/// which no configured keeper could ever service and could hold every price-writing path
/// behind the global freshness gate indefinitely. This remains an aggregate capacity
/// limit: each note still selects its own contractual compounding interval.
uint256 internal constant MAX_ANNUAL_WORK = 100_000;
/// @notice Maximum chronological work returned by one keeper call.
uint256 internal constant MAX_BATCH = 32;
/// @notice The admitted AccrualMath basis domain also bounds every future contractual basis.
uint256 internal constant MAX_BASIS = type(uint256).max / 10_000;
/// @notice Embedded in the reserve's own ERC-7201 namespace.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct State {
AccrualBook.Book book;
mapping(uint256 facilityId => Loan) loans;
uint256 annualWork;
}
/// @notice Contractual debt and the current arithmetic epoch, distinct from booked history.
/// @dev unpaidInterest is canonical through the last closed technical segment. Current
/// unclosed interest is supplied by loanFace. Cash never adds unpaidInterest to basis.
/// Cap-paused loans retain active and their work reservation. nextCapitalization is zero
/// when no further signed PIK boundary fits before maturity; for cash it stores the signed
/// payment due date and is changed only by an authenticated amendment.
struct Loan {
AccrualSegments.Terms terms;
uint256 principal;
uint256 unpaidInterest;
uint256 balanceCeiling;
uint256 frozenPikBasis;
uint256 segmentBookBase;
uint256 segmentCumulativeStart;
uint256 workWeight;
uint64 nextCapitalization;
uint64 paymentInterval;
uint64 legalMaturity;
uint64 lastSettlement;
uint64 closureNonce;
bool pik;
bool active;
bool configured;
bool permanentlyStopped;
// Mixed cash/PIK fields are tail-appended to this mapping value. Legacy entries read zero.
uint256 unpaidCashInterest;
uint256 mixedCashBasis;
uint256 mixedCashCarry;
uint256 mixedPikCarry;
uint256 mixedCashRemainder;
uint256 mixedPikRemainder;
uint256 mixedCashSegmentCumulativeStart;
uint64 mixedRateStart;
uint16 mixedCashRateBps;
bool mixed;
}
/// @notice Validated funded terms; rate/day-count support is explicit in this representation.
/// @dev frozenPikBasis == 0 uses principal for ordinary funding. A nonzero PIK value is only
/// for an authenticated prospective migration of an existing frozen contractual cursor;
/// it does not import or recreate any historical interest in Book. Cash requires zero.
struct Funding {
uint256 principal;
uint256 balanceCeiling;
uint256 scale;
uint256 yearSeconds;
uint16 rateBps;
uint64 fundedAt;
uint64 nextPaymentDue;
uint64 paymentInterval;
uint64 maturity;
bool pik;
bytes32[3] keys;
uint256 frozenPikBasis;
}
/// @notice New-facility terms for concurrent cash and PIK accrual.
/// @dev `pikTerms.rateBps` is the PIK rate and its dates are capitalization dates. Cash and
/// PIK share Actual/360, maturity, scale and the admitted aggregate balance ceiling.
struct MixedFunding {
Funding pikTerms;
uint16 cashRateBps;
}
/// @notice Authenticated opening debt at terms.fundedAt, used as the migration cutoff.
/// @dev recordedFace is the reserve face already backing issued tokens. Only the excess
/// of principal plus interest over that face enters Book as newly recognized income.
/// periodStart preserves the original contractual rounding cursor. The host must prove
/// every field, the legacy asset/identity mapping, the complete portfolio and stop status.
/// This internal routine authorizes no migration and performs no native ledger writes.
struct Opening {
Funding terms;
uint256 recordedFace;
uint256 interest;
uint64 periodStart;
bool permanentlyStopped;
}
/// @notice Forward terms proved by the bridge's existing signed amendment process.
/// @dev nextPaymentDue replaces the future signed PIK boundary without capitalizing now.
struct Amendment {
uint256 balanceCeiling;
uint256 yearSeconds;
uint16 rateBps;
uint64 nextPaymentDue;
uint64 paymentInterval;
uint64 maturity;
}
/// @notice Prospective concurrent-leg terms proved by the bridge's mixed amendment path.
struct MixedAmendment {
Amendment pikTerms;
uint16 cashRateBps;
}
/// @notice Work that the host must execute once, within its protected accounting operation.
/// @dev posting raises recorded reserve/registry face; roundingLoss then reduces that face
/// through the native loss policy. Receipt reductions are separate from those effects.
/// A checkpoint's posting is zero: its income remains virtually backed until post or a
/// lifecycle operation. capitalized is only a PIK debt reclassification, never new yield.
struct LifecycleWork {
uint256 facilityId;
uint64 closureNonce;
uint64 at;
uint256 positiveCorrection;
uint256 roundingLoss;
uint256 posting;
uint256 principalReduction;
uint256 interestReduction;
uint256 capitalized;
uint64 previousDue;
uint64 nextDue;
bool stopped;
bool repaid;
}
/// @dev One aggregate segment backed by two fixed-rate curves.
struct MixedSegment {
uint256 cumulativeStart;
uint256 cashCumulativeStart;
uint256 amount;
uint64 end;
}
/// @notice No contractual metadata was configured for this identifier.
error AccrualLoans_Unknown(uint256 facilityId);
/// @notice Default/declaration or complete repayment cannot be reversed by an amendment.
error AccrualLoans_Inactive(uint256 facilityId);
/// @notice Funded principal, ceiling or optional PIK migration basis is invalid.
error AccrualLoans_InvalidFunding();
/// @notice Opening debt cannot reduce recognized backing or discard its contractual cursor.
error AccrualLoans_InvalidOpening();
/// @notice Signed due, interval and maturity must define a valid forward schedule.
error AccrualLoans_InvalidSchedule();
/// @notice A future balance ceiling exceeds the admitted math domain.
error AccrualLoans_InvalidCeiling(uint256 ceiling);
/// @notice The resulting aggregate annual work reservation exceeds the engineering ceiling.
error AccrualLoans_WorkCapacity(uint256 requested);
/// @notice A maintenance request must process between one and 32 boundaries.
error AccrualLoans_BadBatch(uint256 maximum);
/// @notice A payment must be positive and its combined legs must lie on the reserve grid.
error AccrualLoans_BadPayment();
/// @notice Existing PIK payment semantics require a zero separately designated interest leg.
error AccrualLoans_PikInterestLeg();
/// @notice A payment cannot discharge more than its contractual claim.
error AccrualLoans_PaymentAboveDebt();
/// @notice A closure failed the mathematically proved canonical/interpolation discrepancy bound.
error AccrualLoans_CorrectionOutsideBound(uint256 discrepancy, uint256 scale);
/// @notice Retirement requires the entire contractual debt to be discharged and stopped.
error AccrualLoans_Unsettled(uint256 facilityId);
/// @notice An amount or closure sequence would exceed its stored integer domain.
error AccrualLoans_Overflow();
/// @notice Mixed entry points require two positive fixed rates whose sum fits the protocol cap.
error AccrualLoans_InvalidMixedTerms();
/// @notice A mixed facility cannot be changed through a legacy single-leg lifecycle entry point.
error AccrualLoans_MixedLifecycleRequired(uint256 facilityId);
/// @notice Initializes the reserve-local book at the host's accepted current timestamp.
function initialize(State storage self, uint64 at, uint16 feeBps) internal {
self.book.initialize(at, feeBps);
}
/// @notice Registers funded fixed-rate debt and opens its first eligible segment.
/// @dev principal includes the host's proved financed-fee treatment. Both principal and the
/// entire future balance ceiling must fit AccrualMath's existing basis domain.
function fund(State storage self, uint256 facilityId, Funding memory funded) internal {
_fund(self, facilityId, funded, 0, false);
}
/// @notice Registers one facility with concurrent cash and PIK curves.
function fundMixed(State storage self, uint256 facilityId, MixedFunding memory funded) internal {
Funding memory pikTerms = funded.pikTerms;
if (
!pikTerms.pik || pikTerms.frozenPikBasis != 0 || pikTerms.rateBps == 0 || funded.cashRateBps == 0
|| uint256(pikTerms.rateBps) + funded.cashRateBps > 10_000 || pikTerms.yearSeconds != 360 days
) revert AccrualLoans_InvalidMixedTerms();
_fund(self, facilityId, pikTerms, funded.cashRateBps, true);
}
function _fund(State storage self, uint256 facilityId, Funding memory funded, uint16 cashRateBps, bool mixed)
private
{
if (funded.principal == 0 || funded.principal > MAX_BASIS || funded.balanceCeiling < funded.principal) {
revert AccrualLoans_InvalidFunding();
}
if (funded.frozenPikBasis > MAX_BASIS || (!funded.pik && funded.frozenPikBasis != 0)) {
revert AccrualLoans_InvalidFunding();
}
_validateCeiling(funded.balanceCeiling);
_validateSchedule(funded.fundedAt, funded.nextPaymentDue, funded.paymentInterval, funded.maturity);
AccrualMath.periodAmount(
funded.principal, funded.rateBps, 0, funded.yearSeconds, funded.scale, funded.balanceCeiling
);
self.book.register(facilityId, funded.keys, funded.fundedAt);
Loan storage loan = self.loans[facilityId];
loan.principal = funded.principal;
loan.balanceCeiling = funded.balanceCeiling;
loan.frozenPikBasis = funded.frozenPikBasis == 0 ? funded.principal : funded.frozenPikBasis;
loan.nextCapitalization = funded.nextPaymentDue;
loan.paymentInterval = funded.paymentInterval;
loan.legalMaturity = funded.maturity;
loan.lastSettlement = funded.fundedAt;
loan.pik = funded.pik;
loan.active = true;
loan.configured = true;
loan.mixed = mixed;
loan.mixedCashBasis = mixed ? funded.principal : 0;
loan.mixedCashRateBps = cashRateBps;
loan.mixedRateStart = mixed ? funded.fundedAt : 0;
loan.terms.rateBps = funded.rateBps;
loan.terms.yearSeconds = funded.yearSeconds;
loan.terms.scale = funded.scale;
uint16 workRate = mixed ? funded.rateBps + cashRateBps : funded.rateBps;
_replaceWork(self, loan, _weight(funded.pik, workRate, funded.paymentInterval));
_newEpoch(loan, funded.fundedAt);
_open(self, facilityId, loan, funded.fundedAt);
}
/// @notice Imports one proved opening debt without charging already recognized principal twice.
/// @dev Zero new income represents an opening already settled through the legacy system.
/// Active PIK inputs must already identify their next future contractual boundary;
/// zero is permitted for the final maturity stub. Historical capitalization and all
/// balance assertions are proved by the host, not reconstructed from a guessed history.
/// Future increments subtract the original period's cumulative entitlement at cutoff,
/// retaining fractional entitlement instead of restarting its rounding clock.
function importOpening(State storage self, uint256 facilityId, Opening memory opening)
internal
returns (uint256 income)
{
Loan memory imported = _openingLoan(opening);
uint64 at = opening.terms.fundedAt;
self.book.register(facilityId, opening.terms.keys, at);
self.loans[facilityId] = imported;
Loan storage loan = self.loans[facilityId];
income = _add(loan.principal, loan.unpaidInterest) - opening.recordedFace;
if (income != 0) self.book.creditStoppedCorrection(facilityId, income, at);
if (loan.active) {
_replaceWork(self, loan, _weight(loan.pik, loan.terms.rateBps, loan.paymentInterval));
_open(self, facilityId, loan, at);
}
}
/// @dev Constructs the validated opening without mutating the book or its reservation totals.
function _openingLoan(Opening memory opening) private pure returns (Loan memory loan) {
Funding memory f = opening.terms;
uint64 at = f.fundedAt;
uint256 face = _add(f.principal, opening.interest);
if (face == 0 || face > f.balanceCeiling || opening.recordedFace > face) {
revert AccrualLoans_InvalidOpening();
}
_validateCeiling(f.balanceCeiling);
if (f.frozenPikBasis > MAX_BASIS || (!f.pik && f.frozenPikBasis != 0)) {
revert AccrualLoans_InvalidOpening();
}
bool active = !opening.permanentlyStopped && at < f.maturity;
if (
opening.periodStart > at || opening.periodStart >= f.maturity || f.paymentInterval == 0
|| (f.nextPaymentDue != 0 && (f.nextPaymentDue > f.maturity || f.paymentInterval > f.nextPaymentDue))
|| (active && f.pik && f.nextPaymentDue != 0 && f.nextPaymentDue <= at)
) revert AccrualLoans_InvalidOpening();
uint256 basis = f.pik && f.frozenPikBasis != 0 ? f.frozenPikBasis : f.principal;
uint64 periodEnd =
f.pik && f.nextPaymentDue != 0 && f.nextPaymentDue > opening.periodStart ? f.nextPaymentDue : f.maturity;
uint64 through = at < periodEnd ? at : periodEnd;
uint256 previous = AccrualMath.periodAmount(
basis, f.rateBps, through - opening.periodStart, f.yearSeconds, f.scale, type(uint256).max
);
loan.principal = f.principal;
loan.unpaidInterest = opening.interest;
loan.balanceCeiling = f.balanceCeiling;
loan.frozenPikBasis = basis;
loan.nextCapitalization = f.nextPaymentDue;
loan.paymentInterval = f.paymentInterval;
loan.legalMaturity = f.maturity;
loan.lastSettlement = at;
loan.pik = f.pik;
loan.active = active;
loan.configured = true;
loan.permanentlyStopped = opening.permanentlyStopped;
loan.terms = AccrualSegments.Terms({
basis: basis,
yearSeconds: f.yearSeconds,
scale: f.scale,
cap: _add(previous, f.balanceCeiling - face),
periodStart: opening.periodStart,
periodEnd: periodEnd,
maturity: f.maturity,
rateBps: f.rateBps
});
}
/// @notice Processes at most 32 chronological boundaries and commits partial progress.
/// @return work Fixed-capacity result array; only its first processed elements are populated.
/// @return processed Number of populated work entries and completed boundaries.
/// @return fresh Whether all due boundaries have been processed through at.
function checkpoint(State storage self, uint64 at, uint256 maximum)
internal
returns (LifecycleWork[] memory work, uint256 processed, bool fresh)
{
if (maximum == 0 || maximum > MAX_BATCH) revert AccrualLoans_BadBatch(maximum);
work = new LifecycleWork[](maximum);
while (processed < maximum && self.book.schedule.count() != 0) {
if (self.book.schedule.peek().deadline > at) break;
(uint256 id, uint64 boundary,) = self.book.finishNext(at);
Loan storage loan = _loan(self, id);
LifecycleWork memory item = _work(id, boundary);
(uint256 earned, uint256 cashEarned) = _segmentEarned(loan, boundary);
loan.unpaidInterest = _add(loan.unpaidInterest, earned);
if (loan.mixed) loan.unpaidCashInterest = _add(loan.unpaidCashInterest, cashEarned);
loan.lastSettlement = boundary;
if (loan.pik && boundary == loan.nextCapitalization) {
_capitalize(loan, item);
loan.nextCapitalization = _nextDue(boundary, loan.paymentInterval, loan.legalMaturity);
item.nextDue = loan.nextCapitalization;
if (boundary < loan.legalMaturity) _newEpoch(loan, boundary);
}
if (boundary == loan.legalMaturity) {
_deactivate(self, loan);
item.stopped = true;
} else {
_open(self, id, loan, boundary);
}
work[processed++] = item;
}
fresh = self.book.schedule.count() == 0 || self.book.schedule.peek().deadline > at;
if (fresh) self.book.checkpoint(at);
}
/// @notice Aligns exact contractual debt, returns native receipt work, then resumes forward.
/// @dev The host proves the original attested legs and measured custody. A PIK principal leg
/// can discharge uncapitalized interest after capitalized principal; its interest leg is
/// zero. Cash legs discharge their own separate balances. Only the sum must lie on-grid.
function repay(State storage self, uint256 facilityId, uint256 principalLeg, uint256 interestLeg, uint64 at)
internal
returns (LifecycleWork memory work)
{
Loan storage loan = _loan(self, facilityId);
uint256 paid = _add(principalLeg, interestLeg);
if (paid == 0 || paid % loan.terms.scale != 0) revert AccrualLoans_BadPayment();
if (loan.pik && !loan.mixed && interestLeg != 0) revert AccrualLoans_PikInterestLeg();
bool capPaused = loan.mixed ? _mixedCapReached(loan, at) : _capReached(loan, at);
work = _close(self, facilityId, loan, at);
if (loan.mixed) {
uint256 unpaidPik = loan.unpaidInterest - loan.unpaidCashInterest;
if (principalLeg > _add(loan.principal, unpaidPik) || interestLeg > loan.unpaidCashInterest) {
revert AccrualLoans_PaymentAboveDebt();
}
work.principalReduction = principalLeg < loan.principal ? principalLeg : loan.principal;
uint256 pikReduction = principalLeg - work.principalReduction;
work.interestReduction = pikReduction + interestLeg;
loan.principal -= work.principalReduction;
loan.unpaidInterest -= work.interestReduction;
loan.unpaidCashInterest -= interestLeg;
} else if (loan.pik) {
if (principalLeg > _add(loan.principal, loan.unpaidInterest)) revert AccrualLoans_PaymentAboveDebt();
work.principalReduction = principalLeg < loan.principal ? principalLeg : loan.principal;
work.interestReduction = principalLeg - work.principalReduction;
} else {
if (principalLeg > loan.principal || interestLeg > loan.unpaidInterest) {
revert AccrualLoans_PaymentAboveDebt();
}
work.principalReduction = principalLeg;
work.interestReduction = interestLeg;
}
if (!loan.mixed) {
loan.principal -= work.principalReduction;
loan.unpaidInterest -= work.interestReduction;
}
// CX-01: a quote can land after another block has earned interest. Once every
// unit of capital is returned, that small unpaid interest is still owed, but
// the old capital must never remain the basis of another PIK coupon. Preserve
// mixed-leg fractional carry before changing its prospective basis; interest
// itself compounds only at the signed capitalization boundary.
bool retiredPikCapital = loan.pik && loan.principal == 0 && loan.frozenPikBasis != 0;
if (retiredPikCapital) {
if (loan.mixed && loan.active && !capPaused && at < loan.legalMaturity && at < loan.terms.periodEnd) {
_rollMixedRates(loan, at);
}
loan.frozenPikBasis = 0;
}
if (loan.principal == 0 && loan.unpaidInterest == 0) {
_deactivate(self, loan);
loan.permanentlyStopped = true;
work.stopped = true;
work.repaid = true;
} else if (loan.active && at < loan.legalMaturity) {
// Replenishing a binding cap starts now; it cannot backfill clipped historical time.
// Cash principal changes rebase only prospectively. Otherwise keep the original
// epoch/curve, especially for a partial PIK principal payment in a frozen period.
if (
capPaused || (!loan.pik && principalLeg != 0) || at >= loan.terms.periodEnd
|| (retiredPikCapital && !loan.mixed)
) {
_newEpoch(loan, at);
} else if (loan.mixed && (work.principalReduction != 0 || retiredPikCapital)) {
if (!retiredPikCapital) _rollMixedRates(loan, at);
loan.mixedCashBasis = loan.principal;
loan.terms.cap = _add(loan.terms.cap, paid);
} else {
// No clipped time exists before the cap is reached. Retain the same cumulative
// curve and expand its ceiling by the proved debt repayment instead of losing
// the original period's fractional entitlement through an unnecessary restart.
loan.terms.cap = _add(loan.terms.cap, paid);
}
_open(self, facilityId, loan, at);
} else if (at >= loan.legalMaturity) {
_deactivate(self, loan);
work.stopped = true;
}
}
/// @notice Applies authenticated forward terms after closing the old arithmetic at at.
/// @dev The signed nextPaymentDue replaces the future PIK capitalization date. No principal
/// reclassification or PIK rebasing occurs merely because this amendment was signed.
function amend(State storage self, uint256 facilityId, Amendment memory changed, uint64 at)
internal
returns (LifecycleWork memory work)
{
Loan storage loan = _loan(self, facilityId);
if (loan.mixed) revert AccrualLoans_MixedLifecycleRequired(facilityId);
if (loan.permanentlyStopped) revert AccrualLoans_Inactive(facilityId);
_validateCeiling(changed.balanceCeiling);
_validateSchedule(at, changed.nextPaymentDue, changed.paymentInterval, changed.maturity);
AccrualMath.periodAmount(loan.terms.basis, changed.rateBps, 0, changed.yearSeconds, loan.terms.scale, 0);
uint64 previousDue = loan.nextCapitalization;
work = _close(self, facilityId, loan, at);
_replaceWork(self, loan, _weight(loan.pik, changed.rateBps, changed.paymentInterval));
loan.active = true;
work.previousDue = previousDue;
work.nextDue = changed.nextPaymentDue;
loan.nextCapitalization = changed.nextPaymentDue;
loan.paymentInterval = changed.paymentInterval;
loan.legalMaturity = changed.maturity;
loan.balanceCeiling = changed.balanceCeiling;
loan.terms.rateBps = changed.rateBps;
loan.terms.yearSeconds = changed.yearSeconds;
_newEpoch(loan, at);
_open(self, facilityId, loan, at);
}
/// @notice Applies authenticated prospective rates and PIK dates to a mixed facility.
function amendMixed(State storage self, uint256 facilityId, MixedAmendment memory changed, uint64 at)
internal
returns (LifecycleWork memory work)
{
Loan storage loan = _loan(self, facilityId);
Amendment memory pikTerms = changed.pikTerms;
if (!loan.mixed) revert AccrualLoans_MixedLifecycleRequired(facilityId);
if (
loan.permanentlyStopped || pikTerms.rateBps == 0 || changed.cashRateBps == 0
|| uint256(pikTerms.rateBps) + changed.cashRateBps > 10_000 || pikTerms.yearSeconds != 360 days
) {
if (loan.permanentlyStopped) revert AccrualLoans_Inactive(facilityId);
revert AccrualLoans_InvalidMixedTerms();
}
_validateCeiling(pikTerms.balanceCeiling);
_validateSchedule(at, pikTerms.nextPaymentDue, pikTerms.paymentInterval, pikTerms.maturity);
AccrualMath.periodAmount(loan.frozenPikBasis, pikTerms.rateBps, 0, pikTerms.yearSeconds, loan.terms.scale, 0);
AccrualMath.periodAmount(loan.principal, changed.cashRateBps, 0, pikTerms.yearSeconds, loan.terms.scale, 0);
uint64 previousDue = loan.nextCapitalization;
work = _close(self, facilityId, loan, at);
_replaceWork(self, loan, _weight(true, pikTerms.rateBps + changed.cashRateBps, pikTerms.paymentInterval));
loan.active = true;
work.previousDue = previousDue;
work.nextDue = pikTerms.nextPaymentDue;
loan.nextCapitalization = pikTerms.nextPaymentDue;
loan.paymentInterval = pikTerms.paymentInterval;
loan.legalMaturity = pikTerms.maturity;
loan.balanceCeiling = pikTerms.balanceCeiling;
loan.terms.rateBps = pikTerms.rateBps;
loan.terms.yearSeconds = pikTerms.yearSeconds;
loan.mixedCashRateBps = changed.cashRateBps;
_newEpoch(loan, at);
_open(self, facilityId, loan, at);
}
/// @notice Aligns and permanently stops accrual before the host's default/acceleration action.
/// @dev The host posts the returned face and resolves any rounding loss before default snapshots.
function stop(State storage self, uint256 facilityId, uint64 at) internal returns (LifecycleWork memory work) {
Loan storage loan = _loan(self, facilityId);
work = _close(self, facilityId, loan, at);
_deactivate(self, loan);
loan.permanentlyStopped = true;
work.stopped = true;
}
/// @notice Services signed PIK dates that have no positive queued interest work.
/// @dev Scheduled loans, cash loans, inactive loans and future dormant dates are unchanged.
/// Existing unpaid PIK is capitalized once; only proven zero-income successors are
/// skipped arithmetically. The shared Book checkpoint stores already-visible growth
/// without adding entitlement, posting, closing/reopening a segment or minting yield.
/// The host applies only a nonzero later signed nextDue to its bridge and uses legal
/// maturity as the balloon deadline once no signed capitalization boundary remains.
function serviceDormant(State storage self, uint256 facilityId, uint64 at)
internal
returns (LifecycleWork memory work)
{
Loan storage loan = _loan(self, facilityId);
self.book.requireFresh(at);
work = _work(facilityId, at);
if (self.book.entries[facilityId].scheduled || !loan.active || !loan.pik) return work;
if (at < loan.legalMaturity && (loan.nextCapitalization == 0 || loan.nextCapitalization > at)) return work;
self.book.checkpoint(at);
_settleDormantPik(loan, work, at);
loan.lastSettlement = at;
if (at >= loan.legalMaturity) {
_deactivate(self, loan);
work.stopped = true;
}
}
/// @notice Takes already-recognized posting work without resetting a contractual curve.
function post(State storage self, uint256 facilityId, uint64 at) internal returns (uint256 amount) {
_loan(self, facilityId);
self.book.requireFresh(at);
amount = self.book.takePosting(facilityId, at);
}
/// @notice Retires a completely paid, stopped, posted facility while retaining its known-ID tombstone.
function retire(State storage self, uint256 facilityId, uint64 at) internal {
Loan storage loan = _loan(self, facilityId);
if (loan.active || loan.principal != 0 || loan.unpaidInterest != 0) revert AccrualLoans_Unsettled(facilityId);
self.book.retire(facilityId, at);
}
/// @notice Exact contractual face through the book's coherent current frontier, in O(1).
/// @dev This is not a replacement for the booked accounting carrier used by reserve NAV.
function loanFace(State storage self, uint256 facilityId, uint64 at)
internal
view
returns (uint256 principal, uint256 interest, uint64 accruedThrough)
{
Loan storage loan = _loan(self, facilityId);
accruedThrough = self.book.snapshot(at).accruedThrough;
principal = loan.principal;
interest = loan.unpaidInterest;
if (self.book.entries[facilityId].scheduled) {
(uint256 earned,) = _segmentEarned(loan, accruedThrough);
interest = _add(interest, earned);
}
if (
loan.active && loan.pik && !self.book.entries[facilityId].scheduled && loan.nextCapitalization != 0
&& loan.nextCapitalization <= accruedThrough && loan.nextCapitalization <= loan.legalMaturity
) {
if (loan.mixed) {
uint256 cashInterest = loan.unpaidCashInterest;
principal = _add(principal, interest - cashInterest);
interest = cashInterest;
} else {
principal = _add(principal, interest);
interest = 0;
}
}
}
/// @notice Current unpaid cash and PIK interest through the coherent Book frontier.
function loanInterestLegs(State storage self, uint256 facilityId, uint64 at)
internal
view
returns (uint256 cash, uint256 pik, uint64 accruedThrough)
{
Loan storage loan = _loan(self, facilityId);
accruedThrough = self.book.snapshot(at).accruedThrough;
cash = loan.unpaidCashInterest;
uint256 total = loan.unpaidInterest;
if (self.book.entries[facilityId].scheduled) {
(uint256 earned, uint256 cashEarned) = _segmentEarned(loan, accruedThrough);
total = _add(total, earned);
cash = _add(cash, cashEarned);
}
pik = total - cash;
// A binding ceiling can leave a live mixed loan unscheduled before its signed PIK
// date. The servicing path capitalizes that stored PIK in O(1) when the date arrives,
// and loanFace already presents the same debt as principal. Mirror that virtual
// classification here so callers cannot add a stale PIK-interest leg to a principal
// balance that already includes it.
if (
loan.mixed && loan.active && !self.book.entries[facilityId].scheduled && loan.nextCapitalization != 0
&& loan.nextCapitalization <= accruedThrough && loan.nextCapitalization <= loan.legalMaturity
) pik = 0;
}
/// @dev Stops the local interpolation, aligns the canonical contribution and consumes posting.
function _close(State storage self, uint256 id, Loan storage loan, uint64 at)
private
returns (LifecycleWork memory work)
{
self.book.requireFresh(at);
work = _work(id, at);
if (loan.closureNonce == type(uint64).max) revert AccrualLoans_Overflow();
work.closureNonce = ++loan.closureNonce;
if (self.book.entries[id].scheduled) {
self.book.stop(id, at);
uint256 recognized = self.book.earned(id, at) - loan.segmentBookBase;
(uint256 canonical, uint256 cashCanonical) = _segmentEarned(loan, at);
if (canonical > recognized) {
work.positiveCorrection = canonical - recognized;
if (work.positiveCorrection > loan.terms.scale) {
revert AccrualLoans_CorrectionOutsideBound(work.positiveCorrection, loan.terms.scale);
}
self.book.creditStoppedCorrection(id, work.positiveCorrection, at);
} else {
work.roundingLoss = recognized - canonical;
if (work.roundingLoss >= loan.terms.scale) {
revert AccrualLoans_CorrectionOutsideBound(work.roundingLoss, loan.terms.scale);
}
}
loan.unpaidInterest = _add(loan.unpaidInterest, canonical);
if (loan.mixed) loan.unpaidCashInterest = _add(loan.unpaidCashInterest, cashCanonical);
} else if (loan.active) {
_settleDormantPik(loan, work, at);
}
work.posting = self.book.takePosting(id, at);
loan.lastSettlement = at;
}
/// @dev Opens only useful positive-entitlement work; zero-rate/cap-paused periods do not loop.
function _open(State storage self, uint256 id, Loan storage loan, uint64 at) private {
if (!loan.active || at >= loan.legalMaturity) return;
if (loan.mixed) {
MixedSegment memory mixed = _planMixed(loan, at);
if (mixed.end == at) return;
loan.segmentBookBase = self.book.earned(id, at);
loan.segmentCumulativeStart = mixed.cumulativeStart;
loan.mixedCashSegmentCumulativeStart = mixed.cashCumulativeStart;
self.book.open(id, mixed.amount, at, mixed.end);
return;
}
if (loan.terms.rateBps == 0 || (!loan.pik && loan.terms.basis == 0)) return;
// An imported zero-basis PIK period can still capitalize existing unpaid interest,
// creating a positive basis at its next signed date. Keep that boundary scheduled.
// A dormant PIK period is skipped only if both its remaining entitlement and every
// unchanged successor are zero. The prospective next basis includes existing unpaid
// income, so a pending capitalization that enables a positive next coupon is scheduled.
// A longer first period is not mistaken for a zero regular short coupon.
if (loan.pik) {
uint256 remaining = AccrualSegments.cumulative(loan.terms, loan.terms.periodEnd)
- AccrualSegments.cumulative(loan.terms, at);
uint256 nextBasis = _add(_add(loan.principal, loan.unpaidInterest), remaining);
uint256 room = nextBasis < loan.balanceCeiling ? loan.balanceCeiling - nextBasis : 0;
if (
remaining == 0
&& AccrualMath.periodAmount(
nextBasis, loan.terms.rateBps, loan.paymentInterval, loan.terms.yearSeconds, loan.terms.scale, room
) == 0
) return;
}
if (!loan.pik && AccrualSegments.cumulative(loan.terms, loan.legalMaturity) == 0) return;
AccrualSegments.Segment memory segment = AccrualSegments.plan(loan.terms, at);
if (segment.end == at) return;
loan.segmentBookBase = self.book.earned(id, at);
loan.segmentCumulativeStart = segment.cumulativeStart;
self.book.open(id, segment.amount, at, segment.end);
}
/// @dev A new arithmetic epoch preserves the signed PIK basis while refreshing available room.
function _newEpoch(Loan storage loan, uint64 at) private {
loan.terms.basis = loan.pik ? loan.frozenPikBasis : loan.principal;
loan.terms.periodStart = at;
loan.terms.periodEnd = loan.pik && loan.nextCapitalization != 0 ? loan.nextCapitalization : loan.legalMaturity;
loan.terms.maturity = loan.legalMaturity;
uint256 face = _add(loan.principal, loan.unpaidInterest);
loan.terms.cap = face < loan.balanceCeiling ? loan.balanceCeiling - face : 0;
if (loan.mixed) {
loan.mixedCashBasis = loan.principal;
loan.mixedCashCarry = 0;
loan.mixedPikCarry = 0;
loan.mixedCashRemainder = 0;
loan.mixedPikRemainder = 0;
loan.mixedRateStart = at;
loan.mixedCashSegmentCumulativeStart = 0;
}
}
/// @dev A paused cap or zero-rate interval has no unseen interest recurrence. Capitalize its
/// existing PIK U once, then skip only further zero-income dates arithmetically in O(1).
function _settleDormantPik(Loan storage loan, LifecycleWork memory work, uint64 at) private {
uint64 due = loan.nextCapitalization;
if (!loan.pik || due == 0 || due > at || due > loan.legalMaturity) return;
_capitalize(loan, work);
uint64 through = at < loan.legalMaturity ? at : loan.legalMaturity;
uint256 count = uint256(through - due) / loan.paymentInterval + 1;
uint256 remaining = uint256(loan.legalMaturity - due) / loan.paymentInterval;
loan.nextCapitalization = count > remaining ? 0 : due + uint64(count * loan.paymentInterval);
work.nextDue = loan.nextCapitalization;
}
/// @dev Reclassifies already accrued PIK debt; does not recognize/post/mint it again.
function _capitalize(Loan storage loan, LifecycleWork memory work) private {
work.previousDue = loan.nextCapitalization;
work.capitalized = loan.mixed ? loan.unpaidInterest - loan.unpaidCashInterest : loan.unpaidInterest;
loan.principal = _add(loan.principal, work.capitalized);
loan.unpaidInterest = loan.mixed ? loan.unpaidCashInterest : 0;
loan.frozenPikBasis = loan.principal;
}
/// @notice Canonical current-segment entitlement used by the native rounding preparer.
function canonicalSegment(Loan storage loan, uint64 at) internal view returns (uint256 total, uint256 cash) {
return _segmentEarned(loan, at);
}
function _segmentEarned(Loan storage loan, uint64 at) private view returns (uint256 total, uint256 cash) {
if (!loan.mixed) {
total = AccrualSegments.cumulative(loan.terms, at) - loan.segmentCumulativeStart;
return (total, 0);
}
(uint256 cumulative, uint256 cashCumulative) = _mixedCumulative(loan, at);
total = cumulative - loan.segmentCumulativeStart;
cash = cashCumulative - loan.mixedCashSegmentCumulativeStart;
}
/// @dev Plans one aggregate Book segment while retaining separate contractual leg arithmetic.
function _planMixed(Loan storage loan, uint64 at) private view returns (MixedSegment memory segment) {
uint64 effectiveEnd = loan.terms.periodEnd < loan.legalMaturity ? loan.terms.periodEnd : loan.legalMaturity;
if (at < loan.terms.periodStart || at > effectiveEnd) revert AccrualLoans_InvalidSchedule();
(segment.cumulativeStart, segment.cashCumulativeStart) = _mixedCumulative(loan, at);
segment.end = at;
uint256 gridCap = loan.terms.cap - loan.terms.cap % loan.terms.scale;
if (at == effectiveEnd || segment.cumulativeStart == gridCap) return segment;
uint64 technicalRemaining =
AccrualSegments.MAX_SEGMENT_SECONDS - (at - loan.terms.periodStart) % AccrualSegments.MAX_SEGMENT_SECONDS;
uint64 remaining = effectiveEnd - at;
segment.end = at + (remaining < technicalRemaining ? remaining : technicalRemaining);
(uint256 finalCumulative,) = _mixedCumulative(loan, effectiveEnd);
if (finalCumulative == gridCap) {
uint64 low = at + 1;
uint64 high = effectiveEnd;
while (low < high) {
uint64 middle = low + (high - low) / 2;
(uint256 value,) = _mixedCumulative(loan, middle);
if (value >= gridCap) high = middle;
else low = middle + 1;
}
uint64 capBoundary = low;
if (capBoundary - at > 1) --capBoundary;
if (capBoundary < segment.end) segment.end = capBoundary;
}
(uint256 cumulativeEnd,) = _mixedCumulative(loan, segment.end);
segment.amount = cumulativeEnd - segment.cumulativeStart;
}
/// @dev Aggregate grid rounding occurs once; any cross-leg grid remainder belongs to PIK.
function _mixedCumulative(Loan storage loan, uint64 at) private view returns (uint256 total, uint256 cash) {
(uint256 cashWhole, uint256 cashRemainder) = _legPreview(
loan.mixedCashCarry,
loan.mixedCashRemainder,
loan.mixedCashBasis,
loan.mixedCashRateBps,
loan.mixedRateStart,
at,
loan.terms.yearSeconds
);
(uint256 pikWhole, uint256 pikRemainder) = _legPreview(
loan.mixedPikCarry,
loan.mixedPikRemainder,
loan.frozenPikBasis,
loan.terms.rateBps,
loan.mixedRateStart,
at,
loan.terms.yearSeconds
);
uint256 raw = _add(cashWhole, pikWhole);
// The two legs share one Actual/360 denominator. Carry their fractional wei into the
// aggregate before applying the native asset grid; otherwise independently flooring
// each leg can lose the aggregate carry and make endpoint interpolation exceed the
// canonical curve by one whole grid unit.
uint256 denominator = 10_000 * loan.terms.yearSeconds;
if (cashRemainder >= denominator - pikRemainder) raw = _add(raw, 1);
if (raw > loan.terms.cap) raw = loan.terms.cap;
total = raw - raw % loan.terms.scale;
cash = cashWhole - cashWhole % loan.terms.scale;
if (cash > total) cash = total;
}
/// @dev Carries exact rational remainders when a principal change alters only the cash basis.
function _rollMixedRates(Loan storage loan, uint64 at) private {
(loan.mixedCashCarry, loan.mixedCashRemainder) = _legPreview(
loan.mixedCashCarry,
loan.mixedCashRemainder,
loan.mixedCashBasis,
loan.mixedCashRateBps,
loan.mixedRateStart,
at,
loan.terms.yearSeconds
);
(loan.mixedPikCarry, loan.mixedPikRemainder) = _legPreview(
loan.mixedPikCarry,
loan.mixedPikRemainder,
loan.frozenPikBasis,
loan.terms.rateBps,
loan.mixedRateStart,
at,
loan.terms.yearSeconds
);
loan.mixedRateStart = at;
}
function _legPreview(
uint256 carry,
uint256 remainder,
uint256 basis,
uint16 rateBps,
uint64 start,
uint64 at,
uint256 yearSeconds
) private pure returns (uint256 whole, uint256 nextRemainder) {
if (at < start) revert AccrualLoans_InvalidSchedule();
uint256 denominator = 10_000 * yearSeconds;
uint256 coefficient = basis * rateBps;
uint256 elapsed = at - start;
uint256 quotient = Math.mulDiv(coefficient, elapsed, denominator);
nextRemainder = mulmod(coefficient, elapsed, denominator) + remainder;
if (nextRemainder >= denominator) {
nextRemainder -= denominator;
quotient = _add(quotient, 1);
}
whole = _add(carry, quotient);
}
function _mixedCapReached(Loan storage loan, uint64 at) private view returns (bool) {
uint64 end = loan.terms.periodEnd < loan.legalMaturity ? loan.terms.periodEnd : loan.legalMaturity;
uint64 through = at < end ? at : end;
uint256 gridCap = loan.terms.cap - loan.terms.cap % loan.terms.scale;
(uint256 current,) = _mixedCumulative(loan, through);
if (current != gridCap) return false;
(uint256 finalAmount,) = _mixedCumulative(loan, end);
return finalAmount == gridCap;
}
function _capReached(Loan storage loan, uint64 at) private view returns (bool) {
AccrualSegments.Segment memory prior = AccrualSegments.plan(loan.terms, loan.terms.periodStart);
return prior.capReachable && prior.capHit <= at;
}
/// @dev Returns only a real next contractual capitalization date, never inventing maturity compounding.
function _nextDue(uint64 previous, uint64 interval, uint64 maturity) private pure returns (uint64) {
return interval <= maturity - previous ? previous + interval : 0;
}
/// @dev Reservations persist during cap pauses and are released only on permanent stopping.
function _deactivate(State storage self, Loan storage loan) private {
if (loan.active) {
_replaceWork(self, loan, 0);
loan.active = false;
}
}
/// @dev Conservative autonomous annual work plus phase/technical/cap allowance, per active loan.
function _weight(bool pik, uint16 rateBps, uint64 interval) private pure returns (uint256) {
if (rateBps == 0) return 0;
return pik ? YEAR / interval + (YEAR % interval == 0 ? 0 : 1) + 4 : 4;
}
/// @dev Replacement is atomic: a rejected amendment preserves the prior reservation and terms.
function _replaceWork(State storage self, Loan storage loan, uint256 replacement) private {
uint256 requested = self.annualWork - loan.workWeight + replacement;
// An upgraded historical book may already exceed the newly funded keeper envelope.
// Refusing a strict reduction would trap that book above the cap forever: even default,
// repayment or a safer amendment could not release its old reservation. While over cap,
// admit only a replacement that lowers this loan's contribution. New admissions,
// unchanged schedules and increases continue to fail until the portfolio is back inside.
if (requested > MAX_ANNUAL_WORK && replacement >= loan.workWeight) {
revert AccrualLoans_WorkCapacity(requested);
}
self.annualWork = requested;
loan.workWeight = replacement;
}
/// @dev Validates signed funding/amendment dates without imposing a minimum individual interval.
function _validateSchedule(uint64 at, uint64 due, uint64 interval, uint64 maturity) private pure {
if (interval == 0 || due <= at || due > maturity || interval > due || maturity <= at) {
revert AccrualLoans_InvalidSchedule();
}
}
/// @dev Every future PIK basis must remain inside the already-admitted math domain.
function _validateCeiling(uint256 ceiling) private pure {
if (ceiling > MAX_BASIS) revert AccrualLoans_InvalidCeiling(ceiling);
}
/// @dev Lookup is separate from Book registration so retired contractual metadata remains readable.
function _loan(State storage self, uint256 facilityId) private view returns (Loan storage loan) {
loan = self.loans[facilityId];
if (!loan.configured) revert AccrualLoans_Unknown(facilityId);
}
/// @dev Initializes a result without any externally supplied posting or correction amount.
function _work(uint256 id, uint64 at) private pure returns (LifecycleWork memory work) {
work.facilityId = id;
work.at = at;
}
/// @dev Uses a stable named error instead of a generic arithmetic panic at capacity bounds.
function _add(uint256 first, uint256 second) private pure returns (uint256) {
if (second > type(uint256).max - first) revert AccrualLoans_Overflow();
return first + second;
}
}
src/libraries/AccrualMath.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @title AccrualMath — pure arithmetic on a fixed contractual interest basis
/// @notice Computes simple interest and cumulative fractions without changing a facility's basis.
/// @dev These primitives do not select an accrual architecture, capitalization schedule or rounding
/// policy. In particular, interpolating `periodAmount` is not identical to applying
/// `earnedInterest` at each instant: rounding the endpoint to a reserve unit changes the
/// intermediate curve. With a nonbinding cap their integer outputs differ by at most one reserve
/// unit; the unrounded endpoint interpolation differs by strictly less than one unit. A binding
/// cap can make the difference larger. Callers must choose the contractual policy explicitly.
/// No storage, clock reads, roles, external calls, fee allocation or token operations occur here.
library AccrualMath {
/// @notice The supplied basis exceeds the registry's existing maximum safe exposure.
/// @param basis The invalid normalized principal basis.
error AccrualMath_BasisTooLarge(uint256 basis);
/// @notice The annual nominal rate exceeds the protocol's existing 100% ceiling.
/// @param rateBps The invalid annual rate, in basis points.
error AccrualMath_RateTooLarge(uint16 rateBps);
/// @notice Only the unambiguous Actual/360 and Actual/365 denominators are supported.
/// @param yearSeconds The unsupported interest-year denominator, in seconds.
error AccrualMath_UnsupportedYear(uint256 yearSeconds);
/// @notice Uncapped earned interest cannot be represented in uint256.
/// @dev `periodAmount` can still return a valid capped result for these otherwise valid terms.
error AccrualMath_AmountOverflow();
/// @notice A reserve unit must contain at least one normalized wei.
error AccrualMath_ZeroScale();
/// @notice A cumulative linear interval must have a positive duration.
error AccrualMath_ZeroDuration();
/// @notice The requested cumulative elapsed time lies beyond the fixed interval.
/// @param elapsed The requested elapsed time, in seconds.
/// @param duration The fixed interval duration, in seconds.
error AccrualMath_ElapsedExceedsDuration(uint64 elapsed, uint64 duration);
/// @notice A delta must run forward from its earlier cumulative checkpoint.
/// @param previousElapsed The previous cumulative elapsed time, in seconds.
/// @param elapsed The new cumulative elapsed time, in seconds.
error AccrualMath_ReversedWindow(uint64 previousElapsed, uint64 elapsed);
/// @notice Simple interest earned over cumulative elapsed time on an unchanged basis.
/// @dev Floors once to normalized wei using full-precision multiplication and division. A zero
/// basis, rate or elapsed time returns zero, after validating all input bounds. The uint64
/// elapsed bound and the 10,000 bps ceiling make `rateBps * elapsed` safe in uint256.
/// @param basis Frozen normalized principal, at most uint256-max / 10,000 as in the registry.
/// @param rateBps Fixed annual nominal rate, from zero through 10,000 inclusive.
/// @param elapsed Cumulative elapsed seconds on that basis; this function does not read the clock.
/// @param yearSeconds Exactly 360 days or 365 days, as specified by the note.
/// @return amount Earned interest, rounded down to normalized wei.
function earnedInterest(uint256 basis, uint16 rateBps, uint64 elapsed, uint256 yearSeconds)
internal
pure
returns (uint256 amount)
{
uint256 denominator = _validateTerms(basis, rateBps, yearSeconds);
uint256 coefficient = uint256(rateBps) * elapsed;
(uint256 high,) = Math.mul512(basis, coefficient);
if (high >= denominator) revert AccrualMath_AmountOverflow();
amount = Math.mulDiv(basis, coefficient, denominator);
}
/// @notice The fixed-period amount, capped and rounded down to a whole reserve unit.
/// @dev Reproduces the existing PIK amount/cap/grid order. The cap is a maximum ADDITIONAL
/// amount, not a total facility-balance ceiling. A cap below one reserve unit yields zero;
/// deciding whether to advance a zero-amount period belongs to the servicing layer.
/// A capped result remains computable even when uncapped interest would exceed uint256.
/// @param basis Frozen normalized principal, at most uint256-max / 10,000.
/// @param rateBps Fixed annual nominal rate, from zero through 10,000 inclusive.
/// @param duration Actual elapsed seconds in the fixed contractual period; zero is permitted.
/// @param yearSeconds Exactly 360 days or 365 days.
/// @param scale Normalized wei in one reserve unit; nonzero. Ethereum USDC uses 1e12, BSC uses 1.
/// @param cap Maximum additional normalized interest recognizable for this period.
/// @return amount The capped interest amount, a whole multiple of `scale`.
function periodAmount(
uint256 basis,
uint16 rateBps,
uint64 duration,
uint256 yearSeconds,
uint256 scale,
uint256 cap
) internal pure returns (uint256 amount) {
if (scale == 0) revert AccrualMath_ZeroScale();
uint256 denominator = _validateTerms(basis, rateBps, yearSeconds);
uint256 coefficient = uint256(rateBps) * duration;
(uint256 high,) = Math.mul512(basis, coefficient);
if (high >= denominator) {
// The exact quotient exceeds every uint256 cap; do not evaluate an overflowing div.
amount = cap;
} else {
amount = Math.mulDiv(basis, coefficient, denominator);
if (amount > cap) amount = cap;
}
amount = (amount / scale) * scale;
}
/// @notice Cumulative linear fraction of an already fixed endpoint amount.
/// @dev Floors once to normalized wei. At zero elapsed it returns zero; at the exact duration
/// it returns the endpoint, even for uint256-max amounts. This is an optional interpolation
/// primitive, not a declaration that grid-rounded endpoint interpolation is contractual.
/// @param endpointAmount The fixed amount earned at the end of the interval.
/// @param duration Positive interval duration, in seconds.
/// @param elapsed Cumulative elapsed seconds, no greater than `duration`.
/// @return amount The cumulative floor-rounded fraction of `endpointAmount`.
function linearEarned(uint256 endpointAmount, uint64 duration, uint64 elapsed)
internal
pure
returns (uint256 amount)
{
if (duration == 0) revert AccrualMath_ZeroDuration();
if (elapsed > duration) revert AccrualMath_ElapsedExceedsDuration(elapsed, duration);
amount = Math.mulDiv(endpointAmount, elapsed, duration);
}
/// @notice Newly earned amount between two cumulative linear checkpoints.
/// @dev Subtracts cumulative floors, so arbitrary adjacent checkpoints telescope exactly.
/// Flooring `endpointAmount * (elapsed - previousElapsed) / duration` instead would discard
/// a fresh remainder at every call and make earned value depend on checkpoint frequency.
/// @param endpointAmount The fixed amount earned at the end of the interval.
/// @param duration Positive interval duration, in seconds.
/// @param previousElapsed Earlier cumulative elapsed seconds.
/// @param elapsed Later cumulative elapsed seconds, at most `duration`.
/// @return amount Incremental earned amount between the two checkpoints.
function linearDelta(uint256 endpointAmount, uint64 duration, uint64 previousElapsed, uint64 elapsed)
internal
pure
returns (uint256 amount)
{
if (previousElapsed > elapsed) revert AccrualMath_ReversedWindow(previousElapsed, elapsed);
amount =
linearEarned(endpointAmount, duration, elapsed) - linearEarned(endpointAmount, duration, previousElapsed);
}
/// @dev Validates the existing admission bounds and returns the positive interest denominator.
function _validateTerms(uint256 basis, uint16 rateBps, uint256 yearSeconds)
private
pure
returns (uint256 denominator)
{
if (basis > type(uint256).max / 10_000) revert AccrualMath_BasisTooLarge(basis);
if (rateBps > 10_000) revert AccrualMath_RateTooLarge(rateBps);
if (yearSeconds != 360 days && yearSeconds != 365 days) {
revert AccrualMath_UnsupportedYear(yearSeconds);
}
denominator = 10_000 * yearSeconds;
}
}
src/libraries/AccrualSchedule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title AccrualSchedule — one indexed next event per facility
/// @notice A binary min-heap ordered by (deadline, full-width facility ID).
/// @dev Count, membership, event lookup and minimum lookup are O(1). Insert, reschedule, keyed
/// removal and minimum removal are O(log n), without tombstones or a scan over other events.
/// Zero is a valid facility ID and deadline; every uint256 ID and uint64 deadline is accepted.
/// The caller owns authorization, contractual chronology, processing capacity and events.
/// This library reads no clock, makes no external calls and selects no admission policy.
/// Embed Heap in the host's ERC-7201 storage namespace. Do not directly overwrite its fields
/// or delete a nonempty Heap: Solidity does not clear mapping entries when deleting a struct.
/// Existing OpenZeppelin/Solady heaps do not expose indexed keyed removal or swap hooks for
/// a position map; packing this 320-bit ordering key into uint256 would narrow valid inputs.
library AccrualSchedule {
/// @notice An explicit facility identifier and its next scheduled timestamp.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Event {
uint256 facilityId;
uint64 deadline;
}
/// @notice Heap entries and the one-based position of each scheduled facility.
/// @dev Mapping zero means absent; it does not reserve facility ID zero or timestamp zero.
/// No separate storage namespace or initialization transaction is required.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Heap {
Event[] entries;
mapping(uint256 facilityId => uint256 position) positions;
}
/// @notice An empty schedule has no event to inspect or remove.
error AccrualSchedule_Empty();
/// @notice A facility already has its one permitted next event.
/// @param facilityId The duplicate identifier; use reschedule to change its deadline.
error AccrualSchedule_AlreadyScheduled(uint256 facilityId);
/// @notice The requested facility has no event in this schedule.
/// @param facilityId The missing identifier.
error AccrualSchedule_NotScheduled(uint256 facilityId);
/// @notice Returns the number of scheduled facilities, in O(1).
/// @param self The host's schedule.
/// @return size Number of live entries; no stale or duplicate entries are retained.
function count(Heap storage self) internal view returns (uint256 size) {
size = self.entries.length;
}
/// @notice Reports whether a facility has a next event, in O(1).
/// @param self The host's schedule.
/// @param facilityId The full-width identifier, including zero.
/// @return scheduled Whether the identifier is present.
function contains(Heap storage self, uint256 facilityId) internal view returns (bool scheduled) {
scheduled = self.positions[facilityId] != 0;
}
/// @notice Returns the earliest event; equal deadlines prefer the smaller facility ID.
/// @dev Reverts with AccrualSchedule_Empty if empty. It does not check whether the event is due.
/// @param self The host's schedule.
/// @return next The minimum event, copied into memory without mutating storage.
function peek(Heap storage self) internal view returns (Event memory next) {
if (self.entries.length == 0) revert AccrualSchedule_Empty();
next = self.entries[0];
}
/// @notice Returns one facility's next event, in O(1).
/// @dev Reverts with AccrualSchedule_NotScheduled if the identifier is absent.
/// @param self The host's schedule.
/// @param facilityId The full-width identifier, including zero.
/// @return next The identified event, copied into memory.
function get(Heap storage self, uint256 facilityId) internal view returns (Event memory next) {
uint256 position = self.positions[facilityId];
if (position == 0) revert AccrualSchedule_NotScheduled(facilityId);
next = self.entries[position - 1];
}
/// @notice Inserts a facility's first next event, in O(log n).
/// @dev Duplicate IDs revert. The caller must validate authority, timing and servicing capacity.
/// @param self The host's schedule.
/// @param facilityId Full-width identifier; zero is permitted.
/// @param deadline Explicit timestamp; zero and uint64-max are permitted.
function insert(Heap storage self, uint256 facilityId, uint64 deadline) internal {
if (self.positions[facilityId] != 0) revert AccrualSchedule_AlreadyScheduled(facilityId);
uint256 index = self.entries.length;
self.entries.push(Event(facilityId, deadline));
self.positions[facilityId] = index + 1;
_siftUp(self, index);
}
/// @notice Replaces a present facility's deadline in either direction, in O(log n).
/// @dev A missing ID reverts. An identical deadline is an exact no-op. Moving backward in time
/// is mechanically valid here; the host must enforce any contractual chronology policy.
/// @param self The host's schedule.
/// @param facilityId The existing full-width identifier.
/// @param deadline The replacement timestamp, including either uint64 endpoint.
/// @return previousDeadline The replaced value, allowing the host to emit its transition event.
function reschedule(Heap storage self, uint256 facilityId, uint64 deadline)
internal
returns (uint64 previousDeadline)
{
uint256 position = self.positions[facilityId];
if (position == 0) revert AccrualSchedule_NotScheduled(facilityId);
uint256 index = position - 1;
previousDeadline = self.entries[index].deadline;
if (deadline == previousDeadline) return previousDeadline;
self.entries[index].deadline = deadline;
if (deadline < previousDeadline) {
_siftUp(self, index);
} else {
_siftDown(self, index);
}
}
/// @notice Removes a particular facility's event in O(log n), leaving no position tombstone.
/// @dev A missing identifier reverts. The host decides who may cancel or retire an event.
/// @param self The host's schedule.
/// @param facilityId The full-width identifier to remove.
/// @return removed The old event, allowing the host to emit its transition event.
function remove(Heap storage self, uint256 facilityId) internal returns (Event memory removed) {
uint256 position = self.positions[facilityId];
if (position == 0) revert AccrualSchedule_NotScheduled(facilityId);
removed = _removeAt(self, position - 1);
}
/// @notice Removes and returns the earliest event in O(log n).
/// @dev Reverts if empty. The host must check due time and process the returned contractual
/// event atomically; this data structure neither validates nor performs that processing.
/// @param self The host's schedule.
/// @return removed The minimum event, including its full-width facility ID.
function pop(Heap storage self) internal returns (Event memory removed) {
if (self.entries.length == 0) revert AccrualSchedule_Empty();
removed = _removeAt(self, 0);
}
/// @dev Removes a known valid index, fills its hole with the last entry, then repairs either
/// upward or downward. No external call can observe the temporary relocation.
function _removeAt(Heap storage self, uint256 index) private returns (Event memory removed) {
removed = self.entries[index];
uint256 last = self.entries.length - 1;
if (index != last) {
Event memory replacement = self.entries[last];
self.entries[index] = replacement;
self.positions[replacement.facilityId] = index + 1;
}
self.entries.pop();
delete self.positions[removed.facilityId];
if (index < last) {
if (index != 0 && _less(self.entries[index], self.entries[(index - 1) / 2])) {
_siftUp(self, index);
} else {
_siftDown(self, index);
}
}
}
/// @dev Moves an entry upward until its parent is earlier or it becomes the root.
function _siftUp(Heap storage self, uint256 index) private {
while (index != 0) {
uint256 parent = (index - 1) / 2;
if (!_less(self.entries[index], self.entries[parent])) break;
_swap(self, index, parent);
index = parent;
}
}
/// @dev Visits only internal nodes. `index < size / 2` guarantees that 2*index+1 exists and
/// that both child-index calculations fit uint256, without a narrowing capacity bound.
function _siftDown(Heap storage self, uint256 index) private {
uint256 size = self.entries.length;
while (index < size / 2) {
uint256 child = 2 * index + 1;
uint256 right = child + 1;
if (right < size && _less(self.entries[right], self.entries[child])) child = right;
if (!_less(self.entries[child], self.entries[index])) break;
_swap(self, index, child);
index = child;
}
}
/// @dev Swaps two distinct live entries and updates both reverse positions atomically.
function _swap(Heap storage self, uint256 first, uint256 second) private {
Event memory left = self.entries[first];
Event memory right = self.entries[second];
self.entries[first] = right;
self.entries[second] = left;
self.positions[right.facilityId] = first + 1;
self.positions[left.facilityId] = second + 1;
}
/// @dev Strict lexicographic order with no packed or narrowed facility identifier.
function _less(Event storage left, Event storage right) private view returns (bool) {
return left.deadline < right.deadline || (left.deadline == right.deadline && left.facilityId < right.facilityId);
}
}
src/libraries/AccrualSegments.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {AccrualMath} from "./AccrualMath.sol";
/// @title AccrualSegments
/// @notice Pure fixed-basis entitlement and bounded technical-segment planning.
/// @dev The host supplies authenticated fixed Actual/360 or Actual/365 terms and controls PIK
/// capitalization, cap changes and lifecycle authority. Technical splits never rebase PIK.
/// Cumulative endpoints round the original period's simple interest to the reserve grid;
/// adjacent differences telescope exactly. Interpolating those endpoints is a different
/// partial-time curve from rounding the original simple interest at that instant. Use
/// cumulative for authoritative contractual settlement and handle any discrepancy explicitly
/// in the host's backing/loss accounting. This library makes no such financial-policy choice.
/// It has no state, clock reads, roles, external calls or effects.
library AccrualSegments {
/// @notice Maximum technical interpolation duration; contractual intervals may be longer.
uint64 internal constant MAX_SEGMENT_SECONDS = 365 days;
/// @notice Cached fixed terms for one contractual interest period.
/// @dev cap is the maximum additional interest for this period, not a total loan balance.
/// A technical successor must retain this same basis and periodStart. The host alone
/// changes them at a proved contractual transition. Maturity may truncate periodEnd.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Terms {
uint256 basis;
uint256 yearSeconds;
uint256 scale;
uint256 cap;
uint64 periodStart;
uint64 periodEnd;
uint64 maturity;
uint16 rateBps;
}
/// @notice One bounded segment, its exact endpoint amounts and its termination information.
/// @dev amount equals cumulativeEnd minus cumulativeStart. An already completed period or
/// exhausted cap returns end == start and amount == 0: the host must not open that marker
/// in AccrualBook. Otherwise end is strictly later and at most 365 days away. complete
/// means this period has no remaining entitlement after end; it does not retire the loan.
/// capHit is meaningful only when capReachable, and may be zero for a zero grid cap.
struct Segment {
uint256 cumulativeStart;
uint256 cumulativeEnd;
uint256 amount;
uint64 start;
uint64 end;
uint64 capHit;
bool capReachable;
bool complete;
}
/// @notice A contractual period and its maturity must both lie after the original start.
error AccrualSegments_InvalidPeriod(uint64 periodStart, uint64 periodEnd, uint64 maturity);
/// @notice The requested timestamp lies outside this period's inclusive effective bounds.
error AccrualSegments_TimeOutsidePeriod(uint64 at, uint64 periodStart, uint64 effectiveEnd);
/// @notice Exact cumulative grid-rounded entitlement on the original frozen period basis.
/// @dev Computes floor(min(simpleInterest(at - periodStart), cap) / scale) * scale using
/// AccrualMath's full-precision cap-before-grid calculation. This is the authoritative
/// pure curve for early payoff, amendment and default reconciliation by the host; it
/// must never be posted against a smaller book gross without matching reconciliation.
/// @param terms Fixed authenticated terms; existing AccrualMath numeric bounds apply.
/// @param at Inclusive timestamp from periodStart through min(periodEnd, maturity).
/// @return amount Total entitlement since periodStart, not a per-checkpoint increment.
function cumulative(Terms memory terms, uint64 at) internal pure returns (uint256 amount) {
uint64 effectiveEnd = _effectiveEnd(terms);
_validateTime(terms.periodStart, effectiveEnd, at);
amount = _cumulative(terms, at);
}
/// @notice Plans the next technical segment without modifying the contractual basis.
/// @dev Regular technical boundaries are anchored every 365 days to periodStart. A reachable
/// cap inserts H-1 and H, where H is the first integer timestamp attaining the whole-grid
/// cap. The final one-second segment prevents spreading the capped final increment over
/// a long interval. No loop or precomputation proportional to period duration is needed.
/// @param terms Fixed terms, unchanged across technical successors.
/// @param technicalStart Requested start within the inclusive effective period bounds. The
/// host must use the preceding endpoint except at an authorized lifecycle transition.
/// @return segment Exact cumulative endpoint difference and bounded scheduling metadata.
function plan(Terms memory terms, uint64 technicalStart) internal pure returns (Segment memory segment) {
uint64 effectiveEnd = _effectiveEnd(terms);
_validateTime(terms.periodStart, effectiveEnd, technicalStart);
segment.start = technicalStart;
segment.end = technicalStart;
segment.cumulativeStart = _cumulative(terms, technicalStart);
segment.cumulativeEnd = segment.cumulativeStart;
uint256 gridCap = terms.cap - terms.cap % terms.scale;
uint256 periodTotal = _cumulative(terms, effectiveEnd);
if (periodTotal == gridCap) {
segment.capReachable = true;
if (gridCap == 0) {
segment.capHit = terms.periodStart;
} else {
// Validation in _cumulative guarantees basis <= MAX/10_000 and rate <=10_000,
// so their product fits. A positive reachable grid cap proves a positive product.
// Reachability also proves the ceiling is <= effectiveEnd-periodStart (uint64).
uint256 elapsed =
Math.mulDiv(gridCap, 10_000 * terms.yearSeconds, terms.basis * terms.rateBps, Math.Rounding.Ceil);
segment.capHit = terms.periodStart + uint64(elapsed);
}
}
if (technicalStart == effectiveEnd || (segment.capReachable && technicalStart >= segment.capHit)) {
segment.complete = true;
return segment;
}
uint64 remaining = effectiveEnd - technicalStart;
uint64 technicalRemaining = MAX_SEGMENT_SECONDS - (technicalStart - terms.periodStart) % MAX_SEGMENT_SECONDS;
segment.end = technicalStart + (remaining < technicalRemaining ? remaining : technicalRemaining);
if (segment.capReachable) {
uint64 capBoundary = segment.capHit;
if (capBoundary - technicalStart > 1) --capBoundary;
if (capBoundary < segment.end) segment.end = capBoundary;
}
segment.cumulativeEnd = _cumulative(terms, segment.end);
segment.amount = segment.cumulativeEnd - segment.cumulativeStart;
segment.complete = segment.end == effectiveEnd || (segment.capReachable && segment.end == segment.capHit);
}
/// @dev Validates positive contractual and maturity horizons without reading a clock.
function _effectiveEnd(Terms memory terms) private pure returns (uint64 effectiveEnd) {
if (terms.periodEnd <= terms.periodStart || terms.maturity <= terms.periodStart) {
revert AccrualSegments_InvalidPeriod(terms.periodStart, terms.periodEnd, terms.maturity);
}
effectiveEnd = terms.periodEnd < terms.maturity ? terms.periodEnd : terms.maturity;
}
/// @dev Inclusive bounds also permit querying the original start and exact final endpoint.
function _validateTime(uint64 periodStart, uint64 effectiveEnd, uint64 at) private pure {
if (at < periodStart || at > effectiveEnd) {
revert AccrualSegments_TimeOutsidePeriod(at, periodStart, effectiveEnd);
}
}
/// @dev Called only after validating time bounds; AccrualMath validates every numeric term.
function _cumulative(Terms memory terms, uint64 at) private pure returns (uint256) {
return AccrualMath.periodAmount(
terms.basis, terms.rateBps, at - terms.periodStart, terms.yearSeconds, terms.scale, terms.cap
);
}
}
src/libraries/ReserveAccrualStorageLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IContinuousAccrual} from "../interfaces/IContinuousAccrual.sol";
import {AccrualBook} from "./AccrualBook.sol";
import {AccrualLoans} from "./AccrualLoans.sol";
import {AccrualSchedule} from "./AccrualSchedule.sol";
/// @title ReserveAccrualStorageLib
/// @notice The reserve's own continuous-accrual namespace and storage-only backing helpers.
/// @dev No external reads enter these helpers, including on BSC. Every financial clock is
/// capped at the earliest unresolved event; only authenticated host transitions write it.
library ReserveAccrualStorageLib {
using AccrualSchedule for AccrualSchedule.Heap;
/// @notice Immutable identities copied from the funded bridge record.
struct Identity {
address asset;
uint256 classId;
bytes32 borrowerId;
bytes32 stateId;
uint256 reservedCeiling;
bool known;
}
/// @notice One exact burn within a reserve-derived contractual rounding correction.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Rounding {
uint256 facilityId;
uint64 closureNonce;
address from;
uint256 amount;
bool active;
bool ready;
}
/// @notice The one-time native import session, with a bounded positive-face roster.
/// @dev LAYOUT-FROZEN: embedded storage; append future fields to State instead.
struct Migration {
uint64 cutoff;
uint32 expected;
uint32 imported;
uint16 feeBps;
bool active;
uint256 nonce;
uint256 originalFace;
uint256 importedOriginalFace;
bytes32 sessionKey;
uint256[] facilityIds;
mapping(uint256 facilityId => bytes32) frozenRecords;
}
/// @custom:storage-location erc7201:forestroad.storage.ContinuousAccrual
struct State {
AccrualLoans.State loans;
IContinuousAccrual.Modules modules;
mapping(uint256 facilityId => Identity) identities;
address feeRecipient;
uint256 reservedCeilings;
uint256 nonce;
IContinuousAccrual.Delivery delivery;
IContinuousAccrual.Snapshot deliverySnapshot;
bool enabled;
bool busy;
uint256 recordedFace;
Rounding rounding;
uint256 roundingUnabsorbed;
Migration migration;
// Irreversible feature latch appended after every historical field.
bool mixedInterestEnabled;
}
bytes32 private constant ACCRUAL_STORAGE_LOCATION =
0x2420c1d967401a6739c551e175fd4dfa8e9cd5ee804155e89721bed004930b00;
/// @notice The chain clock cannot be represented by the admitted schedule domain.
error ReserveAccrual_TimeOverflow();
/// @notice Accesses this reserve's independent accounting namespace.
function state() internal pure returns (State storage $) {
assembly {
$.slot := ACCRUAL_STORAGE_LOCATION
}
}
/// @notice Current checked schedule timestamp; no truncating casts are permitted.
function now64() internal view returns (uint64) {
if (block.timestamp > type(uint64).max) revert ReserveAccrual_TimeOverflow();
return uint64(block.timestamp);
}
/// @notice Portfolio clock frontier, including an unresolved endpoint at equality.
function frontier(State storage s) internal view returns (uint64 at) {
at = now64();
AccrualSchedule.Heap storage queue = s.loans.book.schedule;
if (queue.count() != 0) {
uint64 boundary = queue.peek().deadline;
if (boundary < at) at = boundary;
}
}
/// @notice Earned receivable not yet transferred to the native deployed-face ledger.
function unposted() internal view returns (uint256) {
State storage s = state();
if (!s.enabled) return 0;
AccrualBook.Book storage book = s.loans.book;
uint64 at = frontier(s);
return book.total.value + book.total.rate * (at - book.total.at) - book.posted;
}
/// @notice Facility's effective face increment; resolved historic entries return zero.
function facilityUnposted(uint256 facilityId) internal view returns (uint256) {
State storage s = state();
if (!s.enabled) return 0;
AccrualBook.Entry storage entry = s.loans.book.entries[facilityId];
if (!entry.known) return 0;
uint64 at = frontier(s);
return entry.clock.value + entry.clock.rate * (at - entry.clock.at) - entry.posted;
}
/// @notice Domain-separated, constant-time exposure keys for the immutable facility identities.
function keys(uint256 classId, bytes32 borrowerId, bytes32 stateId)
internal
pure
returns (bytes32[3] memory result)
{
result[0] = keccak256(abi.encode(uint8(1), classId));
result[1] = keccak256(abi.encode(uint8(2), borrowerId));
result[2] = keccak256(abi.encode(uint8(3), stateId));
}
}
Настройки компилятораПоказать
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solady/=lib/solady/src/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.