Verified contractPartialMIT
StickyHook
Address0x57bb7161afce10a12b1761483bfc61dfcb2c4df5
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,222,421
- Creation transaction
- 0x2b3d3ca48e…12ccb0da63
55 files
- src/StickyHook.solmain71.67 KB
- node_modules/@bananapus/core-v6/src/enums/JBApprovalStatus.sol865 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBCashOutHook.sol796 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBController.sol19.41 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBDirectory.sol5.25 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBDirectoryAccessControl.sol795 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBFundAccessLimits.sol4.22 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBPayHook.sol755 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBPayerTracker.sol891 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBPriceFeed.sol485 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBPrices.sol5.51 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBProjectUriRegistry.sol644 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBProjects.sol2.8 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBRulesetApprovalHook.sol1.48 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBRulesetDataHook.sol3.56 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBRulesets.sol8.96 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBSplitHook.sol855 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBSplits.sol1.88 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBTerminal.sol8.78 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBToken.sol1.96 KB
- node_modules/@bananapus/core-v6/src/interfaces/IJBTokenUriResolver.sol393 B
- node_modules/@bananapus/core-v6/src/interfaces/IJBTokens.sol8.36 KB
- node_modules/@bananapus/core-v6/src/structs/JBAccountingContext.sol785 B
- node_modules/@bananapus/core-v6/src/structs/JBAfterCashOutRecordedContext.sol1.55 KB
- node_modules/@bananapus/core-v6/src/structs/JBAfterPayRecordedContext.sol1.45 KB
- node_modules/@bananapus/core-v6/src/structs/JBBeforeCashOutRecordedContext.sol1.91 KB
- node_modules/@bananapus/core-v6/src/structs/JBBeforePayRecordedContext.sol1.3 KB
- node_modules/@bananapus/core-v6/src/structs/JBCashOutHookSpecification.sol638 B
- node_modules/@bananapus/core-v6/src/structs/JBCurrencyAmount.sol358 B
- node_modules/@bananapus/core-v6/src/structs/JBFundAccessLimitGroup.sol1.39 KB
- node_modules/@bananapus/core-v6/src/structs/JBPayHookSpecification.sol609 B
- node_modules/@bananapus/core-v6/src/structs/JBRuleset.sol2.15 KB
- node_modules/@bananapus/core-v6/src/structs/JBRulesetConfig.sol1.86 KB
- node_modules/@bananapus/core-v6/src/structs/JBRulesetMetadata.sol3.2 KB
- node_modules/@bananapus/core-v6/src/structs/JBRulesetWithMetadata.sol340 B
- node_modules/@bananapus/core-v6/src/structs/JBSplit.sol2.64 KB
- node_modules/@bananapus/core-v6/src/structs/JBSplitGroup.sol375 B
- node_modules/@bananapus/core-v6/src/structs/JBSplitHookContext.sol755 B
- node_modules/@bananapus/core-v6/src/structs/JBTerminalConfig.sol444 B
- node_modules/@bananapus/core-v6/src/structs/JBTokenAmount.sol578 B
- node_modules/@openzeppelin/contracts/metatx/ERC2771Context.sol3.62 KB
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol4.93 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- node_modules/@openzeppelin/contracts/utils/Panic.sol1.97 KB
- node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol879 B
- node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- node_modules/@openzeppelin/contracts/utils/math/Math.sol32.66 KB
- node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol34.94 KB
- src/interfaces/IStickyDeployer.sol6.42 KB
- src/interfaces/IStickyHook.sol16.36 KB
- src/libraries/StickyPricing.sol5.16 KB
- src/structs/StickyPaySnapshot.sol571 B
- src/structs/StickyTranche.sol561 B
src/StickyHook.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IJBCashOutHook} from "@bananapus/core-v6/src/interfaces/IJBCashOutHook.sol";
import {IJBDirectory} from "@bananapus/core-v6/src/interfaces/IJBDirectory.sol";
import {IJBPayHook} from "@bananapus/core-v6/src/interfaces/IJBPayHook.sol";
import {IJBRulesetDataHook} from "@bananapus/core-v6/src/interfaces/IJBRulesetDataHook.sol";
import {IJBTerminal} from "@bananapus/core-v6/src/interfaces/IJBTerminal.sol";
import {IJBToken} from "@bananapus/core-v6/src/interfaces/IJBToken.sol";
import {JBAfterCashOutRecordedContext} from "@bananapus/core-v6/src/structs/JBAfterCashOutRecordedContext.sol";
import {JBAfterPayRecordedContext} from "@bananapus/core-v6/src/structs/JBAfterPayRecordedContext.sol";
import {JBBeforeCashOutRecordedContext} from "@bananapus/core-v6/src/structs/JBBeforeCashOutRecordedContext.sol";
import {JBBeforePayRecordedContext} from "@bananapus/core-v6/src/structs/JBBeforePayRecordedContext.sol";
import {JBCashOutHookSpecification} from "@bananapus/core-v6/src/structs/JBCashOutHookSpecification.sol";
import {JBPayHookSpecification} from "@bananapus/core-v6/src/structs/JBPayHookSpecification.sol";
import {JBRuleset} from "@bananapus/core-v6/src/structs/JBRuleset.sol";
import {ERC2771Context} from "@openzeppelin/contracts/metatx/ERC2771Context.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IStickyDeployer} from "./interfaces/IStickyDeployer.sol";
import {IStickyHook} from "./interfaces/IStickyHook.sol";
import {StickyPricing} from "./libraries/StickyPricing.sol";
import {StickyPaySnapshot} from "./structs/StickyPaySnapshot.sol";
import {StickyTranche} from "./structs/StickyTranche.sol";
/// @notice A data hook that tracks staking positions for sticky projects. Each stake joins the holder's newest
/// tranche when both were created in the same epoch and otherwise creates a tranche with its own timestamp, unstakes
/// consume tranches newest-first (splitting the newest tranche if needed, without resetting its timestamp), and each
/// holder has a streak clock that starts when their staked balance becomes non-zero and resets only when it returns
/// to zero. Net stake is also bucketed by the epoch it joined in, so the distributor can weigh tenure rewards by
/// tranche age without checkpoints. Streak views are informational; default-group rewards use the share token's voting
/// checkpoints.
// Callbacks are payable to implement the core interfaces, but both explicitly reject ETH.
// slither-disable-next-line locked-ether
contract StickyHook is ERC165, ERC2771Context, IStickyHook {
//*********************************************************************//
// --------------------------- custom errors ------------------------- //
//*********************************************************************//
/// @notice Thrown when a deployer binding is already set, so registration authority cannot be replaced.
/// @param deployer The permanently bound deployer.
error StickyHook_AlreadyBound(address deployer);
/// @notice Thrown when an account other than the deployment authority attempts the one-time deployer binding.
/// @param caller The account attempting the binding.
error StickyHook_BindingUnauthorized(address caller);
/// @notice Thrown when a pay or cash out hook callback comes from an address that isn't a terminal of the project.
/// @param caller The address that attempted the callback.
error StickyHook_CallerNotTerminal(address caller);
/// @notice Thrown when a transfer or burn report comes from an address other than the registered share token.
/// @param caller The address that reported the Sticky share movement.
/// @param token The project's registered Sticky share token.
error StickyHook_CallerNotToken(address caller, address token);
/// @notice Thrown when a share token reports more shares leaving than the holder has staked.
/// @param projectId The ID of the Sticky project.
/// @param holder The holder whose Sticky shares are leaving.
/// @param balance The holder's tracked Sticky share balance.
/// @param count The number of Sticky shares reported as leaving.
error StickyHook_InsufficientStakedBalance(uint256 projectId, address holder, uint256 balance, uint256 count);
/// @notice Thrown when the terminal's backing is below the excluded orphaned balance, since share-owned backing
/// cannot be negative.
/// @param projectId The ID of the Sticky project.
/// @param backing The terminal's current backing for the project.
/// @param orphanedBalance The backing excluded from Sticky share ownership.
error StickyHook_InvalidBacking(uint256 projectId, uint256 backing, uint256 orphanedBalance);
/// @notice Thrown when a deployer is missing or has a different hook, directory or forwarder, so registration
/// authority cannot be bound to an incompatible project launcher.
/// @param deployer The supplied deployer address.
error StickyHook_InvalidDeployer(address deployer);
/// @notice Thrown when no deployment authority is supplied, so the deployer binding cannot remain inaccessible.
/// @param deploymentAuthority The supplied deployment authority.
error StickyHook_InvalidDeploymentAuthority(address deploymentAuthority);
/// @notice Thrown when an epoch range ends before it starts, so it selects no buckets.
/// @param fromEpoch The first epoch in the requested range.
/// @param toEpoch The last epoch in the requested range.
error StickyHook_InvalidEpochRange(uint256 fromEpoch, uint256 toEpoch);
/// @notice Thrown when a payment callback does not carry the pricing snapshot produced by this hook, so its
/// issuance cannot be authenticated.
/// @param projectId The ID of the Sticky project receiving the payment.
/// @param length The byte length of the callback's hook metadata.
error StickyHook_InvalidPricingMetadata(uint256 projectId, uint256 length);
/// @notice Thrown when a share-token callback changes aggregate pricing state before this payment is accounted for,
/// so a stale quote cannot issue shares.
/// @param projectId The ID of the Sticky project receiving the payment.
/// @param expectedSupply The Sticky share supply expected after this payment's issuance.
/// @param actualSupply The Sticky share supply observed after issuance.
/// @param expectedBacking The terminal backing expected after this payment.
/// @param actualBacking The terminal backing observed after the payment.
error StickyHook_PricingStateChanged(
uint256 projectId, uint256 expectedSupply, uint256 actualSupply, uint256 expectedBacking, uint256 actualBacking
);
/// @notice Thrown when a payer stakes to a beneficiary who hasn't trusted them, without being one of the
/// project's granters.
/// @param payer The address paying to add the stake.
/// @param beneficiary The holder whose position would receive the stake.
error StickyHook_SenderNotTrusted(address payer, address beneficiary);
/// @notice Thrown when an address other than the deployer attempts to set a project's granters or share token.
/// @param caller The address that attempted the restricted operation.
/// @param deployer The address permitted to perform the operation.
error StickyHook_Unauthorized(address caller, address deployer);
/// @notice Thrown when the terminal issues a share count other than the one priced by the authenticated
/// pre-payment snapshot.
/// @param projectId The ID of the Sticky project receiving the payment.
/// @param expected The Sticky share count priced from the authenticated snapshot.
/// @param actual The Sticky share count issued by the terminal.
error StickyHook_UnexpectedIssuedCount(uint256 projectId, uint256 expected, uint256 actual);
/// @notice Thrown when a callback receives native funds, which this hook has no path to withdraw.
/// @param value The amount of native currency received.
error StickyHook_UnexpectedValue(uint256 value);
/// @notice Thrown when pricing a payment for a project without a registered Sticky share token, since issuance
/// depends on its share supply.
/// @param projectId The ID of the project without a registered Sticky share token.
error StickyHook_UnknownProject(uint256 projectId);
/// @notice Thrown when a positive payment would issue no Sticky shares, so the payer keeps funds that bought no
/// shares.
/// @param projectId The ID of the Sticky project receiving the payment.
/// @param amount The payment amount that would issue no Sticky shares.
error StickyHook_ZeroIssuance(uint256 projectId, uint256 amount);
//*********************************************************************//
// ------------------------- public constants ------------------------ //
//*********************************************************************//
/// @notice The duration of one stake-age epoch. Tranches created in the same epoch merge, and net stake is
/// bucketed by the epoch it joined in.
uint256 public constant override EPOCH_DURATION = 1 weeks;
//*********************************************************************//
// ----------------------- internal constants ------------------------ //
//*********************************************************************//
/// @notice The most tranches returned by a bounded query, limiting RPC response size.
uint256 internal constant _MAX_TRANCHE_PAGE = 256;
/// @notice The seed of each project's transient slot counting payments whose minted shares are not yet recorded.
/// @dev Solidity 0.8.28 gives the transient data location to value types only, so per-project counters live in
/// keyed slots read with `tload` and written with `tstore`.
bytes32 internal constant _PAYING_SLOT_SEED = keccak256("StickyHook.payingOf");
//*********************************************************************//
// --------------- public immutable stored properties ---------------- //
//*********************************************************************//
/// @notice The only account allowed to bind the deployer once.
/// @dev Has no operation authority after the deployer is bound.
address public immutable override DEPLOYMENT_AUTHORITY;
/// @notice The directory of terminals and controllers for projects.
IJBDirectory public immutable override DIRECTORY;
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/// @notice Whether an address can airdrop stakes to any holder of a sticky project.
/// @custom:param projectId The ID of the sticky project the granter can airdrop to.
/// @custom:param granter The address allowed to airdrop.
mapping(uint256 projectId => mapping(address granter => bool)) public override isGranterOf;
/// @notice Whether a holder allows a sender to add stakes to their position.
/// @custom:param projectId The ID of the sticky project the trust applies to.
/// @custom:param holder The holder whose position the sender can add to.
/// @custom:param sender The trusted sender.
mapping(uint256 projectId => mapping(address holder => mapping(address sender => bool)))
public
override isTrustedSenderOf;
/// @notice The net stake still held from tranches created in each epoch, as a fixed point number with 18
/// decimals.
/// @dev Grows when shares join a position during the epoch and shrinks when a tranche created in the epoch is
/// later consumed, so a project's buckets always sum to its holders' staked balances.
/// @custom:param projectId The ID of the sticky project.
/// @custom:param epoch The epoch, measured as `timestamp / EPOCH_DURATION`.
mapping(uint256 projectId => mapping(uint256 epoch => uint256)) public override netStakedIn;
/// @notice Underlying backing permanently excluded because it was present when the project had no shares.
/// @dev Refreshed when the next positive stake establishes a new supply. With zero supply all current backing
/// is unowned, including donations received since this value was last stored.
/// @custom:param projectId The ID of the sticky project.
mapping(uint256 projectId => uint256) public override orphanedBalanceOf;
/// @notice The total number of Sticky shares in a holder's position, as a fixed point number with 18 decimals.
/// @custom:param projectId The ID of the sticky project the balance belongs to.
/// @custom:param holder The address the balance belongs to.
mapping(uint256 projectId => mapping(address holder => uint256)) public override stakedBalanceOf;
/// @notice The timestamp at which a holder's active streak started, or 0 if nothing is staked.
/// @dev Staking more never moves this timestamp. It resets only when the holder's staked balance returns to zero.
/// @custom:param projectId The ID of the sticky project the streak belongs to.
/// @custom:param holder The address the streak belongs to.
mapping(uint256 projectId => mapping(address holder => uint256)) public override streakStartOf;
/// @notice The Sticky share token allowed to report transfers and burns for a project.
/// @custom:param projectId The ID of the sticky project.
mapping(uint256 projectId => address) public override tokenOf;
//*********************************************************************//
// -------------------- internal stored properties ------------------- //
//*********************************************************************//
/// @notice The longest completed streak a holder has had, in seconds.
/// @dev Does not include the holder's active streak. Use `longestStreakOf(...)` for the combined value.
/// @custom:param projectId The ID of the sticky project the streak belongs to.
/// @custom:param holder The address the streak belongs to.
mapping(uint256 projectId => mapping(address holder => uint256)) internal _longestCompletedStreakOf;
/// @notice The number of active tranches for each holder.
/// @dev Entries at or above this count are discarded and can be overwritten by later stakes.
/// @custom:param projectId The ID of the sticky project.
/// @custom:param holder The holder whose tranches are counted.
mapping(uint256 projectId => mapping(address holder => uint256)) internal _trancheCountOf;
/// @notice The cumulative staked balance through each active tranche, oldest first.
/// @dev Strictly increasing because zero additions are ignored. Binary search finds a partial exit's retained
/// tail without iterating over discarded tranches. Entries outside the active count are never read.
/// @custom:param projectId The ID of the sticky project.
/// @custom:param holder The holder whose tranches are indexed.
/// @custom:param index The tranche's zero-based index.
mapping(uint256 projectId => mapping(address holder => mapping(uint256 index => uint256))) internal _trancheEndOf;
/// @notice Each holder's staking tranches, oldest first, including inactive storage awaiting reuse.
/// @dev Only entries below `_trancheCountOf` are active, and each active tranche was created in a distinct epoch.
/// Logical truncation plus same-epoch merging keeps an exit's cost bounded by the number of epochs it consumes
/// even after arbitrary incoming dust transfers.
/// @custom:param projectId The ID of the sticky project the tranches belong to.
/// @custom:param holder The address the tranches belong to.
/// @custom:param index The tranche's zero-based index.
mapping(uint256 projectId => mapping(address holder => mapping(uint256 index => StickyTranche))) internal
_tranchesOf;
//*********************************************************************//
// -------------------- private stored properties -------------------- //
//*********************************************************************//
/// @notice The address allowed to register project tokens and set granters, once, at launch.
/// @dev Zero until the deployment authority completes the permanent one-time binding.
address private _deployer;
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/// @notice Binds position accounting to the trusted project directory and one-time deployment authority.
/// @param directory The directory of terminals and controllers for projects.
/// @dev The authority binds a deployed launcher that reciprocally references this hook. Project registration
/// remains inaccessible until that binding is complete.
/// @param deploymentAuthority The nonzero account allowed to bind the project's deployer exactly once.
/// @param trustedForwarder A trusted forwarder of transactions to this contract.
constructor(
IJBDirectory directory,
address deploymentAuthority,
address trustedForwarder
)
ERC2771Context(trustedForwarder)
{
// CREATE2 uses the factory as sender, so the intended setup authority must be supplied explicitly.
if (deploymentAuthority == address(0)) {
revert StickyHook_InvalidDeploymentAuthority(deploymentAuthority);
}
// Use the project's directory to authenticate terminal callbacks against its registered terminals.
DIRECTORY = directory;
// Restrict the one-time reciprocal binding without introducing ongoing configuration authority.
DEPLOYMENT_AUTHORITY = deploymentAuthority;
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/// @notice Accepts a terminal's cash out callback without modifying token accounting.
/// @dev Burns are recorded by the registered token, including direct controller burns. Recording them here as
/// well would consume the holder's tranches twice. This compatibility callback is not requested by the hook.
/// @param context The cash out context passed in by the terminal.
function afterCashOutRecordedWith(JBAfterCashOutRecordedContext calldata context) external payable override {
// This callback only acknowledges accounting; accepting ETH would leave it without a withdrawal path.
if (msg.value != 0) revert StickyHook_UnexpectedValue(msg.value);
// Restrict callback entry to a terminal registered for the project whose cash out is being reported.
if (!DIRECTORY.isTerminalOf({projectId: context.projectId, terminal: IJBTerminal(msg.sender)})) {
// Reject unrelated callers even though this compatibility callback makes no accounting changes.
revert StickyHook_CallerNotTerminal(msg.sender);
}
}
/// @notice Records a stake for the payment's beneficiary, joining their newest tranche when it was created in the
/// same epoch and creating a new tranche otherwise. If the beneficiary's staked balance was zero, their streak
/// starts. Staking more never moves an existing streak's start, and a tranche's timestamp only ever moves
/// forward, so a recorded age cannot be backdated by topping up. Tenure rewards weigh tranche age through the
/// epoch buckets; default-group rewards use voting checkpoints.
/// @dev Can only be called by a terminal of the project. No funds are forwarded to this hook.
/// @param context The payment context passed in by the terminal.
function afterPayRecordedWith(JBAfterPayRecordedContext calldata context) external payable override {
// Deposits belong in the terminal's backing; this hook only records the resulting position.
if (msg.value != 0) revert StickyHook_UnexpectedValue(msg.value);
// Only a registered terminal can authenticate the payment and its pre-payment pricing snapshot.
if (!DIRECTORY.isTerminalOf({projectId: context.projectId, terminal: IJBTerminal(msg.sender)})) {
// Prevent an arbitrary caller from fabricating a stake or changing the excluded orphaned balance.
revert StickyHook_CallerNotTerminal(msg.sender);
}
// Account for shares actually issued by the terminal, then verify them against the quoted payment.
uint256 count = context.newlyIssuedTokenCount;
// A callback with no issued shares must either be an empty payment or fail without taking the deposit.
if (count == 0) {
// A positive payment cannot silently donate backing when its issuance rounds down to zero.
if (context.amount.value != 0) {
// Revert the terminal's payment too, so the payer keeps funds that bought no shares.
revert StickyHook_ZeroIssuance({projectId: context.projectId, amount: context.amount.value});
}
// An empty payment cannot create a tranche, start a streak, or establish new orphaned backing.
return;
}
// The terminal mints before calling this hook. Its approve(0) token interaction can invoke arbitrary token
// code in between, so neither nested payments nor burns/donations may cross this pricing snapshot.
if (context.hookMetadata.length != 96) {
// Require exactly the three encoded pricing values before attempting to interpret the snapshot.
revert StickyHook_InvalidPricingMetadata({
projectId: context.projectId, length: context.hookMetadata.length
});
}
// Recover the pre-payment supply and backing that this hook supplied to the authenticated terminal.
StickyPaySnapshot memory snapshot = abi.decode(context.hookMetadata, (StickyPaySnapshot));
// A missing or failed project feed must never make a fallback price dilute existing holders.
// Empty supply starts at one share per underlying unit; later deposits buy a proportional backing claim.
uint256 expectedCount = Math.mulDiv({
x: context.amount.value,
y: snapshot.supply == 0 ? 1e18 : snapshot.supply,
denominator: snapshot.supply == 0
? 10 ** context.amount.decimals
: snapshot.backing - snapshot.orphanedBalance
});
// The terminal's issuance must match the direct quote, including its downward rounding to whole share atoms.
if (count != expectedCount) {
// Reject any alternate terminal or feed calculation that changes the payer's backing-priced issuance.
revert StickyHook_UnexpectedIssuedCount({
projectId: context.projectId, expected: expectedCount, actual: count
});
}
// Read supply after minting to detect intervening mints or burns that would invalidate the quote.
uint256 actualSupply = IJBToken(tokenOf[context.projectId]).totalSupply();
// Read backing in the same token units as the snapshot so donations and nested payments are detectable.
uint256 actualBacking = _backingOf({
terminal: IJBTerminal(msg.sender),
projectId: context.projectId,
token: context.amount.token,
decimals: context.amount.decimals,
currency: context.amount.currency
});
// Only the shares issued for this payment may have been added to the quoted supply.
uint256 expectedSupply = snapshot.supply + count;
// Only this payment's deposit may have been added to the quoted terminal backing.
uint256 expectedBacking = snapshot.backing + context.amount.value;
// Require both sides of the share price to reflect exactly this payment before recording its position.
if (actualSupply != expectedSupply || actualBacking != expectedBacking) {
// Roll back a payment whose intervening token activity would otherwise use a stale issuance price.
revert StickyHook_PricingStateChanged({
projectId: context.projectId,
expectedSupply: expectedSupply,
actualSupply: actualSupply,
expectedBacking: expectedBacking,
actualBacking: actualBacking
});
}
// A bootstrap can discover additional funds left without shares; persist that exclusion when it changes.
if (orphanedBalanceOf[context.projectId] != snapshot.orphanedBalance) {
// Establish the excluded balance only after the terminal has authenticated the bootstrap payment.
orphanedBalanceOf[context.projectId] = snapshot.orphanedBalance;
// Let observers reconcile the backing excluded from holders' share claims.
// All preceding external calls are reads under STATICCALL, so none can reorder these state updates.
// forge-lint: disable-next-item(reentrancy-events)
emit ExcludeOrphanedBalance({
projectId: context.projectId, amount: snapshot.orphanedBalance, caller: msg.sender
});
}
// Record the stake in the beneficiary's newest tranche, starting their streak if their balance was zero.
uint256 stakedBalance = _addTo({projectId: context.projectId, holder: context.beneficiary, count: count});
// The minted shares now have a tranche, so the buckets agree with the supply again for this payment.
_settlePayingFor(context.projectId);
// Publish the authenticated deposit and resulting balance for position histories.
// All preceding external calls are reads under STATICCALL; position accounting makes no external calls.
// forge-lint: disable-next-item(reentrancy-events)
emit Staked({
projectId: context.projectId,
holder: context.beneficiary,
payer: context.payer,
count: count,
stakedBalance: stakedBalance,
caller: msg.sender
});
}
/// @notice Consumes the newest tranches for every Sticky share burn, including burns that reclaim no backing.
/// @dev Only the project's registered Sticky share token can report burns. Zero burns leave accounting unchanged.
/// A holder's exit never depends on the share supply left with other holders. Small supplies can make later
/// deposits unissuable, in which case the payment's rounding checks reject them without taking funds.
/// @param projectId The ID of the sticky project.
/// @param holder The holder whose shares were burned.
/// @param amount The number of shares burned, as a fixed point number with 18 decimals.
function recordBurn(uint256 projectId, address holder, uint256 amount) external override {
// Only the registered share token can report a burn as part of its authenticated balance update.
if (msg.sender != tokenOf[projectId]) {
// Reject fabricated burns that would reduce another holder's tranches without reducing their shares.
revert StickyHook_CallerNotToken({caller: msg.sender, token: tokenOf[projectId]});
}
// A zero burn must not alter tranche ages, streaks, or the holder's activity history.
if (amount == 0) return;
// Remove the burned amount from the newest tranches, preserving the age of any retained shares.
uint256 stakedBalance = _consumeFrom({projectId: projectId, holder: holder, count: amount});
// Report exits even when they came from a direct burn that reclaimed no terminal backing.
emit Unstaked({
projectId: projectId, holder: holder, count: amount, stakedBalance: stakedBalance, caller: msg.sender
});
}
/// @notice Counts a share issuance whose tranche this hook has not yet recorded, flagging the project's payment as
/// in progress until the terminal's after-pay callback records it.
/// @dev Can only be called by the project's registered Sticky share token, which mints only when a terminal pays
/// the project. The count lives in transient storage, so a payment that reverts leaves no flag behind.
/// @param projectId The ID of the sticky project whose shares were issued.
function recordMint(uint256 projectId) external override {
// Only the registered share token can report a mint as part of its authenticated balance update.
if (msg.sender != tokenOf[projectId]) {
// Reject fabricated mints that would block tenure funding for a project without a payment in flight.
revert StickyHook_CallerNotToken({caller: msg.sender, token: tokenOf[projectId]});
}
// Nested payments to the same project each add one, and each after-pay callback removes one.
_setPayingCountOf({projectId: projectId, count: _payingCountOf(projectId) + 1});
}
/// @notice Moves staked accounting between holders for a transferable Sticky share token: the sender's newest
/// tranches are consumed and the moved shares join the receiver's newest tranche of the current epoch, or a fresh
/// one. The receiver's existing streak continues.
/// @dev Can only be called by the project's registered Sticky share token.
/// @param projectId The ID of the sticky project the transfer belongs to.
/// @param from The holder the shares moved from.
/// @param to The holder the shares moved to.
/// @param amount The number of shares moved, as a fixed point number with 18 decimals.
function recordTransfer(uint256 projectId, address from, address to, uint256 amount) external override {
// Only the registered share token can report a transfer as part of its authenticated balance update.
if (msg.sender != tokenOf[projectId]) {
// Reject fabricated transfers that would change tranche ownership without moving any shares.
revert StickyHook_CallerNotToken({caller: msg.sender, token: tokenOf[projectId]});
}
// Zero movements and self transfers cannot create tranches or restart an existing position.
if (amount == 0 || from == to) return;
// Consume the sender's newest tranches, ending their streak if their balance reached zero.
uint256 fromBalance = _consumeFrom({projectId: projectId, holder: from, count: amount});
// Expose the sender's exit and retained balance to the same position history used for burns.
emit Unstaked({
projectId: projectId, holder: from, count: amount, stakedBalance: fromBalance, caller: msg.sender
});
// The moved shares restart their clock in the receiver's newest tranche.
uint256 toBalance = _addTo({projectId: projectId, holder: to, count: amount});
// Attribute the receiver's added stake to the sender while preserving their resulting balance.
emit Staked({
projectId: projectId, holder: to, payer: from, count: amount, stakedBalance: toBalance, caller: msg.sender
});
}
/// @notice Permanently binds the deployer authorized to register project tokens and granters.
/// @dev Only the explicit deployment authority can bind once. The caller is authenticated directly, without
/// forwarding, and the deployed launcher must share this hook's directory and trusted forwarder.
/// @param deployer The deployed launcher that permanently references this hook.
function setDeployer(address deployer) external override {
// Setup authority cannot be impersonated by a constructor factory or forwarded caller.
if (msg.sender != DEPLOYMENT_AUTHORITY) revert StickyHook_BindingUnauthorized(msg.sender);
// A completed binding permanently removes every account's ability to select another launcher.
if (_deployer != address(0)) revert StickyHook_AlreadyBound(_deployer);
// Require deployed reciprocal dependencies before opening project registration.
if (
deployer.code.length == 0 || address(IStickyDeployer(deployer).HOOK()) != address(this)
|| address(IStickyDeployer(deployer).CONTROLLER().DIRECTORY()) != address(DIRECTORY)
|| ERC2771Context(deployer).trustedForwarder() != trustedForwarder()
) revert StickyHook_InvalidDeployer(deployer);
// Store the sole runtime registration authority only after every reciprocal check succeeds.
_deployer = deployer;
emit BindDeployer({deployer: deployer, caller: msg.sender});
}
/// @notice Allows addresses to airdrop stakes to any holder of a sticky project.
/// @dev Can only be called by the deployer, which calls it once at launch — a project's granters are permanent.
/// @param projectId The ID of the sticky project the senders can airdrop to.
/// @param granters The addresses allowed to airdrop.
function setGrantersFor(uint256 projectId, address[] calldata granters) external override {
// Only the launch deployer may grant permission to add stakes without each beneficiary's consent.
if (msg.sender != _deployer) revert StickyHook_Unauthorized({caller: msg.sender, deployer: _deployer});
// Solidity initializes the index to zero, covering every granter supplied at launch.
// forge-lint: disable-next-line(uninitialized-local)
for (uint256 i; i < granters.length; i++) {
// A project-wide granter can add stakes without requiring each beneficiary's individual trust.
// Each launch-time granter needs a separate permission entry; the caller pays for the list it chose.
// forge-lint: disable-next-line(costly-loop)
isGranterOf[projectId][granters[i]] = true;
// Publish each address that beneficiaries must treat as a project-wide authorized sender.
emit SetGranter({projectId: projectId, granter: granters[i], caller: msg.sender});
}
}
/// @notice Registers the Sticky share token allowed to report transfers and burns for a project.
/// @dev Can only be called by the deployer, which calls it once at launch.
/// @param projectId The ID of the sticky project.
/// @param token The Sticky share token.
function setTokenFor(uint256 projectId, address token) external override {
// Only the launch deployer may choose the token trusted to report this project's ownership changes.
if (msg.sender != _deployer) revert StickyHook_Unauthorized({caller: msg.sender, deployer: _deployer});
// Bind movement reports to the share token so external callers cannot change position accounting.
// The SetToken event below records both the project and the token receiving this permission.
// forge-lint: disable-next-line(missing-events-access-control)
tokenOf[projectId] = token;
// Expose the token binding so consumers can identify the authoritative share supply and movement source.
emit SetToken({projectId: projectId, token: token, caller: msg.sender});
}
/// @notice Allows or disallows a sender to add stakes to the caller's position.
/// @param projectId The ID of the sticky project the trust applies to.
/// @param sender The sender to trust or untrust.
/// @param trusted Whether the sender should be trusted.
function setTrustedSenderFor(uint256 projectId, address sender, bool trusted) external override {
// Scope consent to the caller's own position; this never grants access to their underlying tokens.
isTrustedSenderOf[projectId][_msgSender()][sender] = trusted;
// Let holders and senders track whether beneficiary consent has been granted or revoked.
emit SetTrustedSender({projectId: projectId, holder: _msgSender(), sender: sender, trusted: trusted});
}
//*********************************************************************//
// ----------------------- external views ---------------------------- //
//*********************************************************************//
/// @notice The permanently bound project launcher, zero until the one-time setup is completed.
/// @return deployer The launcher authorized to register project tokens and granters.
function DEPLOYER() external view override returns (address deployer) {
return _deployer;
}
/// @notice Prices a cash out against share-owned backing, excluding funds that existed without any shares.
/// @param context The cash out context passed to this hook by the terminal.
/// @return cashOutTaxRate The ruleset's cash out tax rate, unchanged.
/// @return effectiveCashOutCount The number of shares being cashed out, unchanged.
/// @return effectiveTotalSupply The project token's total supply, unchanged.
/// @return effectiveSurplusValue The project's surplus less the excluded orphaned backing.
/// @return hookSpecifications No cash out callbacks; the share token records every burn exactly once.
function beforeCashOutRecordedWith(JBBeforeCashOutRecordedContext calldata context)
external
view
override
returns (
uint256 cashOutTaxRate,
uint256 effectiveCashOutCount,
uint256 effectiveTotalSupply,
uint256 effectiveSurplusValue,
JBCashOutHookSpecification[] memory hookSpecifications
)
{
// The share token reports every burn, so no additional callback is needed to account for this exit.
hookSpecifications = new JBCashOutHookSpecification[](0);
// Funds left without any shares must remain excluded from subsequent holders' redemption claims.
uint256 orphanedBalance = orphanedBalanceOf[context.projectId];
// Verify that the terminal can still cover the excluded funds before subtracting them from surplus.
if (context.surplus.value < orphanedBalance) {
// An inconsistent backing balance cannot safely price a holder's redemption.
revert StickyHook_InvalidBacking({
projectId: context.projectId, backing: context.surplus.value, orphanedBalance: orphanedBalance
});
}
// Preserve the ruleset's cash out curve and share counts, changing only the backing holders can reclaim.
return (
context.cashOutTaxRate,
context.cashOutCount,
context.totalSupply,
// Orphaned funds have no share owner and cannot subsidize this cash out.
context.surplus.value - orphanedBalance,
// Burn accounting belongs to the share token, so the terminal has no follow-up hook to invoke.
hookSpecifications
);
}
/// @notice Prices new shares against their pre-payment backing and requests a callback to record the stake.
/// @dev Self-stakes are always allowed. Stakes to someone else require the payer to be one of the project's
/// granters or a sender the beneficiary has trusted — so nobody can pad a stranger's position.
/// @param context The payment context passed to this hook by the terminal.
/// @return weight The backing-priced issuance weight, or zero if issuance would lose too much to rounding.
/// @return hookSpecifications A specification instructing the terminal to call this hook with no funds forwarded.
function beforePayRecordedWith(JBBeforePayRecordedContext calldata context)
external
view
override
returns (uint256 weight, JBPayHookSpecification[] memory hookSpecifications)
{
// Self-stakes are always allowed; stakes to someone else need the beneficiary's trust or granter status.
if (
context.payer != context.beneficiary && !isGranterOf[context.projectId][context.payer]
&& !isTrustedSenderOf[context.projectId][context.beneficiary][context.payer]
) revert StickyHook_SenderNotTrusted({payer: context.payer, beneficiary: context.beneficiary});
// Use the launch-registered share token as the source of outstanding claims on the project's backing.
address token = tokenOf[context.projectId];
// An unregistered project has no authoritative share supply from which to calculate issuance.
if (token == address(0)) revert StickyHook_UnknownProject(context.projectId);
// Existing supply determines whether issuance bootstraps or preserves holders' proportional backing.
uint256 supply = IJBToken(token).totalSupply();
// Price the deposit against backing before this payment, expressed in the payment token's accounting units.
uint256 backing = _backingOf({
terminal: IJBTerminal(context.terminal),
projectId: context.projectId,
token: context.amount.token,
decimals: context.amount.decimals,
currency: context.amount.currency
});
// An empty project cannot transfer ownership of its existing backing to the next depositor.
uint256 orphanedBalance = supply == 0 ? backing : orphanedBalanceOf[context.projectId];
// The excluded amount must fit within the terminal's balance before deriving share-owned backing.
if (backing < orphanedBalance) {
// Reject inconsistent backing instead of attempting to quote issuance from a negative owned balance.
revert StickyHook_InvalidBacking({
projectId: context.projectId, backing: backing, orphanedBalance: orphanedBalance
});
}
// Convert the backing-based share quote into the core terminal's issuance weight with rounding checks.
weight = StickyPricing.weightFrom({
amount: context.amount.value,
supply: supply,
backing: backing - orphanedBalance,
decimals: context.amount.decimals
});
// Reserve one callback so every successful positive payment records exactly one beneficiary tranche.
hookSpecifications = new JBPayHookSpecification[](1);
// Request position accounting after minting while keeping the entire deposit in terminal backing.
hookSpecifications[0] = JBPayHookSpecification({
hook: IJBPayHook(address(this)),
noop: false,
amount: 0,
// Carry the quote's inputs through the terminal so the callback can reject intervening pricing changes.
metadata: abi.encode(
StickyPaySnapshot({supply: supply, backing: backing, orphanedBalance: orphanedBalance})
)
});
// Give the terminal both the issuance price and the callback needed to verify and record the resulting stake.
return (weight, hookSpecifications);
}
/// @notice No address can mint a sticky project's shares on demand; shares only exist against stakes.
/// @dev The project ID, ruleset and address do not affect the unconditional denial.
/// @return permitted Always false.
function hasMintPermissionFor(uint256, JBRuleset memory, address) external pure override returns (bool permitted) {
// Unbacked discretionary issuance would dilute holders, so this hook never grants mint permission.
return false;
}
/// @notice Whether a payment to a project has minted shares this hook has not yet recorded.
/// @dev The terminal mints before it calls `afterPayRecordedWith`, so during that gap the share-token supply
/// exceeds the sum of the project's epoch buckets. The distributor refuses to read a tenure denominator while this
/// is set.
/// @param projectId The ID of the sticky project to check.
/// @return isPaying Whether a payment's minted shares are still waiting for their tranche.
function isPayingFor(uint256 projectId) external view override returns (bool isPaying) {
return _payingCountOf(projectId) != 0;
}
/// @notice The longest streak a holder has ever had, including their active streak.
/// @param projectId The ID of the sticky project to check the streak of.
/// @param holder The address to check the streak of.
/// @return duration The holder's longest streak duration, in seconds.
function longestStreakOf(uint256 projectId, address holder) external view override returns (uint256 duration) {
// Include an ongoing streak because it can exceed every streak the holder has already completed.
uint256 current = currentStreakOf({projectId: projectId, holder: holder});
// Preserve the holder's historical record when their current position is shorter or empty.
uint256 longestCompleted = _longestCompletedStreakOf[projectId][holder];
// Report the best duration across completed history and uninterrupted current ownership.
return current > longestCompleted ? current : longestCompleted;
}
/// @notice The net stake still held from tranches created within an inclusive epoch range, as a fixed point
/// number with 18 decimals.
/// @param projectId The ID of the sticky project.
/// @param fromEpoch The first epoch to include.
/// @param toEpoch The last epoch to include.
/// @return amount The sum of the range's net stake buckets.
function netStakedWithin(
uint256 projectId,
uint256 fromEpoch,
uint256 toEpoch
)
external
view
override
returns (uint256 amount)
{
// An inverted range selects no buckets, so reject it instead of silently reporting zero.
if (fromEpoch > toEpoch) revert StickyHook_InvalidEpochRange({fromEpoch: fromEpoch, toEpoch: toEpoch});
// Sum every bucket in the range; callers bound the range to the weeks their reward window spans.
for (uint256 epoch = fromEpoch; epoch <= toEpoch; epoch++) {
// Each bucket holds only stake that joined in its epoch and is still held.
amount += netStakedIn[projectId][epoch];
}
}
/// @notice A holder's staked balance held in tranches created through an epoch, as a fixed point number with 18
/// decimals.
/// @dev Tranche timestamps never decrease with their index, so a binary search finds the newest tranche created
/// in or before the epoch and its cumulative endpoint is the balance through that epoch.
/// @param projectId The ID of the sticky project.
/// @param holder The holder whose tranches to read.
/// @param epoch The last epoch to include.
/// @return balance The staked balance from tranches created in or before the epoch.
function stakedBalanceThroughEpochOf(
uint256 projectId,
address holder,
uint256 epoch
)
external
view
override
returns (uint256 balance)
{
// Start at the oldest tranche so the search can include every active tranche.
uint256 low;
// Search the whole active prefix; discarded entries above it are never read.
uint256 high = _trancheCountOf[projectId][holder];
// Find the number of active tranches created through the epoch. Each iteration halves the range.
// Solidity initializes low to zero, including the oldest active tranche in the search.
// forge-lint: disable-next-line(uninitialized-local)
while (low < high) {
// Split the remaining range without adding its two indices, which could overflow.
uint256 middle = low + (high - low) / 2;
// A tranche created through the epoch means the boundary lies strictly after it.
if (uint256(_tranchesOf[projectId][holder][middle].timestamp) / EPOCH_DURATION <= epoch) low = middle + 1;
// Otherwise this tranche is too new, and so is everything after it.
else high = middle;
}
// The cumulative endpoint of the newest qualifying tranche is the balance through the epoch.
return low == 0 ? 0 : _trancheEndOf[projectId][holder][low - 1];
}
/// @notice The number of tranches a holder has.
/// @param projectId The ID of the sticky project to check the tranches of.
/// @param holder The address to check the tranches of.
/// @return count The number of active tranches.
function trancheCountOf(uint256 projectId, address holder) external view override returns (uint256 count) {
// Count only the active prefix; consumed entries can remain in storage for later reuse.
return _trancheCountOf[projectId][holder];
}
/// @notice A holder's tranches, oldest first.
/// @dev Copies every active tranche. Use the paginated overload for positions with many deposits or transfers.
/// @param projectId The ID of the sticky project to get the tranches of.
/// @param holder The address to get the tranches of.
/// @return tranches The active tranches, oldest first.
function tranchesOf(
uint256 projectId,
address holder
)
external
view
override
returns (StickyTranche[] memory tranches)
{
// Copy the complete active prefix in deposit order without exposing entries discarded by prior exits.
return _tranchesIn({projectId: projectId, holder: holder, start: 0, count: _trancheCountOf[projectId][holder]});
}
/// @notice A bounded range of a holder's active tranches, oldest first.
/// @param projectId The ID of the sticky project.
/// @param holder The holder whose tranches to read.
/// @param start The zero-based index of the first tranche to read.
/// @param count The maximum number of tranches to return, capped at 256.
/// @return tranches The requested tranches, ending at the active count if fewer remain.
function tranchesOf(
uint256 projectId,
address holder,
uint256 start,
uint256 count
)
external
view
override
returns (StickyTranche[] memory tranches)
{
// Limit each page's allocation and RPC response size even when a holder has many incoming tranches.
if (count > _MAX_TRANCHE_PAGE) count = _MAX_TRANCHE_PAGE;
// Clamp the requested page to active entries while preserving their oldest-first ordering.
return _tranchesIn({projectId: projectId, holder: holder, start: start, count: count});
}
//*********************************************************************//
// -------------------------- public views --------------------------- //
//*********************************************************************//
/// @notice The duration of a holder's active streak, in seconds.
/// @param projectId The ID of the sticky project to check the streak of.
/// @param holder The address to check the streak of.
/// @return duration The number of seconds since the holder's staked balance last became non-zero, or 0 if nothing
/// is staked.
function currentStreakOf(uint256 projectId, address holder) public view override returns (uint256 duration) {
// The saved start tracks uninterrupted positive ownership, independently of individual tranche ages.
uint256 streakStart = streakStartOf[projectId][holder];
// An empty position has no active duration; otherwise measure time since its balance first became positive.
return streakStart == 0 ? 0 : block.timestamp - streakStart;
}
/// @notice Indicates whether this contract adheres to the specified interface.
/// @param interfaceId The ID of the interface to check for adherence to.
/// @return supported Whether the provided interface ID is supported.
function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool supported) {
// Advertise the Sticky and core hook entry points while retaining the inherited ERC165 support.
return interfaceId == type(IStickyHook).interfaceId || interfaceId == type(IJBRulesetDataHook).interfaceId
|| interfaceId == type(IJBPayHook).interfaceId || interfaceId == type(IJBCashOutHook).interfaceId
|| super.supportsInterface(interfaceId);
}
//*********************************************************************//
// ---------------------- internal transactions ---------------------- //
//*********************************************************************//
/// @notice Records shares joining a holder's position, merging them into the newest tranche when it was created
/// in the current epoch and appending a fresh tranche otherwise, and starts their streak if their staked balance
/// was zero.
/// @dev Merging keeps every active tranche in a distinct epoch, which bounds the bucket updates an exit makes to
/// the number of epochs the holder staked in. A merged tranche takes the current timestamp, so its recorded age
/// never overstates the age of the shares that joined last.
/// @param projectId The ID of the sticky project.
/// @param holder The holder the shares joined.
/// @param count The number of shares joining, as a fixed point number with 18 decimals.
/// @return stakedBalance The holder's staked balance after the addition.
function _addTo(uint256 projectId, address holder, uint256 count) internal returns (uint256 stakedBalance) {
// Extend the existing position so a top-up preserves earlier tranches and any uninterrupted streak.
stakedBalance = stakedBalanceOf[projectId][holder];
// Empty additions must not create zero-sized tranches or start an ownership clock.
if (count == 0) return stakedBalance;
// Append to the active prefix, reusing discarded storage while preserving cumulative-balance ordering.
uint256 index = _trancheCountOf[projectId][holder];
// The resulting total is both the holder's balance and the newest tranche's cumulative endpoint.
stakedBalance += count;
// Bucket the addition by the epoch it joins in, so aged stake can be totaled without checkpoints.
uint256 epoch = block.timestamp / EPOCH_DURATION;
// Shares joining in the epoch of the newest tranche share its age, so they extend it instead of a new entry.
// Whole-epoch comparison; a validator moving the timestamp within a block cannot change entitlements.
// forge-lint: disable-next-item(block-timestamp)
// slither-disable-next-line incorrect-equality
if (index != 0 && uint256(_tranchesOf[projectId][holder][index - 1].timestamp) / EPOCH_DURATION == epoch) {
// Edit the newest tranche in place; its index becomes the cumulative endpoint written below.
index -= 1;
// Read the tranche once for both the amount extension and the timestamp refresh.
StickyTranche storage tranche = _tranchesOf[projectId][holder][index];
// Grow the tranche by the joining shares; the checked cast prevents truncating the amount.
tranche.amount = SafeCast.toUint208(uint256(tranche.amount) + count);
// Move the tranche's age to the latest joining, so it never overstates how long its shares have stuck.
tranche.timestamp = SafeCast.toUint48(block.timestamp);
} else {
// Give incoming shares their own deposit age; checked casts prevent truncating the amount or timestamp.
_tranchesOf[projectId][holder][index] =
StickyTranche({amount: SafeCast.toUint208(count), timestamp: SafeCast.toUint48(block.timestamp)});
// Include the appended tranche in the logical stack without reactivating any later discarded storage.
_trancheCountOf[projectId][holder] = index + 1;
}
// Store the cumulative endpoint so a later newest-first exit can locate its retained tail by binary search.
_trancheEndOf[projectId][holder][index] = stakedBalance;
// Credit the epoch's bucket; the matching exit debits the same epoch, so buckets always sum to balances.
netStakedIn[projectId][epoch] += count;
// Keep aggregate position accounting aligned with the sum of the holder's active tranches.
stakedBalanceOf[projectId][holder] = stakedBalance;
// Only the first positive addition starts a streak; top-ups must not reset uninterrupted ownership.
if (streakStartOf[projectId][holder] == 0) {
// Anchor the streak to the moment this holder first enters their current nonzero position.
streakStartOf[projectId][holder] = block.timestamp;
// Publish the ownership clock's start separately from the caller's stake event.
// This helper makes no external calls; its callers only read external state under STATICCALL.
// forge-lint: disable-next-line(reentrancy-events)
emit StreakStarted({projectId: projectId, holder: holder, caller: msg.sender});
}
}
/// @notice Consumes a holder's newest tranches to cover shares leaving their position, splitting the last tranche
/// in place (keeping its original timestamp), debiting each consumed tranche's original epoch bucket, and ending
/// the holder's streak if their balance reached zero.
/// @dev The retained tail is found by binary search. Each fully consumed tranche then debits its own epoch's
/// bucket, so an exit's cost grows with the number of distinct epochs it consumes, not with the number of
/// deposits made in them.
/// @param projectId The ID of the sticky project.
/// @param holder The holder the shares left.
/// @param count The number of shares leaving, as a fixed point number with 18 decimals.
/// @return stakedBalance The holder's staked balance after the consumption.
function _consumeFrom(uint256 projectId, address holder, uint256 count) internal returns (uint256 stakedBalance) {
// Use the aggregate tracked balance to bound the exit before touching individual tranche records.
stakedBalance = stakedBalanceOf[projectId][holder];
// A zero exit leaves tranche ages and the holder's active streak intact.
if (count == 0) return stakedBalance;
// Token movement reports cannot remove more shares than this hook has recorded for the holder.
if (count > stakedBalance) {
// Fail with the accounting mismatch instead of underflowing or consuming another position's shares.
revert StickyHook_InsufficientStakedBalance({
projectId: projectId, holder: holder, balance: stakedBalance, count: count
});
}
// The balance left after this exit determines the oldest prefix of tranches that must remain active.
stakedBalance -= count;
// Keep the aggregate synchronized with the retained prefix before adjusting its tranche boundary.
stakedBalanceOf[projectId][holder] = stakedBalance;
// Every tranche at or above this index leaves the position entirely and must debit its epoch bucket.
uint256 activeCount = _trancheCountOf[projectId][holder];
// The oldest tranche that leaves entirely; a full exit removes them all, starting at the oldest.
uint256 removedFrom;
// A full exit needs no search because every tranche can be removed from the logical stack at once.
if (stakedBalance == 0) {
// Discard the entire logical stack; the bucket loop below still visits each removed tranche's epoch.
_trancheCountOf[projectId][holder] = 0;
} else {
// Start at the oldest tranche so the search includes every possible retained prefix.
uint256 low;
// A positive retained balance guarantees an active tranche and bounds the search at its newest entry.
uint256 high = activeCount - 1;
// Find the first cumulative tranche balance that contains the retained balance. Each iteration halves
// the range, so even a dust-filled position can exit without scanning or deleting its newest tranches.
// Solidity initializes low to zero, including the oldest active tranche in the search.
// forge-lint: disable-next-line(uninitialized-local)
while (low < high) {
// Split the remaining range without adding its two indices, which could overflow.
uint256 middle = low + (high - low) / 2;
// An endpoint below the retained balance means the boundary lies strictly after this tranche.
if (_trancheEndOf[projectId][holder][middle] < stakedBalance) low = middle + 1;
// Otherwise this tranche can contain the boundary, so keep it while dropping later candidates.
else high = middle;
}
// Edit the last retained tranche in place so its surviving shares keep their original deposit timestamp.
StickyTranche storage tranche = _tranchesOf[projectId][holder][low];
// Only the part above the retained balance leaves; an exact endpoint leaves this tranche intact.
uint256 trimmed = _trancheEndOf[projectId][holder][low] - stakedBalance;
// Remove the trimmed part while keeping the tranche's original timestamp.
tranche.amount = SafeCast.toUint208(tranche.amount - trimmed);
// Debit the trimmed part from the epoch this tranche joined in, not the epoch it leaves in.
netStakedIn[projectId][uint256(tranche.timestamp) / EPOCH_DURATION] -= trimmed;
// Align the retained tail's cumulative endpoint with the holder's reduced aggregate balance.
_trancheEndOf[projectId][holder][low] = stakedBalance;
// Discard all newer tranches logically; only their epoch buckets still need debiting below.
_trancheCountOf[projectId][holder] = low + 1;
// Every tranche after the retained tail leaves entirely.
removedFrom = low + 1;
}
// Debit each fully removed tranche from its original epoch bucket. Merging keeps active tranches in distinct
// epochs, so this loop runs once per epoch the exit consumes rather than once per deposit.
// Solidity initializes `removedFrom` to zero, which a full exit relies on to visit every active tranche.
// forge-lint: disable-next-line(uninitialized-local)
for (uint256 i = removedFrom; i < activeCount; i++) {
// Read the removed tranche once for both its epoch and its amount.
StickyTranche storage removed = _tranchesOf[projectId][holder][i];
// Return the tranche's full amount to the bucket it was credited to when it joined.
// Each consumed epoch needs its own bucket debit; the exiting holder pays for the epochs they staked in.
// forge-lint: disable-next-line(costly-loop)
netStakedIn[projectId][uint256(removed.timestamp) / EPOCH_DURATION] -= removed.amount;
}
// Partial exits preserve uninterrupted positive ownership; only a complete exit ends the streak.
if (stakedBalance == 0) {
// Read the active start before clearing it so the completed duration can be preserved.
uint256 streakStart = streakStartOf[projectId][holder];
// Only an active streak has a duration to record or an ending event to publish.
if (streakStart != 0) {
// Measure the ownership interval through this exit, independently of which tranches it consumed.
uint256 duration = block.timestamp - streakStart;
// Preserve the maximum completed duration without replacing a longer historical streak.
// Streak durations are informational and never determine balances or reward entitlements.
// forge-lint: disable-next-line(block-timestamp)
if (duration > _longestCompletedStreakOf[projectId][holder]) {
// Save the record so it remains queryable while the holder is unstaked or starts over.
_longestCompletedStreakOf[projectId][holder] = duration;
}
// Mark ownership as interrupted so a later positive addition must start a fresh streak.
streakStartOf[projectId][holder] = 0;
// Publish the completed duration for histories that track uninterrupted ownership over time.
emit StreakEnded({projectId: projectId, holder: holder, duration: duration, caller: msg.sender});
}
}
}
/// @notice Writes a project's count of payments whose minted shares are not yet recorded.
/// @param projectId The ID of the sticky project.
/// @param count The number of payments in flight.
function _setPayingCountOf(uint256 projectId, uint256 count) internal {
// Locate the project's keyed transient counter.
bytes32 slot = _payingSlotOf(projectId);
// Transient storage resets at the end of the transaction, so a reverted payment leaves nothing behind.
// Solidity has no keyed transient variables, so the write goes straight to the slot.
// forge-lint: disable-next-item(inline-assembly)
assembly ("memory-safe") {
tstore(slot, count)
}
}
/// @notice Removes one payment from a project's count of unrecorded mints once its tranche is recorded.
/// @param projectId The ID of the sticky project.
function _settlePayingFor(uint256 projectId) internal {
// Read how many payments to the project still have unrecorded mints in this transaction.
uint256 paying = _payingCountOf(projectId);
// Nothing is cleared when no mint was counted in this transaction, so a callback on its own cannot underflow.
if (paying != 0) _setPayingCountOf({projectId: projectId, count: paying - 1});
}
//*********************************************************************//
// ----------------------- internal helpers -------------------------- //
//*********************************************************************//
/// @notice The transient slot counting a project's payments whose minted shares are not yet recorded.
/// @param projectId The ID of the sticky project.
/// @return slot The project's keyed transient slot.
function _payingSlotOf(uint256 projectId) internal pure returns (bytes32 slot) {
// Fixed-width encoding under a contract-specific seed keeps every project's slot distinct. The hash runs once
// per mint and once per callback, so an assembly hash would save little for the readability it costs.
// forge-lint: disable-next-line(asm-keccak256)
return keccak256(abi.encode(_PAYING_SLOT_SEED, projectId));
}
//*********************************************************************//
// ----------------------- internal views ---------------------------- //
//*********************************************************************//
/// @notice Reads pre-payment or post-payment backing in the project's single accepted token.
/// @param terminal The project's immutable terminal.
/// @param projectId The ID of the sticky project.
/// @param token The accepted underlying token.
/// @param decimals The underlying token's accounting decimals.
/// @param currency The underlying token's accounting currency.
/// @return backing The terminal backing in underlying token atoms, including excluded orphaned funds.
function _backingOf(
IJBTerminal terminal,
uint256 projectId,
address token,
uint8 decimals,
uint32 currency
)
internal
view
returns (uint256 backing)
{
// The terminal accepts a token list, while each Sticky project prices shares against one underlying token.
address[] memory tokens = new address[](1);
// Restrict the surplus query to the accepted underlying so unrelated terminal assets cannot affect pricing.
tokens[0] = token;
// Express gross backing in the payment's accounting units; callers separately exclude orphaned funds.
return terminal.currentSurplusOf({projectId: projectId, tokens: tokens, decimals: decimals, currency: currency});
}
/// @notice Reads a project's count of payments whose minted shares are not yet recorded.
/// @param projectId The ID of the sticky project.
/// @return count The number of payments in flight.
function _payingCountOf(uint256 projectId) internal view returns (uint256 count) {
// Locate the project's keyed transient counter.
bytes32 slot = _payingSlotOf(projectId);
// The slot is keyed by project, so payments to other projects never appear in this count.
// Solidity has no keyed transient variables, so the read comes straight from the slot.
// forge-lint: disable-next-item(inline-assembly)
assembly ("memory-safe") {
count := tload(slot)
}
}
/// @notice Copies a bounded range of active tranches without exposing logically discarded entries.
/// @param projectId The ID of the sticky project.
/// @param holder The holder whose tranches to read.
/// @param start The zero-based index of the first tranche to read.
/// @param count The maximum number of tranches to return.
/// @return tranches The requested range of active tranches.
function _tranchesIn(
uint256 projectId,
address holder,
uint256 start,
uint256 count
)
internal
view
returns (StickyTranche[] memory tranches)
{
// Bound the copy to active entries so logically discarded tranches are never exposed.
uint256 activeCount = _trancheCountOf[projectId][holder];
// An out-of-range page has no active entries, including when the holder has exited every tranche.
if (start >= activeCount) return new StickyTranche[](0);
// Subtraction is safe after the bounds check and avoids overflowing a caller-supplied start plus count.
uint256 available = activeCount - start;
// Shorten the final page so it cannot include inactive storage awaiting reuse.
if (count > available) count = available;
// Allocate only the entries this page can actually return.
tranches = new StickyTranche[](count);
// Solidity initializes the index to zero, filling the result from its first element.
// forge-lint: disable-next-line(uninitialized-local)
for (uint256 i; i < count; i++) {
// Preserve storage order so the returned page runs from older deposits toward newer ones.
tranches[i] = _tranchesOf[projectId][holder][start + i];
}
}
}
node_modules/@bananapus/core-v6/src/enums/JBApprovalStatus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The lifecycle states a queued ruleset can be in relative to its approval hook.
/// @dev `Empty` — no ruleset exists.
/// `Upcoming` — queued but not yet eligible for approval check.
/// `Active` — currently governing the project.
/// `ApprovalExpected` — provisionally approved and still replaceable before final approval.
/// Hooks should return it only when the ruleset will become `Approved` if no later ruleset replaces it first.
/// `Approved` — passed the approval hook and is final for its scheduled cycle. Later rulesets must derive from it
/// instead of replacing it within that cycle.
/// `Failed` — rejected by the approval hook; the previous ruleset continues.
enum JBApprovalStatus {
Empty,
Upcoming,
Active,
ApprovalExpected,
Approved,
Failed
}
node_modules/@bananapus/core-v6/src/interfaces/IJBCashOutHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {JBAfterCashOutRecordedContext} from "./../structs/JBAfterCashOutRecordedContext.sol";
/// @notice Hook called after a terminal's `cashOutTokensOf(...)` logic completes (if passed by the ruleset's data
/// hook).
interface IJBCashOutHook is IERC165 {
/// @notice Called by the terminal after a cash out has been recorded in the terminal store.
/// @dev Critical business logic should be protected by appropriate access control.
/// @param context The context passed in by the terminal, as a `JBAfterCashOutRecordedContext` struct.
function afterCashOutRecordedWith(JBAfterCashOutRecordedContext calldata context) external payable;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBController.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IJBDirectory} from "./IJBDirectory.sol";
import {IJBDirectoryAccessControl} from "./IJBDirectoryAccessControl.sol";
import {IJBFundAccessLimits} from "./IJBFundAccessLimits.sol";
import {IJBPriceFeed} from "./IJBPriceFeed.sol";
import {IJBPrices} from "./IJBPrices.sol";
import {IJBProjects} from "./IJBProjects.sol";
import {IJBProjectUriRegistry} from "./IJBProjectUriRegistry.sol";
import {IJBRulesets} from "./IJBRulesets.sol";
import {IJBSplits} from "./IJBSplits.sol";
import {IJBToken} from "./IJBToken.sol";
import {IJBTokens} from "./IJBTokens.sol";
import {JBApprovalStatus} from "./../enums/JBApprovalStatus.sol";
import {JBRuleset} from "./../structs/JBRuleset.sol";
import {JBRulesetConfig} from "./../structs/JBRulesetConfig.sol";
import {JBRulesetMetadata} from "./../structs/JBRulesetMetadata.sol";
import {JBRulesetWithMetadata} from "./../structs/JBRulesetWithMetadata.sol";
import {JBSplit} from "./../structs/JBSplit.sol";
import {JBSplitGroup} from "./../structs/JBSplitGroup.sol";
import {JBTerminalConfig} from "./../structs/JBTerminalConfig.sol";
/// @notice The interface for the protocol's project controller — launch projects, queue rulesets, mint/burn tokens,
/// deploy ERC-20s, distribute reserved tokens, and manage all project configuration. This is the primary contract
/// project owners and frontends interact with.
interface IJBController is IERC165, IJBProjectUriRegistry, IJBDirectoryAccessControl {
/// @notice Tokens were burned from a holder's balance.
/// @param holder The address whose tokens were burned.
/// @param projectId The ID of the project whose tokens were burned.
/// @param tokenCount The number of tokens burned.
/// @param memo A memo associated with the burn.
/// @param caller The address that called the burn function.
event BurnTokens(
address indexed holder, uint256 indexed projectId, uint256 tokenCount, string memo, address caller
);
/// @notice An ERC-20 token was deployed for a project.
/// @param projectId The ID of the project the token was deployed for.
/// @param deployer The address that deployed the token.
/// @param salt The salt used for deterministic deployment.
/// @param saltHash The hash of the salt.
/// @param caller The address that called the deploy function.
event DeployERC20(
uint256 indexed projectId, address indexed deployer, bytes32 salt, bytes32 saltHash, address caller
);
/// @notice A project was launched with its initial rulesets and terminals.
/// @param rulesetId The ID of the first queued ruleset.
/// @param projectId The ID of the newly created project.
/// @param projectUri The metadata URI of the project.
/// @param memo A memo associated with the launch.
/// @param caller The address that called the launch function.
event LaunchProject(uint256 rulesetId, uint256 projectId, string projectUri, string memo, address caller);
/// @notice Rulesets were launched for an existing project.
/// @param rulesetId The ID of the first queued ruleset.
/// @param projectId The ID of the project.
/// @param projectUri The metadata URI of the project.
/// @param memo A memo associated with the launch.
/// @param caller The address that called the launch function.
event LaunchRulesets(uint256 rulesetId, uint256 projectId, string projectUri, string memo, address caller);
/// @notice Tokens were minted for a beneficiary.
/// @param beneficiary The address that received the minted tokens.
/// @param projectId The ID of the project whose tokens were minted.
/// @param tokenCount The total number of tokens minted, including reserved tokens.
/// @param beneficiaryTokenCount The number of tokens minted for the beneficiary.
/// @param memo A memo associated with the mint.
/// @param reservedPercent The reserved percent applied to the mint, out of `JBConstants.MAX_RESERVED_PERCENT`.
/// @param caller The address that called the mint function.
event MintTokens(
address indexed beneficiary,
uint256 indexed projectId,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
uint256 reservedPercent,
address caller
);
/// @notice Rulesets were queued for a project.
/// @param rulesetId The ID of the first queued ruleset.
/// @param projectId The ID of the project.
/// @param memo A memo associated with the queue operation.
/// @param caller The address that called the queue function.
event QueueRulesets(uint256 rulesetId, uint256 projectId, string memo, address caller);
/// @notice A reserved token distribution to a split reverted.
/// @param projectId The ID of the project.
/// @param split The split that the distribution reverted for.
/// @param tokenCount The number of tokens that failed to distribute.
/// @param reason The revert reason.
/// @param caller The address that called the distribution function.
event ReservedDistributionReverted(
uint256 indexed projectId, JBSplit split, uint256 tokenCount, bytes reason, address caller
);
/// @notice A split hook's `processSplitWith` call reverted.
/// @param projectId The ID of the project.
/// @param hook The split hook that reverted.
/// @param reason The revert reason.
/// @param caller The address that called the distribution function.
event SplitHookReverted(uint256 indexed projectId, address hook, bytes reason, address caller);
/// @notice Reserved tokens were sent to a specific split.
/// @param projectId The ID of the project.
/// @param rulesetId The ID of the ruleset during the distribution.
/// @param groupId The ID of the split group.
/// @param split The split that received the tokens.
/// @param tokenCount The number of tokens sent to the split.
/// @param caller The address that called the distribution function.
event SendReservedTokensToSplit(
uint256 indexed projectId,
uint256 indexed rulesetId,
uint256 indexed groupId,
JBSplit split,
uint256 tokenCount,
address caller
);
/// @notice Reserved tokens were distributed to a project's splits.
/// @param rulesetId The ID of the ruleset during the distribution.
/// @param rulesetCycleNumber The cycle number of the ruleset.
/// @param projectId The ID of the project.
/// @param owner The project's owner.
/// @param tokenCount The total number of reserved tokens distributed.
/// @param leftoverAmount The number of tokens left over after distribution.
/// @param caller The address that called the distribution function.
event SendReservedTokensToSplits(
uint256 indexed rulesetId,
uint256 indexed rulesetCycleNumber,
uint256 indexed projectId,
address owner,
uint256 tokenCount,
uint256 leftoverAmount,
address caller
);
/// @notice A project's metadata URI was set.
/// @param projectId The ID of the project.
/// @param uri The metadata URI that was set.
/// @param caller The address that called the set URI function.
event SetUri(uint256 indexed projectId, string uri, address caller);
/// @notice The directory of terminals and controllers for projects.
function DIRECTORY() external view returns (IJBDirectory);
/// @notice The contract that stores fund access limits for each project.
function FUND_ACCESS_LIMITS() external view returns (IJBFundAccessLimits);
/// @notice The address of the contract that manages omnichain ruleset ops.
function OMNICHAIN_RULESET_OPERATOR() external view returns (address);
/// @notice The contract that stores prices for each project.
function PRICES() external view returns (IJBPrices);
/// @notice Mints ERC-721s that represent project ownership and transfers.
function PROJECTS() external view returns (IJBProjects);
/// @notice The contract storing and managing project rulesets.
function RULESETS() external view returns (IJBRulesets);
/// @notice The contract that stores splits for each project.
function SPLITS() external view returns (IJBSplits);
/// @notice The contract that manages token minting and burning.
function TOKENS() external view returns (IJBTokens);
/// @notice Returns an array of a project's rulesets with metadata, sorted from latest to earliest.
/// @param projectId The ID of the project to get the rulesets of.
/// @param startingId The ID of the ruleset to begin with. If 0, the project's latest ruleset is used.
/// @param size The maximum number of rulesets to return.
/// @return rulesets The array of rulesets with their metadata.
function allRulesetsOf(
uint256 projectId,
uint256 startingId,
uint256 size
)
external
view
returns (JBRulesetWithMetadata[] memory rulesets);
/// @notice Returns a project's currently active ruleset and its metadata.
/// @param projectId The ID of the project to get the current ruleset of.
/// @return ruleset The current ruleset.
/// @return metadata The current ruleset's metadata.
function currentRulesetOf(uint256 projectId)
external
view
returns (JBRuleset memory ruleset, JBRulesetMetadata memory metadata);
/// @notice Returns the ruleset and metadata for a specific ruleset ID.
/// @param projectId The ID of the project the ruleset belongs to.
/// @param rulesetId The ID of the ruleset to look up.
/// @return ruleset The ruleset.
/// @return metadata The ruleset's metadata.
function getRulesetOf(
uint256 projectId,
uint256 rulesetId
)
external
view
returns (JBRuleset memory ruleset, JBRulesetMetadata memory metadata);
/// @notice Returns the latest queued ruleset for a project, its metadata, and its approval status.
/// @param projectId The ID of the project to get the latest queued ruleset of.
/// @return ruleset The latest queued ruleset.
/// @return metadata The ruleset's metadata.
/// @return approvalStatus The ruleset's approval status.
function latestQueuedRulesetOf(uint256 projectId)
external
view
returns (JBRuleset memory ruleset, JBRulesetMetadata memory metadata, JBApprovalStatus approvalStatus);
/// @notice Returns a project's unrealized reserved token balance.
/// @param projectId The ID of the project to get the pending reserved token balance of.
/// @return The pending reserved token balance.
function pendingReservedTokenBalanceOf(uint256 projectId) external view returns (uint256);
/// @notice Previews how many beneficiary and reserved tokens `mintTokensOf(...)` would produce.
/// @param projectId The ID of the project to mint tokens for.
/// @param tokenCount The number of tokens to mint, including any reserved tokens.
/// @param useReservedPercent Whether to apply the ruleset's reserved percent.
/// @return beneficiaryTokenCount The number of tokens that would be minted for the beneficiary.
/// @return reservedTokenCount The number of tokens that would be reserved.
function previewMintOf(
uint256 projectId,
uint256 tokenCount,
bool useReservedPercent
)
external
view
returns (uint256 beneficiaryTokenCount, uint256 reservedTokenCount);
/// @notice Returns a project's total token supply including pending reserved tokens.
/// @param projectId The ID of the project to get the total token supply of.
/// @return The total supply including pending reserved tokens.
function totalTokenSupplyWithReservedTokensOf(uint256 projectId) external view returns (uint256);
/// @notice Returns a project's upcoming ruleset and its metadata.
/// @param projectId The ID of the project to get the upcoming ruleset of.
/// @return ruleset The upcoming ruleset.
/// @return metadata The upcoming ruleset's metadata.
function upcomingRulesetOf(uint256 projectId)
external
view
returns (JBRuleset memory ruleset, JBRulesetMetadata memory metadata);
/// @notice Adds a price feed for a project.
/// @param projectId The ID of the project to add the feed for.
/// @param pricingCurrency The currency the feed's output price is in terms of.
/// @param unitCurrency The currency the feed prices.
/// @param feed The price feed to add.
function addPriceFeedFor(
uint256 projectId,
uint256 pricingCurrency,
uint256 unitCurrency,
IJBPriceFeed feed
)
external;
/// @notice Burns a holder's project tokens or unclaimed project token credits, removing them from supply.
/// @param holder The address whose project tokens (or credits) are being burned.
/// @param projectId The ID of the project whose project tokens are being burned.
/// @param tokenCount The number of project tokens (or credits) to burn.
/// @param memo A memo to pass along to the emitted event.
function burnTokensOf(address holder, uint256 projectId, uint256 tokenCount, string calldata memo) external;
/// @notice Converts project token credits into the project's ERC-20 representation, sending them to a beneficiary.
/// @param holder The address whose project token credits are being redeemed.
/// @param projectId The ID of the project whose project tokens are being claimed.
/// @param tokenCount The number of project token credits to convert into ERC-20 project tokens.
/// @param beneficiary The account that receives the resulting ERC-20 project tokens.
function claimTokensFor(address holder, uint256 projectId, uint256 tokenCount, address beneficiary) external;
/// @notice Deploys an ERC-20 token for a project.
/// @param projectId The ID of the project to deploy the ERC-20 for.
/// @param name The ERC-20's name.
/// @param symbol The ERC-20's symbol.
/// @param salt The salt used for deterministic ERC-1167 clone deployment.
/// @return token The address of the deployed token.
function deployERC20For(
uint256 projectId,
string calldata name,
string calldata symbol,
bytes32 salt
)
external
returns (IJBToken token);
/// @notice Creates a project, queues its initial rulesets, and sets up its terminals.
/// @param owner The project's owner. The project ERC-721 will be minted to this address.
/// @param projectUri The project's metadata URI.
/// @param rulesetConfigurations The rulesets to queue.
/// @param terminalConfigurations The terminals to set up for the project.
/// @param memo A memo to pass along to the emitted event.
/// @return projectId The project's ID.
function launchProjectFor(
address owner,
string calldata projectUri,
JBRulesetConfig[] calldata rulesetConfigurations,
JBTerminalConfig[] calldata terminalConfigurations,
string calldata memo
)
external
payable
returns (uint256 projectId);
/// @notice Queues a project's initial rulesets and sets up terminals for it.
/// @param projectId The ID of the project to launch rulesets for.
/// @param projectUri The project's metadata URI. Pass an empty string to leave it unchanged.
/// @param rulesetConfigurations The rulesets to queue.
/// @param terminalConfigurations The terminals to set up.
/// @param memo A memo to pass along to the emitted event.
/// @return rulesetId The ID of the last successfully queued ruleset.
function launchRulesetsFor(
uint256 projectId,
string calldata projectUri,
JBRulesetConfig[] calldata rulesetConfigurations,
JBTerminalConfig[] calldata terminalConfigurations,
string calldata memo
)
external
returns (uint256 rulesetId);
/// @notice Mints new project tokens (or credits) to a beneficiary, optionally reserving a portion for the ruleset's
/// reserved splits.
/// @param projectId The ID of the project whose project tokens are being minted.
/// @param tokenCount The total number of project tokens to mint, including reserved tokens if
/// `useReservedPercent` is true.
/// @param beneficiary The address that receives the non-reserved portion of the minted project tokens.
/// @param memo A memo to pass along to the emitted event.
/// @param useReservedPercent Whether to apply the ruleset's reserved percent.
/// @return beneficiaryTokenCount The number of project tokens minted to `beneficiary` (excluding the reserved
/// share).
function mintTokensOf(
uint256 projectId,
uint256 tokenCount,
address beneficiary,
string calldata memo,
bool useReservedPercent
)
external
returns (uint256 beneficiaryTokenCount);
/// @notice Queues one or more rulesets to the end of a project's ruleset queue.
/// @param projectId The ID of the project to queue rulesets for.
/// @param rulesetConfigurations The rulesets to queue.
/// @param memo A memo to pass along to the emitted event.
/// @return rulesetId The ID of the last successfully queued ruleset.
function queueRulesetsOf(
uint256 projectId,
JBRulesetConfig[] calldata rulesetConfigurations,
string calldata memo
)
external
returns (uint256 rulesetId);
/// @notice Sends a project's pending reserved tokens to its reserved token splits.
/// @param projectId The ID of the project to send reserved tokens for.
/// @return The amount of reserved tokens minted and sent.
function sendReservedTokensToSplitsOf(uint256 projectId) external returns (uint256);
/// @notice Sets a project's split groups.
/// @param projectId The ID of the project to set the split groups of.
/// @param rulesetId The ID of the ruleset the split groups should be active in.
/// @param splitGroups An array of split groups to set.
function setSplitGroupsOf(uint256 projectId, uint256 rulesetId, JBSplitGroup[] calldata splitGroups) external;
/// @notice Sets a project's token.
/// @param projectId The ID of the project to set the token of.
/// @param token The new token's address.
function setTokenFor(uint256 projectId, IJBToken token) external;
/// @notice Sets the name and symbol of a project's token.
/// @param projectId The ID of the project to update the token for.
/// @param name The new name.
/// @param symbol The new symbol.
function setTokenMetadataOf(uint256 projectId, string calldata name, string calldata symbol) external;
/// @notice Transfers credits from one address to another.
/// @param holder The address to transfer credits from.
/// @param projectId The ID of the project to transfer credits for.
/// @param recipient The address to transfer credits to.
/// @param creditCount The number of credits to transfer.
function transferCreditsFrom(address holder, uint256 projectId, address recipient, uint256 creditCount) external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBDirectory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IJBProjects} from "./IJBProjects.sol";
import {IJBTerminal} from "./IJBTerminal.sol";
/// @notice Interface for the protocol's routing table. Tracks which terminals accept payments for each project and
/// which controller manages each project's rulesets and tokens. Used by frontends and contracts to discover where to
/// send funds.
interface IJBDirectory {
/// @notice A terminal was added to a project.
/// @param projectId The ID of the project the terminal was added to.
/// @param terminal The terminal that was added.
/// @param caller The address that added the terminal.
event AddTerminal(uint256 indexed projectId, IJBTerminal indexed terminal, address caller);
/// @notice A project's controller was set.
/// @param projectId The ID of the project whose controller was set.
/// @param controller The controller that was set.
/// @param caller The address that set the controller.
event SetController(uint256 indexed projectId, IERC165 indexed controller, address caller);
/// @notice An address's permission to set a project's first controller was updated.
/// @param addr The address whose permission was updated.
/// @param isAllowed Whether the address is allowed to set a project's first controller.
/// @param caller The address that updated the permission.
event SetIsAllowedToSetFirstController(address indexed addr, bool indexed isAllowed, address caller);
/// @notice A project's primary terminal for a token was set.
/// @param projectId The ID of the project whose primary terminal was set.
/// @param token The token the primary terminal was set for.
/// @param terminal The terminal that was set as primary.
/// @param caller The address that set the primary terminal.
event SetPrimaryTerminal(
uint256 indexed projectId, address indexed token, IJBTerminal indexed terminal, address caller
);
/// @notice A project's terminals were set.
/// @param projectId The ID of the project whose terminals were set.
/// @param terminals The terminals that were set.
/// @param caller The address that set the terminals.
event SetTerminals(uint256 indexed projectId, IJBTerminal[] terminals, address caller);
/// @notice Mints ERC-721s that represent project ownership and transfers.
function PROJECTS() external view returns (IJBProjects);
/// @notice Returns the controller for a project.
/// @param projectId The ID of the project to get the controller of.
/// @return The project's controller.
function controllerOf(uint256 projectId) external view returns (IERC165);
/// @notice Returns whether an address is allowed to set a project's first controller on its behalf.
/// @param addr The address to check.
/// @return A flag indicating whether the address is allowed.
function isAllowedToSetFirstController(address addr) external view returns (bool);
/// @notice Returns whether a terminal is one of a project's terminals.
/// @param projectId The ID of the project to check.
/// @param terminal The terminal to check.
/// @return A flag indicating whether the terminal belongs to the project.
function isTerminalOf(uint256 projectId, IJBTerminal terminal) external view returns (bool);
/// @notice Returns the primary terminal for a project's token.
/// @param projectId The ID of the project to get the primary terminal of.
/// @param token The token to get the primary terminal for.
/// @return The primary terminal for the project's token.
function primaryTerminalOf(uint256 projectId, address token) external view returns (IJBTerminal);
/// @notice Returns a project's terminals.
/// @param projectId The ID of the project to get the terminals of.
/// @return The project's terminals.
function terminalsOf(uint256 projectId) external view returns (IJBTerminal[] memory);
/// @notice Sets a project's controller.
/// @param projectId The ID of the project to set the controller of.
/// @param controller The controller to set.
function setControllerOf(uint256 projectId, IERC165 controller) external;
/// @notice Sets whether an address is allowed to set a project's first controller on its behalf.
/// @param addr The address to set the permission for.
/// @param flag A flag indicating whether the address is allowed.
function setIsAllowedToSetFirstController(address addr, bool flag) external;
/// @notice Sets a project's primary terminal for a specific token.
/// @param projectId The ID of the project to set the primary terminal of.
/// @param token The token to set the primary terminal for.
/// @param terminal The terminal to set as primary.
function setPrimaryTerminalOf(uint256 projectId, address token, IJBTerminal terminal) external;
/// @notice Sets a project's terminals.
/// @param projectId The ID of the project to set the terminals of.
/// @param terminals The terminals to set.
function setTerminalsOf(uint256 projectId, IJBTerminal[] calldata terminals) external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBDirectoryAccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Provides the directory with access control checks for setting a project's controller and terminals.
interface IJBDirectoryAccessControl {
/// @notice Returns whether a project's controller can currently be set.
/// @param projectId The ID of the project to check.
/// @return A flag indicating whether setting the controller is allowed.
function setControllerAllowed(uint256 projectId) external view returns (bool);
/// @notice Returns whether a project's terminals can currently be set.
/// @param projectId The ID of the project to check.
/// @return A flag indicating whether setting the terminals is allowed.
function setTerminalsAllowed(uint256 projectId) external view returns (bool);
}
node_modules/@bananapus/core-v6/src/interfaces/IJBFundAccessLimits.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBCurrencyAmount} from "./../structs/JBCurrencyAmount.sol";
import {JBFundAccessLimitGroup} from "./../structs/JBFundAccessLimitGroup.sol";
/// @notice Stores fund access limits (payout limits and surplus allowances) for each project.
interface IJBFundAccessLimits {
/// @notice Fund access limits were set for a project's ruleset.
/// @param rulesetId The ID of the ruleset the limits apply within.
/// @param projectId The ID of the project the limits were set for.
/// @param fundAccessLimitGroup The fund access limit group that was set.
/// @param caller The address that set the fund access limits.
event SetFundAccessLimits(
uint256 indexed rulesetId,
uint256 indexed projectId,
JBFundAccessLimitGroup fundAccessLimitGroup,
address caller
);
/// @notice Returns the payout limit for a project, ruleset, terminal, token, and currency.
/// @param projectId The ID of the project to get the payout limit of.
/// @param rulesetId The ID of the ruleset the limit applies within.
/// @param terminal The terminal the limit applies to.
/// @param token The token the limit is denominated in.
/// @param currency The currency the limit is denominated in.
/// @return payoutLimit The payout limit.
function payoutLimitOf(
uint256 projectId,
uint256 rulesetId,
address terminal,
address token,
uint256 currency
)
external
view
returns (uint256 payoutLimit);
/// @notice Returns all payout limits for a project, ruleset, terminal, and token.
/// @param projectId The ID of the project to get the payout limits of.
/// @param rulesetId The ID of the ruleset the limits apply within.
/// @param terminal The terminal the limits apply to.
/// @param token The token the limits are denominated in.
/// @return payoutLimits The payout limits as an array of currency-amount pairs.
function payoutLimitsOf(
uint256 projectId,
uint256 rulesetId,
address terminal,
address token
)
external
view
returns (JBCurrencyAmount[] memory payoutLimits);
/// @notice Returns the surplus allowance for a project, ruleset, terminal, token, and currency.
/// @param projectId The ID of the project to get the surplus allowance of.
/// @param rulesetId The ID of the ruleset the allowance applies within.
/// @param terminal The terminal the allowance applies to.
/// @param token The token the allowance is denominated in.
/// @param currency The currency the allowance is denominated in.
/// @return surplusAllowance The surplus allowance.
function surplusAllowanceOf(
uint256 projectId,
uint256 rulesetId,
address terminal,
address token,
uint256 currency
)
external
view
returns (uint256 surplusAllowance);
/// @notice Returns all surplus allowances for a project, ruleset, terminal, and token.
/// @param projectId The ID of the project to get the surplus allowances of.
/// @param rulesetId The ID of the ruleset the allowances apply within.
/// @param terminal The terminal the allowances apply to.
/// @param token The token the allowances are denominated in.
/// @return surplusAllowances The surplus allowances as an array of currency-amount pairs.
function surplusAllowancesOf(
uint256 projectId,
uint256 rulesetId,
address terminal,
address token
)
external
view
returns (JBCurrencyAmount[] memory surplusAllowances);
/// @notice Sets the fund access limits for a project's ruleset.
/// @param projectId The ID of the project to set the fund access limits of.
/// @param rulesetId The ID of the ruleset the limits apply within.
/// @param fundAccessLimitGroups An array of payout limits and surplus allowances for each terminal.
function setFundAccessLimitsFor(
uint256 projectId,
uint256 rulesetId,
JBFundAccessLimitGroup[] calldata fundAccessLimitGroups
)
external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBPayHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {JBAfterPayRecordedContext} from "./../structs/JBAfterPayRecordedContext.sol";
/// @notice Hook called after a terminal's `pay(...)` logic completes (if passed by the ruleset's data hook).
interface IJBPayHook is IERC165 {
/// @notice Called by the terminal after a payment has been recorded in the terminal store.
/// @dev Critical business logic should be protected by appropriate access control.
/// @param context The context passed in by the terminal, as a `JBAfterPayRecordedContext` struct.
function afterPayRecordedWith(JBAfterPayRecordedContext calldata context) external payable;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBPayerTracker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Exposes the original payer of a forwarded payment.
/// @dev Implemented by intermediaries that forward value on behalf of a user — `JBProjects` (while forwarding a
/// project creation fee, where the original payer is reported as the new project's owner) and `JBProjectPayer`
/// (while relaying received funds to a project's terminal). A downstream forwarder or router terminal queries this
/// to resolve the payment beneficiary, refund partial-fill leftovers, and attribute credit cash-outs to the true
/// payer instead of the intermediary contract.
interface IJBPayerTracker {
/// @notice The original payer of the current forwarded payment.
/// @return payer The original payer address, or `address(0)` if no forwarding is in progress.
function originalPayer() external view returns (address payer);
}
node_modules/@bananapus/core-v6/src/interfaces/IJBPriceFeed.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice A price feed that returns a current unit price.
interface IJBPriceFeed {
/// @notice Gets the current price (per 1 unit) from the feed.
/// @param decimals The number of decimals the return value should use.
/// @return The current unit price from the feed, as a fixed point number with the specified number of decimals.
function currentUnitPrice(uint256 decimals) external view returns (uint256);
}
node_modules/@bananapus/core-v6/src/interfaces/IJBPrices.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBPriceFeed} from "./IJBPriceFeed.sol";
import {IJBProjects} from "./IJBProjects.sol";
/// @notice Resolves protocol currency conversions from append-only project and default price feeds.
interface IJBPrices {
/// @notice Emitted when a price feed is added for an exact currency pair.
/// @param projectId The ID of the project the price feed was added for. Project ID 0 stores protocol defaults.
/// @param pricingCurrency The currency that the feed's returned price is denominated in.
/// @param unitCurrency The currency whose unit is priced by the feed.
/// @param feed The price feed that was added.
/// @param caller The address that added the price feed.
event AddPriceFeed(
uint256 indexed projectId,
uint256 indexed pricingCurrency,
uint256 indexed unitCurrency,
IJBPriceFeed feed,
address caller
);
/// @notice The project ID used to store protocol default price feeds.
/// @return projectId The project ID used to store protocol defaults.
function DEFAULT_PROJECT_ID() external view returns (uint256 projectId);
/// @notice Mints ERC-721s that represent project ownership and transfers.
/// @return projects The project NFT contract.
function PROJECTS() external view returns (IJBProjects projects);
/// @notice Returns the feed stored at an exact pair's index.
/// @dev This view does not apply inverse or project-default fallback lookup. It reverts with Solidity's default
/// array bounds check if `index` is not configured.
/// @param projectId The ID of the project whose feed should be returned.
/// @param pricingCurrency The currency that the feed's returned price is denominated in.
/// @param unitCurrency The currency whose unit is priced by the feed.
/// @param index The index of the feed to return.
/// @return feed The configured price feed for the exact pair at `index`.
function priceFeedAt(
uint256 projectId,
uint256 pricingCurrency,
uint256 unitCurrency,
uint256 index
)
external
view
returns (IJBPriceFeed);
/// @notice Returns the number of feeds configured for an exact currency pair.
/// @dev This count does not include feeds configured for the inverse direction or project ID 0 defaults.
/// @param projectId The ID of the project whose feed count should be returned.
/// @param pricingCurrency The currency that the feeds' returned prices are denominated in.
/// @param unitCurrency The currency whose unit is priced by the feeds.
/// @return count The number of configured price feeds for the exact pair.
function priceFeedCountFor(
uint256 projectId,
uint256 pricingCurrency,
uint256 unitCurrency
)
external
view
returns (uint256 count);
/// @notice Returns the primary feed for an exact currency pair, or zero if none is configured.
/// @dev This view only returns the stored primary feed address. It does not call the feed, skip unavailable feeds,
/// derive inverse feeds, or fall back to project ID 0 defaults.
/// @param projectId The ID of the project whose primary feed should be returned.
/// @param pricingCurrency The currency that the feed's returned price is denominated in.
/// @param unitCurrency The currency whose unit is priced by the feed.
/// @return feed The first configured price feed for the exact pair, or the zero address if none exists.
function priceFeedFor(
uint256 projectId,
uint256 pricingCurrency,
uint256 unitCurrency
)
external
view
returns (IJBPriceFeed feed);
/// @notice Returns the price of one `unitCurrency` unit denominated in `pricingCurrency`.
/// @dev Lookup order is project direct feeds, project inverse feeds, default direct feeds, then default inverse
/// feeds. Each feed list is tried in registration order, skipping feeds that revert or return zero.
/// @param projectId The ID of the project to check first. Project ID 0 feeds are used as defaults.
/// @param pricingCurrency The currency that the returned price is denominated in.
/// @param unitCurrency The currency whose unit is being priced.
/// @param decimals The number of decimals the returned fixed point price should use.
/// @return price The `pricingCurrency` price of one `unitCurrency`, using `decimals` fixed point precision.
function pricePerUnitOf(
uint256 projectId,
uint256 pricingCurrency,
uint256 unitCurrency,
uint256 decimals
)
external
view
returns (uint256 price);
/// @notice Adds an append-only price feed for a project's exact currency pair.
/// @dev Project ID 0 stores protocol defaults and can only be configured by this contract's owner. Non-zero
/// project IDs can only be configured by that project's controller.
/// @param projectId The ID of the project to add the feed for, or 0 to add a protocol default.
/// @param pricingCurrency The currency that the feed's returned price is denominated in.
/// @param unitCurrency The currency whose unit is priced by the feed.
/// @param feed The price feed to add.
function addPriceFeedFor(
uint256 projectId,
uint256 pricingCurrency,
uint256 unitCurrency,
IJBPriceFeed feed
)
external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBProjectUriRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice A registry of metadata URIs for projects.
interface IJBProjectUriRegistry {
/// @notice Returns the metadata URI for a project.
/// @param projectId The ID of the project to get the metadata URI of.
/// @return The project's metadata URI.
function uriOf(uint256 projectId) external view returns (string memory);
/// @notice Sets the metadata URI for a project.
/// @param projectId The ID of the project to set the metadata URI of.
/// @param uri The metadata URI to set.
function setUriOf(uint256 projectId, string calldata uri) external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBProjects.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IJBTokenUriResolver} from "./IJBTokenUriResolver.sol";
/// @notice Mints ERC-721s that represent project ownership and transfers.
interface IJBProjects is IERC721 {
/// @notice A new project was created.
/// @param projectId The ID of the newly created project.
/// @param owner The address that owns the project.
/// @param caller The address that created the project.
event Create(uint256 indexed projectId, address indexed owner, address caller);
/// @notice The native-token fee required to create a project was set.
/// @param fee The required creation fee.
/// @param receiver The address that receives the fee.
/// @param caller The address that set the fee.
event SetCreationFee(uint256 fee, address payable receiver, address caller);
/// @notice The token URI resolver was set.
/// @param resolver The new token URI resolver.
/// @param caller The address that set the resolver.
event SetTokenUriResolver(IJBTokenUriResolver indexed resolver, address caller);
/// @notice Returns the maximum native-token fee the owner can require to create a project.
function MAX_CREATION_FEE() external view returns (uint256);
/// @notice Returns the native-token fee required to create a project.
function creationFee() external view returns (uint256);
/// @notice Returns the address that receives project creation fees.
function creationFeeReceiver() external view returns (address payable);
/// @notice Returns the total number of projects that have been created.
function count() external view returns (uint256);
/// @notice Returns the token URI resolver.
function tokenUriResolver() external view returns (IJBTokenUriResolver);
/// @notice Creates a new project and mints the project's ERC-721 to the specified owner.
/// @param owner The address that will own the new project's ERC-721.
/// @return projectId The ID of the newly created project.
function createFor(address owner) external payable returns (uint256 projectId);
/// @notice Sets the native-token fee required to create a project and the address that receives it.
/// @param fee The required creation fee. Set to 0 to disable creation fees. Must be `<= MAX_CREATION_FEE`.
/// @param receiver The address that receives creation fees. Must be non-zero when `fee` is non-zero.
function setCreationFee(uint256 fee, address payable receiver) external;
/// @notice Sets the token URI resolver used to retrieve project token URIs.
/// @param resolver The new token URI resolver.
function setTokenUriResolver(IJBTokenUriResolver resolver) external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBRulesetApprovalHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {JBApprovalStatus} from "./../enums/JBApprovalStatus.sol";
import {JBRuleset} from "./../structs/JBRuleset.sol";
/// @notice Determines whether the next ruleset in a project's queue is approved or rejected.
/// @dev Project rulesets are stored in a queue. Rulesets take effect after the previous ruleset in the queue ends, and
/// only if they are approved by the previous ruleset's approval hook.
/// `ApprovalExpected` is a provisional, non-blocking approval state: hooks should return it only when the ruleset will
/// become `Approved` if no later ruleset replaces it before final approval. Once a hook returns `Approved`, the ruleset
/// is final for its scheduled cycle and later queued rulesets must derive from it instead of replacing that cycle.
interface IJBRulesetApprovalHook is IERC165 {
/// @notice The minimum number of seconds that must pass for a queued ruleset to be considered approved.
function DURATION() external view returns (uint256);
/// @notice Returns the approval status of a given ruleset.
/// @param projectId The ID of the project the ruleset belongs to.
/// @param ruleset The ruleset to check the approval status of.
/// @return The ruleset's approval status.
function approvalStatusOf(uint256 projectId, JBRuleset memory ruleset) external view returns (JBApprovalStatus);
}
node_modules/@bananapus/core-v6/src/interfaces/IJBRulesetDataHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {JBBeforeCashOutRecordedContext} from "./../structs/JBBeforeCashOutRecordedContext.sol";
import {JBBeforePayRecordedContext} from "./../structs/JBBeforePayRecordedContext.sol";
import {JBCashOutHookSpecification} from "./../structs/JBCashOutHookSpecification.sol";
import {JBPayHookSpecification} from "./../structs/JBPayHookSpecification.sol";
import {JBRuleset} from "./../structs/JBRuleset.sol";
/// @notice Data hooks extend a terminal's pay/cash-out functionality by overriding the weight or memo, specifying
/// pay/cash-out hooks, or allowing addresses to mint a project's tokens on-demand.
/// @dev If a project's ruleset has `useDataHookForPay` or `useDataHookForCashOut` enabled, its `dataHook` is called by
/// the terminal upon payments/cash outs (respectively).
interface IJBRulesetDataHook is IERC165 {
/// @notice Calculates data before a cash out is recorded in the terminal store.
/// @param context The context passed to this data hook by the `cashOutTokensOf(...)` function.
/// @return cashOutTaxRate The rate determining the reclaimable amount for a given surplus and token supply.
/// @return effectiveCashOutCount The effective token count to use for pricing the cash out. The terminal still
/// burns the caller-supplied token count.
/// @return effectiveTotalSupply The effective total supply to use for both the proportional reclaim and tax
/// calculations. For omnichain projects, this should include tokens on other chains so the tax cannot be bypassed.
/// @return effectiveSurplusValue The surplus value to use for the bonding curve calculation, denominated in the
/// same token, decimals, and currency as `context.surplus`. The terminal caps the reclaim at locally available
/// funds.
/// @return hookSpecifications The amount and data to send to cash out hooks instead of returning to the
/// beneficiary.
function beforeCashOutRecordedWith(JBBeforeCashOutRecordedContext calldata context)
external
view
returns (
uint256 cashOutTaxRate,
uint256 effectiveCashOutCount,
uint256 effectiveTotalSupply,
uint256 effectiveSurplusValue,
JBCashOutHookSpecification[] memory hookSpecifications
);
/// @notice Calculates data before a payment is recorded in the terminal store.
/// @param context The context passed to this data hook by the `pay(...)` function.
/// @return weight The new weight to use, overriding the ruleset's weight.
/// @return hookSpecifications The amount and data to send to pay hooks instead of adding to the terminal's balance.
function beforePayRecordedWith(JBBeforePayRecordedContext calldata context)
external
view
returns (uint256 weight, JBPayHookSpecification[] memory hookSpecifications);
/// @notice Returns whether an address has permission to mint a project's tokens on-demand.
/// @param projectId The ID of the project whose token can be minted.
/// @param ruleset The ruleset to check the token minting permission of.
/// @param addr The address to check the token minting permission of.
/// @return flag A flag indicating whether the address has permission.
function hasMintPermissionFor(
uint256 projectId,
JBRuleset memory ruleset,
address addr
)
external
view
returns (bool flag);
}
node_modules/@bananapus/core-v6/src/interfaces/IJBRulesets.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBRulesetApprovalHook} from "./IJBRulesetApprovalHook.sol";
import {JBApprovalStatus} from "./../enums/JBApprovalStatus.sol";
import {JBRuleset} from "./../structs/JBRuleset.sol";
/// @notice Interface for the ruleset storage and lifecycle contract. Rulesets define a project's economic parameters
/// (weight, duration, cash-out rate, etc.) and are queued as a linked list with approval hooks gating transitions.
interface IJBRulesets {
/// @notice A ruleset was initialized from a base ruleset.
/// @param rulesetId The ID of the initialized ruleset.
/// @param projectId The ID of the project the ruleset belongs to.
/// @param basedOnId The ID of the base ruleset the new ruleset was derived from.
/// @param caller The address that initialized the ruleset.
event RulesetInitialized(
uint256 indexed rulesetId, uint256 indexed projectId, uint256 indexed basedOnId, address caller
);
/// @notice A ruleset was queued for a project.
/// @param rulesetId The ID of the queued ruleset.
/// @param projectId The ID of the project the ruleset was queued for.
/// @param duration The duration of the ruleset in seconds.
/// @param weight The weight of the ruleset.
/// @param weightCutPercent The percent by which the weight decreases each cycle, out of
/// `JBConstants.MAX_WEIGHT_CUT_PERCENT`.
/// @param approvalHook The approval hook for the ruleset.
/// @param metadata The packed ruleset metadata.
/// @param mustStartAtOrAfter The earliest time the ruleset can start.
/// @param caller The address that queued the ruleset.
event RulesetQueued(
uint256 indexed rulesetId,
uint256 indexed projectId,
uint256 duration,
uint256 weight,
uint256 weightCutPercent,
IJBRulesetApprovalHook approvalHook,
uint256 metadata,
uint256 mustStartAtOrAfter,
address caller
);
/// @notice A ruleset's weight cache was updated.
/// @param projectId The ID of the project whose weight cache was updated.
/// @param weight The cached weight value.
/// @param weightCutMultiple The weight cut multiple used for caching.
/// @param caller The address that updated the weight cache.
event WeightCacheUpdated(uint256 projectId, uint112 weight, uint256 weightCutMultiple, address caller);
/// @notice Returns an array of rulesets for a project, sorted from latest to earliest.
/// @param projectId The ID of the project to get rulesets of.
/// @param startingId The ID of the ruleset to begin with. If 0, the latest ruleset is used.
/// @param size The maximum number of rulesets to return.
/// @return rulesets The array of rulesets.
function allOf(
uint256 projectId,
uint256 startingId,
uint256 size
)
external
view
returns (JBRuleset[] memory rulesets);
/// @notice Returns the approval status of the latest queued ruleset relative to the current ruleset.
/// @param projectId The ID of the project to check.
/// @return The approval status of the latest queued ruleset.
function currentApprovalStatusForLatestRulesetOf(uint256 projectId) external view returns (JBApprovalStatus);
/// @notice Returns the current ruleset for a project, deriving its properties from the base ruleset.
/// @param projectId The ID of the project to get the current ruleset of.
/// @return ruleset The current ruleset.
function currentOf(uint256 projectId) external view returns (JBRuleset memory ruleset);
/// @notice Derives the start time from the base ruleset's parameters.
/// @param baseRulesetStart The start time of the base ruleset.
/// @param baseRulesetDuration The duration of the base ruleset.
/// @param mustStartAtOrAfter The earliest time the derived ruleset can start.
/// @return start The derived start time.
function deriveStartFrom(
uint256 baseRulesetStart,
uint256 baseRulesetDuration,
uint256 mustStartAtOrAfter
)
external
view
returns (uint256 start);
/// @notice Derives the weight from the base ruleset's parameters, accounting for weight cuts over elapsed cycles.
/// @param projectId The ID of the project.
/// @param baseRulesetStart The start time of the base ruleset.
/// @param baseRulesetDuration The duration of the base ruleset.
/// @param baseRulesetWeight The weight of the base ruleset.
/// @param baseRulesetWeightCutPercent The weight cut percent of the base ruleset, out of
/// `JBConstants.MAX_WEIGHT_CUT_PERCENT`.
/// @param baseRulesetCacheId The cache ID of the base ruleset.
/// @param start The start time to derive the weight for.
/// @return weight The derived weight.
function deriveWeightFrom(
uint256 projectId,
uint256 baseRulesetStart,
uint256 baseRulesetDuration,
uint256 baseRulesetWeight,
uint256 baseRulesetWeightCutPercent,
uint256 baseRulesetCacheId,
uint256 start
)
external
view
returns (uint256 weight);
/// @notice Returns a specific ruleset for a project by its ID.
/// @param projectId The ID of the project the ruleset belongs to.
/// @param rulesetId The ID of the ruleset to retrieve.
/// @return The ruleset.
function getRulesetOf(uint256 projectId, uint256 rulesetId) external view returns (JBRuleset memory);
/// @notice Returns the latest queued ruleset for a project and its approval status.
/// @param projectId The ID of the project to get the latest queued ruleset of.
/// @return ruleset The latest queued ruleset.
/// @return approvalStatus The ruleset's approval status.
function latestQueuedOf(uint256 projectId)
external
view
returns (JBRuleset memory ruleset, JBApprovalStatus approvalStatus);
/// @notice Returns the ID of the latest ruleset queued for a project.
/// @param projectId The ID of the project to get the latest ruleset ID of.
/// @return The latest ruleset ID.
function latestRulesetIdOf(uint256 projectId) external view returns (uint256);
/// @notice Returns the upcoming ruleset for a project.
/// @param projectId The ID of the project to get the upcoming ruleset of.
/// @return ruleset The upcoming ruleset.
function upcomingOf(uint256 projectId) external view returns (JBRuleset memory ruleset);
/// @notice Derives the cycle number from the base ruleset's parameters and a given start time.
/// @param baseRulesetCycleNumber The cycle number of the base ruleset.
/// @param baseRulesetStart The start time of the base ruleset.
/// @param baseRulesetDuration The duration of the base ruleset.
/// @param start The start time to derive the cycle number for.
/// @return The derived cycle number.
function deriveCycleNumberFrom(
uint256 baseRulesetCycleNumber,
uint256 baseRulesetStart,
uint256 baseRulesetDuration,
uint256 start
)
external
returns (uint256);
/// @notice Queues a new ruleset for a project.
/// @dev A latest queued ruleset with `ApprovalExpected` can still be replaced within its scheduled cycle, but can
/// be used as the base for a later cycle because it is expected to become `Approved` unless replaced. A latest
/// queued ruleset with `Approved` is final for its scheduled cycle; later queued rulesets derive from it.
/// @param projectId The ID of the project to queue the ruleset for.
/// @param duration The duration of the ruleset in seconds.
/// @param weight The weight of the ruleset.
/// @param weightCutPercent The percent by which the weight decreases each cycle, out of
/// `JBConstants.MAX_WEIGHT_CUT_PERCENT`.
/// @param approvalHook The approval hook for the ruleset.
/// @param metadata The packed ruleset metadata.
/// @param mustStartAtOrAfter The earliest time the ruleset can start.
/// @return ruleset The queued ruleset.
function queueFor(
uint256 projectId,
uint256 duration,
uint256 weight,
uint256 weightCutPercent,
IJBRulesetApprovalHook approvalHook,
uint256 metadata,
uint256 mustStartAtOrAfter
)
external
returns (JBRuleset memory ruleset);
/// @notice Updates the weight cache for a specific ruleset to allow efficient weight derivation over many cycles.
/// @param projectId The ID of the project to update the weight cache for.
/// @param rulesetId The ID of the ruleset to update the cache for. This should be the ruleset that currentOf()
/// actually uses, which may differ from latestRulesetIdOf if the latest was rejected by an approval hook.
function updateRulesetWeightCache(uint256 projectId, uint256 rulesetId) external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBSplitHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {JBSplitHookContext} from "../structs/JBSplitHookContext.sol";
/// @notice Allows processing a single split with custom logic.
/// @dev The split hook's address should be set as the `hook` in the relevant split.
interface IJBSplitHook is IERC165 {
/// @notice Called by terminals and controllers while processing a split.
/// @dev Critical business logic should be protected by appropriate access control. The tokens and/or native tokens
/// are optimistically transferred to the split hook when this function is called.
/// @param context The context passed by the terminal/controller to the split hook.
function processSplitWith(JBSplitHookContext calldata context) external payable;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBSplits.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBSplit} from "./../structs/JBSplit.sol";
import {JBSplitGroup} from "./../structs/JBSplitGroup.sol";
/// @notice Interface for the split storage contract. Splits define how payouts and reserved tokens are distributed —
/// each split specifies a recipient and their percentage share. Splits can be locked until a timestamp.
interface IJBSplits {
/// @notice A split was set for a project.
/// @param projectId The ID of the project the split was set for.
/// @param rulesetId The ID of the ruleset the split is active in.
/// @param groupId The ID of the split group.
/// @param split The split that was set.
/// @param caller The address that set the split.
event SetSplit(
uint256 indexed projectId, uint256 indexed rulesetId, uint256 indexed groupId, JBSplit split, address caller
);
/// @notice The ruleset ID used as a fallback when no splits are set for a specific ruleset.
function FALLBACK_RULESET_ID() external view returns (uint256);
/// @notice Returns the splits for a project, ruleset, and group.
/// @param projectId The ID of the project to get the splits of.
/// @param rulesetId The ID of the ruleset the splits should be active in.
/// @param groupId The ID of the group to get the splits of.
/// @return The splits.
function splitsOf(uint256 projectId, uint256 rulesetId, uint256 groupId) external view returns (JBSplit[] memory);
/// @notice Sets a project's split groups.
/// @param projectId The ID of the project to set the split groups of.
/// @param rulesetId The ID of the ruleset the split groups should be active in.
/// @param splitGroups An array of split groups to set.
function setSplitGroupsOf(uint256 projectId, uint256 rulesetId, JBSplitGroup[] calldata splitGroups) external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBTerminal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IJBPayHook} from "./IJBPayHook.sol";
import {JBAccountingContext} from "../structs/JBAccountingContext.sol";
import {JBAfterPayRecordedContext} from "../structs/JBAfterPayRecordedContext.sol";
import {JBPayHookSpecification} from "../structs/JBPayHookSpecification.sol";
import {JBRuleset} from "../structs/JBRuleset.sol";
/// @notice Base interface for all Juicebox terminals. A terminal accepts payments for projects, reports surplus, and
/// supports balance migration. Projects register their terminals in `JBDirectory`; the primary terminal for a token
/// receives payments routed by frontends.
interface IJBTerminal is IERC165 {
/// @notice Funds were added to a project's balance.
/// @param projectId The ID of the project that received the funds.
/// @param amount The amount of tokens added.
/// @param returnedFees The amount of fees returned.
/// @param memo A memo associated with the addition.
/// @param metadata Extra metadata associated with the addition.
/// @param caller The address that added the funds.
event AddToBalance(
uint256 indexed projectId, uint256 amount, uint256 returnedFees, string memo, bytes metadata, address caller
);
/// @notice A pay hook was called after a payment was recorded.
/// @param hook The pay hook that was called.
/// @param context The context passed to the hook.
/// @param specificationAmount The amount specified for the hook.
/// @param caller The address that called the pay function.
event HookAfterRecordPay(
IJBPayHook indexed hook, JBAfterPayRecordedContext context, uint256 specificationAmount, address caller
);
/// @notice A project's balance was migrated to another terminal.
/// @param projectId The ID of the project that was migrated.
/// @param token The token that was migrated.
/// @param to The terminal the balance was migrated to.
/// @param amount The amount of tokens migrated.
/// @param caller The address that called the migrate function.
event MigrateTerminal(
uint256 indexed projectId, address indexed token, IJBTerminal indexed to, uint256 amount, address caller
);
/// @notice A payment was made to a project.
/// @param rulesetId The ID of the ruleset during the payment.
/// @param rulesetCycleNumber The cycle number of the ruleset during the payment.
/// @param projectId The ID of the project that received the payment.
/// @param payer The address that made the payment.
/// @param beneficiary The address that received the project tokens.
/// @param amount The amount of tokens paid.
/// @param newlyIssuedTokenCount The number of project tokens minted.
/// @param memo A memo associated with the payment.
/// @param metadata Extra metadata associated with the payment.
/// @param caller The address that called the pay function.
event Pay(
uint256 indexed rulesetId,
uint256 indexed rulesetCycleNumber,
uint256 indexed projectId,
address payer,
address beneficiary,
uint256 amount,
uint256 newlyIssuedTokenCount,
string memo,
bytes metadata,
address caller
);
/// @notice An accounting context was set for a project's token.
/// @param projectId The ID of the project the accounting context was set for.
/// @param context The accounting context that was set.
/// @param caller The address that set the accounting context.
event SetAccountingContext(uint256 indexed projectId, JBAccountingContext context, address caller);
/// @notice Returns the accounting context for a project's token.
/// @param projectId The ID of the project to get the accounting context of.
/// @param token The token to get the accounting context for.
/// @return The accounting context for the project's token.
function accountingContextForTokenOf(
uint256 projectId,
address token
)
external
view
returns (JBAccountingContext memory);
/// @notice Returns all accounting contexts for a project.
/// @param projectId The ID of the project to get the accounting contexts of.
/// @return The accounting contexts for the project.
function accountingContextsOf(uint256 projectId) external view returns (JBAccountingContext[] memory);
/// @notice Returns a project's current surplus in this terminal.
/// @param projectId The ID of the project to get the surplus of.
/// @param tokens The tokens to include in the surplus calculation. If empty, all tokens are included.
/// @param decimals The number of decimals to express the surplus with.
/// @param currency The currency to express the surplus in.
/// @return The project's current surplus for the given tokens.
function currentSurplusOf(
uint256 projectId,
address[] calldata tokens,
uint256 decimals,
uint256 currency
)
external
view
returns (uint256);
/// @notice Simulates paying a project through this terminal without modifying state.
/// @param projectId The ID of the project to pay.
/// @param token The token to pay with.
/// @param amount The amount of tokens to pay.
/// @param beneficiary The address to mint project tokens to.
/// @param metadata Extra data to pass along to the data hook and pay hooks.
/// @return ruleset The project's current ruleset.
/// @return beneficiaryTokenCount The number of project tokens that would be minted for the beneficiary.
/// @return reservedTokenCount The number of project tokens that would be reserved.
/// @return hookSpecifications Any pay hook specifications from the data hook.
function previewPayFor(
uint256 projectId,
address token,
uint256 amount,
address beneficiary,
bytes calldata metadata
)
external
view
returns (
JBRuleset memory ruleset,
uint256 beneficiaryTokenCount,
uint256 reservedTokenCount,
JBPayHookSpecification[] memory hookSpecifications
);
/// @notice Adds accounting contexts for a project's tokens.
/// @param projectId The ID of the project to add accounting contexts for.
/// @param accountingContexts The accounting contexts to add.
function addAccountingContextsFor(uint256 projectId, JBAccountingContext[] calldata accountingContexts) external;
/// @notice Adds terminal tokens to a project's balance (no project tokens are minted).
/// @param projectId The ID of the project to add funds to.
/// @param token The terminal token being added.
/// @param amount The amount of terminal `token` being added.
/// @param shouldReturnHeldFees Whether held fees should be returned based on the amount added.
/// @param memo A memo to pass along to the emitted event.
/// @param metadata Extra data to pass along to the emitted event.
function addToBalanceOf(
uint256 projectId,
address token,
uint256 amount,
bool shouldReturnHeldFees,
string calldata memo,
bytes calldata metadata
)
external
payable;
/// @notice Migrates a project's funds from this terminal to another.
/// @param projectId The ID of the project to migrate.
/// @param token The address of the token to migrate.
/// @param to The terminal to migrate to.
/// @return balance The amount of funds that were migrated.
function migrateBalanceOf(uint256 projectId, address token, IJBTerminal to) external returns (uint256 balance);
/// @notice Pay a project with a payment token in exchange for project tokens minted to a beneficiary.
/// @param projectId The ID of the project to pay.
/// @param token The payment token to pay with.
/// @param amount The amount of the payment `token` to pay.
/// @param beneficiary The address to mint project tokens to.
/// @param minReturnedTokens The minimum number of project tokens the beneficiary must receive.
/// @param memo A memo to pass along to the emitted event.
/// @param metadata Extra data to pass along to the pay hooks.
/// @return beneficiaryTokenCount The number of project tokens minted to the beneficiary.
function pay(
uint256 projectId,
address token,
uint256 amount,
address beneficiary,
uint256 minReturnedTokens,
string calldata memo,
bytes calldata metadata
)
external
payable
returns (uint256 beneficiaryTokenCount);
}
node_modules/@bananapus/core-v6/src/interfaces/IJBToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice A token that can be used by a project in the Juicebox ecosystem.
interface IJBToken {
/// @notice Returns the balance of an account.
/// @param account The account to get the balance of.
/// @return The number of tokens owned by the account.
function balanceOf(address account) external view returns (uint256);
/// @notice Returns whether this token can be added to a given project.
/// @param projectId The ID of the project to check.
/// @return A flag indicating whether the token can be added.
function canBeAddedTo(uint256 projectId) external view returns (bool);
/// @notice Returns the number of decimals used by the token.
/// @return The number of decimals.
function decimals() external view returns (uint8);
/// @notice Returns the total supply of the token.
/// @return The total supply.
function totalSupply() external view returns (uint256);
/// @notice Burns tokens from an account.
/// @param account The address to burn tokens from.
/// @param amount The amount of tokens to burn.
function burn(address account, uint256 amount) external;
/// @notice Initializes the token with a name, symbol, and the JBTokens contract.
/// @param name The token's name.
/// @param symbol The token's symbol.
/// @param tokensAddress The JBTokens contract that manages this token.
function initialize(string memory name, string memory symbol, address tokensAddress) external;
/// @notice Mints tokens to an account.
/// @param account The address to mint tokens to.
/// @param amount The amount of tokens to mint.
function mint(address account, uint256 amount) external;
/// @notice Sets the token's name and symbol.
/// @param name The new name.
/// @param symbol The new symbol.
function setMetadata(string memory name, string memory symbol) external;
}
node_modules/@bananapus/core-v6/src/interfaces/IJBTokenUriResolver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Resolves token URIs for project NFTs.
interface IJBTokenUriResolver {
/// @notice Returns the token URI for a project.
/// @param projectId The ID of the project to get the token URI of.
/// @return tokenUri The token URI.
function getUri(uint256 projectId) external view returns (string memory tokenUri);
}
node_modules/@bananapus/core-v6/src/interfaces/IJBTokens.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBToken} from "./IJBToken.sol";
/// @notice Interface for the dual-token system. Manages credits (internal balances) and ERC-20 tokens for every
/// project. Credits are minted first and can later be claimed as transferable ERC-20 tokens.
interface IJBTokens {
/// @notice Tokens or credits were burned from a holder's balance.
/// @param holder The address whose tokens were burned.
/// @param projectId The ID of the project whose tokens were burned.
/// @param count The number of tokens burned.
/// @param creditBalance The holder's remaining credit balance after the burn.
/// @param tokenBalance The holder's remaining token balance after the burn.
/// @param caller The address that called the burn function.
event Burn(
address indexed holder,
uint256 indexed projectId,
uint256 count,
uint256 creditBalance,
uint256 tokenBalance,
address caller
);
/// @notice Credits were claimed as ERC-20 tokens.
/// @param holder The address whose credits were claimed.
/// @param projectId The ID of the project whose tokens were claimed.
/// @param creditBalance The holder's remaining credit balance after the claim.
/// @param count The number of tokens claimed.
/// @param beneficiary The address that received the claimed tokens.
/// @param caller The address that called the claim function.
event ClaimTokens(
address indexed holder,
uint256 indexed projectId,
uint256 creditBalance,
uint256 count,
address beneficiary,
address caller
);
/// @notice An ERC-20 token was deployed for a project.
/// @param projectId The ID of the project the token was deployed for.
/// @param token The deployed token.
/// @param name The token's name.
/// @param symbol The token's symbol.
/// @param salt The salt used for deterministic deployment.
/// @param caller The address that deployed the token.
event DeployERC20(
uint256 indexed projectId, IJBToken indexed token, string name, string symbol, bytes32 salt, address caller
);
/// @notice Tokens or credits were minted for a holder.
/// @param holder The address that received the minted tokens.
/// @param projectId The ID of the project whose tokens were minted.
/// @param count The number of tokens minted.
/// @param tokensWereClaimed Whether the tokens were claimed as ERC-20 tokens.
/// @param caller The address that called the mint function.
event Mint(
address indexed holder, uint256 indexed projectId, uint256 count, bool tokensWereClaimed, address caller
);
/// @notice A project's token was set.
/// @param projectId The ID of the project whose token was set.
/// @param token The token that was set.
/// @param caller The address that set the token.
event SetToken(uint256 indexed projectId, IJBToken indexed token, address caller);
/// @notice A project token's name and symbol were updated.
/// @param projectId The ID of the project whose token was updated.
/// @param name The new token name.
/// @param symbol The new token symbol.
/// @param caller The address that called the function.
event SetTokenMetadata(uint256 indexed projectId, string name, string symbol, address caller);
/// @notice Credits were transferred from one holder to another.
/// @param holder The address that transferred the credits.
/// @param projectId The ID of the project whose credits were transferred.
/// @param recipient The address that received the credits.
/// @param count The number of credits transferred.
/// @param caller The address that called the transfer function.
event TransferCredits(
address indexed holder, uint256 indexed projectId, address indexed recipient, uint256 count, address caller
);
/// @notice Returns the credit balance for a holder and project.
/// @param holder The address to get the credit balance of.
/// @param projectId The ID of the project to get the credit balance for.
/// @return The credit balance.
function creditBalanceOf(address holder, uint256 projectId) external view returns (uint256);
/// @notice The project ID that a given ERC-20 token contract is associated with.
/// @param token The token to get the project ID of.
/// @return The project ID.
function projectIdOf(IJBToken token) external view returns (uint256);
/// @notice Returns the token for a project.
/// @param projectId The ID of the project to get the token of.
/// @return The project's token.
function tokenOf(uint256 projectId) external view returns (IJBToken);
/// @notice Returns the total balance (tokens + credits) for a holder and project.
/// @param holder The address to get the total balance of.
/// @param projectId The ID of the project to get the total balance for.
/// @return balance The combined token and credit balance.
function totalBalanceOf(address holder, uint256 projectId) external view returns (uint256 balance);
/// @notice Returns the total credit supply for a project.
/// @param projectId The ID of the project to get the total credit supply of.
/// @return The total credit supply.
function totalCreditSupplyOf(uint256 projectId) external view returns (uint256);
/// @notice Returns the total supply (tokens + credits) for a project.
/// @param projectId The ID of the project to get the total supply of.
/// @return The total supply.
function totalSupplyOf(uint256 projectId) external view returns (uint256);
/// @notice Burns tokens and/or credits from a holder's balance.
/// @param holder The address to burn tokens from.
/// @param projectId The ID of the project to burn tokens for.
/// @param count The number of tokens to burn.
function burnFrom(address holder, uint256 projectId, uint256 count) external;
/// @notice Claims tokens from a holder's credits into a beneficiary's account.
/// @param holder The address to claim credits from.
/// @param projectId The ID of the project to claim tokens for.
/// @param count The number of tokens to claim.
/// @param beneficiary The address to send the claimed tokens to.
function claimTokensFor(address holder, uint256 projectId, uint256 count, address beneficiary) external;
/// @notice Deploys an ERC-20 token for a project.
/// @param projectId The ID of the project to deploy the ERC-20 for.
/// @param name The ERC-20's name.
/// @param symbol The ERC-20's symbol.
/// @param salt The salt used for deterministic clone deployment.
/// @return token The deployed token.
function deployERC20For(
uint256 projectId,
string calldata name,
string calldata symbol,
bytes32 salt
)
external
returns (IJBToken token);
/// @notice Mints tokens or credits for a holder.
/// @param holder The address to mint tokens for.
/// @param projectId The ID of the project to mint tokens for.
/// @param count The number of tokens to mint.
/// @return token The project's token, if one exists.
function mintFor(address holder, uint256 projectId, uint256 count) external returns (IJBToken token);
/// @notice Sets a project's token.
/// @param projectId The ID of the project to set the token of.
/// @param token The token to set.
function setTokenFor(uint256 projectId, IJBToken token) external;
/// @notice Sets the name and symbol of a project's token.
/// @param projectId The ID of the project to update the token for.
/// @param name The new name.
/// @param symbol The new symbol.
function setTokenMetadataFor(uint256 projectId, string calldata name, string calldata symbol) external;
/// @notice Transfers credits from one holder to another.
/// @param holder The address to transfer credits from.
/// @param projectId The ID of the project to transfer credits for.
/// @param recipient The address to transfer credits to.
/// @param count The number of credits to transfer.
function transferCreditsFrom(address holder, uint256 projectId, address recipient, uint256 count) external;
}
node_modules/@bananapus/core-v6/src/structs/JBAccountingContext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Describes how a terminal accounts for a specific token — its address, decimal precision, and the currency
/// it's priced in. Used when recording payments, payouts, and cash outs to ensure correct fixed-point arithmetic.
/// @custom:member token The token address (use `JBConstants.NATIVE_TOKEN` for ETH).
/// @custom:member decimals The number of decimals for this token's fixed-point amounts (e.g. 18 for ETH, 6 for USDC).
/// @custom:member currency The currency ID for price feed lookups. Convention: `uint32(uint160(tokenAddress))` for
/// tokens, or `JBCurrencyIds.ETH`/`JBCurrencyIds.USD` for well-known currencies.
struct JBAccountingContext {
address token;
uint8 decimals;
uint32 currency;
}
node_modules/@bananapus/core-v6/src/structs/JBAfterCashOutRecordedContext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from "./JBTokenAmount.sol";
/// @custom:member holder The holder of the tokens to cash out.
/// @custom:member projectId The ID of the project to cash out from.
/// @custom:member rulesetId The ID of the ruleset the cash out is made during.
/// @custom:member cashOutCount The number of project tokens to cash out.
/// @custom:member cashOutTaxRate The current ruleset's cash out tax rate, out of
/// `JBConstants.MAX_CASH_OUT_TAX_RATE`.
/// @custom:member reclaimedAmount The token amount reclaimed from the project's terminal balance. Includes the token
/// reclaimed, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The token amount forwarded to the cash out hook. Includes the token
/// forwarded, the value, the number of decimals included, and the currency of the amount.
/// @custom:member beneficiary The address the reclaimed amount will be sent to.
/// @custom:member hookMetadata Extra data specified by the data hook, which is sent to the cash out hook.
/// @custom:member cashOutMetadata Extra data specified by the account cashing out, which is sent to the cash out hook.
struct JBAfterCashOutRecordedContext {
address holder;
uint256 projectId;
uint256 rulesetId;
uint256 cashOutCount;
JBTokenAmount reclaimedAmount;
JBTokenAmount forwardedAmount;
uint256 cashOutTaxRate;
address payable beneficiary;
bytes hookMetadata;
bytes cashOutMetadata;
}
node_modules/@bananapus/core-v6/src/structs/JBAfterPayRecordedContext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from "./JBTokenAmount.sol";
/// @custom:member payer The address the payment originated from.
/// @custom:member projectId The ID of the project to pay.
/// @custom:member rulesetId The ID of the ruleset the payment is made during.
/// @custom:member amount The payment's token amount. Includes the token paid, the value, the number of decimals
/// included, and the currency of the amount.
/// @custom:member forwardedAmount The token amount forwarded to the pay hook. Includes the token
/// paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member weight The current ruleset's weight (used to determine how many tokens should be minted).
/// @custom:member newlyIssuedTokenCount The number of project tokens minted for the beneficiary.
/// @custom:member beneficiary The address which receives any tokens this payment yields.
/// @custom:member hookMetadata Extra data specified by the data hook, which is sent to the pay hook.
/// @custom:member payerMetadata Extra data specified by the payer, which is sent to the pay hook.
struct JBAfterPayRecordedContext {
address payer;
uint256 projectId;
uint256 rulesetId;
JBTokenAmount amount;
JBTokenAmount forwardedAmount;
uint256 weight;
uint256 newlyIssuedTokenCount;
address beneficiary;
bytes hookMetadata;
bytes payerMetadata;
}
node_modules/@bananapus/core-v6/src/structs/JBBeforeCashOutRecordedContext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from "./JBTokenAmount.sol";
/// @notice Context sent from the terminal to the ruleset's data hook upon cash out.
/// @custom:member terminal The terminal that is facilitating the cash out.
/// @custom:member holder The holder of the tokens to cash out.
/// @custom:member projectId The ID of the project cashing out tokens.
/// @custom:member rulesetId The ID of the ruleset the cash out is made during.
/// @custom:member cashOutCount The number of tokens to cash out, as a fixed point number with 18 decimals.
/// @custom:member totalSupply The total token supply to use for the calculation, as a fixed point number with 18
/// decimals.
/// @custom:member surplus The surplus amount used for the calculation, as a fixed point number with 18 decimals.
/// Includes the token of the surplus, the surplus value, the number of decimals
/// included, and the currency of the surplus.
/// @custom:member scopeCashOutsToLocalBalances If true, omnichain hooks should use only local chain balances for cash
/// outs (skip cross-chain aggregation).
/// @custom:member cashOutTaxRate The cash out tax rate of the ruleset the cash out is made during, out of
/// `JBConstants.MAX_CASH_OUT_TAX_RATE`.
/// @custom:member beneficiaryIsFeeless Whether the cash out's beneficiary is a feeless address. Useful for data hooks
/// that charge their own fees — they can skip fees when value stays in the protocol (e.g. project-to-project
/// routing).
/// @custom:member metadata Extra data provided by the casher.
struct JBBeforeCashOutRecordedContext {
address terminal;
address holder;
uint256 projectId;
uint256 rulesetId;
uint256 cashOutCount;
uint256 totalSupply;
JBTokenAmount surplus;
bool scopeCashOutsToLocalBalances;
uint256 cashOutTaxRate;
bool beneficiaryIsFeeless;
bytes metadata;
}
node_modules/@bananapus/core-v6/src/structs/JBBeforePayRecordedContext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBTokenAmount} from "./JBTokenAmount.sol";
/// @notice Context sent from the terminal to the ruleset's data hook upon payment.
/// @custom:member terminal The terminal that is facilitating the payment.
/// @custom:member payer The address that the payment originated from.
/// @custom:member amount The payment's token amount, including the token paid, the value, the number of decimals
/// included, and the currency of the amount.
/// @custom:member projectId The ID of the project to pay.
/// @custom:member rulesetId The ID of the ruleset the payment is made during.
/// @custom:member beneficiary The specified address that should be the beneficiary of anything that this payment
/// yields.
/// @custom:member weight The weight of the ruleset during which the payment is made.
/// @custom:member reservedPercent The reserved percent of the ruleset the payment is made during, out of
/// `JBConstants.MAX_RESERVED_PERCENT`.
/// @custom:member metadata Extra data specified by the payer.
struct JBBeforePayRecordedContext {
address terminal;
address payer;
JBTokenAmount amount;
uint256 projectId;
uint256 rulesetId;
address beneficiary;
uint256 weight;
uint256 reservedPercent;
bytes metadata;
}
node_modules/@bananapus/core-v6/src/structs/JBCashOutHookSpecification.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBCashOutHook} from "../interfaces/IJBCashOutHook.sol";
/// @notice A cash out hook specification sent from the ruleset's data hook back to the terminal for fulfillment.
/// @custom:member hook The cash out hook to use when fulfilling this specification.
/// @custom:member noop A flag indicating if the hook callback should be skipped.
/// @custom:member amount The amount to send to the hook.
/// @custom:member metadata Metadata to pass to the hook.
struct JBCashOutHookSpecification {
IJBCashOutHook hook;
bool noop;
uint256 amount;
bytes metadata;
}
node_modules/@bananapus/core-v6/src/structs/JBCurrencyAmount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @custom:member amount The amount of the currency.
/// @custom:member currency The currency. By convention, this is `uint32(uint160(tokenAddress))` for tokens, or a
/// constant ID from e.g. `JBCurrencyIds` for other currencies.
struct JBCurrencyAmount {
uint224 amount;
uint32 currency;
}
node_modules/@bananapus/core-v6/src/structs/JBFundAccessLimitGroup.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBCurrencyAmount} from "./JBCurrencyAmount.sol";
/// @notice Defines how much a project can withdraw from a specific terminal and token during a ruleset.
/// @dev A ruleset configuration should include at most one group for each `(terminal, token)` pair.
/// @dev Example — payout limit of 5 USD in an ETH terminal: the project can distribute up to 5 USD worth of ETH to
/// its splits per ruleset cycle. Example — surplus allowance of 5 USD: the project owner can pull up to 5 USD
/// worth of ETH from the surplus (balance above payout limits) during the ruleset.
/// @dev Multiple limits in different currencies are additive within their respective reset windows.
/// @dev Amounts use the same decimal precision as the terminal token (e.g. 18 for ETH, 6 for USDC).
/// @custom:member terminal The terminal address these limits apply to.
/// @custom:member token The token address within that terminal these limits apply to.
/// @custom:member payoutLimits Maximum amounts distributable to splits per ruleset cycle, each in a specific currency.
/// @custom:member surplusAllowances Maximum amounts withdrawable from surplus per ruleset, each in a specific currency.
struct JBFundAccessLimitGroup {
address terminal;
address token;
JBCurrencyAmount[] payoutLimits;
JBCurrencyAmount[] surplusAllowances;
}
node_modules/@bananapus/core-v6/src/structs/JBPayHookSpecification.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBPayHook} from "../interfaces/IJBPayHook.sol";
/// @notice A pay hook specification sent from the ruleset's data hook back to the terminal for fulfillment.
/// @custom:member hook The pay hook to use when fulfilling this specification.
/// @custom:member noop A flag indicating if the hook callback should be skipped.
/// @custom:member amount The amount to send to the hook.
/// @custom:member metadata Metadata to pass the hook.
struct JBPayHookSpecification {
IJBPayHook hook;
bool noop;
uint256 amount;
bytes metadata;
}
node_modules/@bananapus/core-v6/src/structs/JBRuleset.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBRulesetApprovalHook} from "./../interfaces/IJBRulesetApprovalHook.sol";
/// @notice A ruleset defines how a project behaves during a period of time — token issuance rate, cash-out terms,
/// payout rules, and permissions. Rulesets cycle automatically: when one expires, the next queued (and approved) one
/// takes effect. If nothing is queued, the current ruleset auto-cycles with decayed weight.
/// @dev Timestamps are unix timestamps (seconds since epoch).
/// @custom:member cycleNumber Which cycle this is (starts at 1, increments each cycle).
/// @custom:member id The ruleset's ID — the unix timestamp when it was first stored. Stays the same across
/// auto-cycles.
/// @custom:member basedOnId The ID of the ruleset that was active when this one was created (forms a linked list).
/// @custom:member start When this ruleset became/becomes active.
/// @custom:member duration How many seconds the ruleset lasts. 0 = no auto-cycling (must be explicitly replaced).
/// @custom:member weight Tokens minted per unit paid (18 decimals). The terminal divides payment amount by weight to
/// determine token issuance. Higher weight = more tokens per unit of payment.
/// @custom:member weightCutPercent How much to reduce weight each cycle, out of
/// `JBConstants.MAX_WEIGHT_CUT_PERCENT`. 100,000,000 = 10% cut per cycle. 0 = no decay. Only applies when a cycle
/// auto-rolls without an explicitly queued replacement.
/// @custom:member approvalHook A contract that gates whether queued rulesets can take effect (e.g. `JBDeadline` for
/// minimum notice periods). If the hook rejects a queued ruleset, the current one continues.
/// @custom:member metadata Packed 256-bit field containing reservedPercent, cashOutTaxRate, baseCurrency, boolean
/// flags, data hook address, and custom metadata. Decoded by `JBRulesetMetadataResolver`.
struct JBRuleset {
uint48 cycleNumber;
uint48 id;
uint48 basedOnId;
uint48 start;
uint32 duration;
uint112 weight;
uint32 weightCutPercent;
IJBRulesetApprovalHook approvalHook;
uint256 metadata;
}
node_modules/@bananapus/core-v6/src/structs/JBRulesetConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBRulesetApprovalHook} from "../interfaces/IJBRulesetApprovalHook.sol";
import {JBFundAccessLimitGroup} from "./JBFundAccessLimitGroup.sol";
import {JBRulesetMetadata} from "./JBRulesetMetadata.sol";
import {JBSplitGroup} from "./JBSplitGroup.sol";
/// @notice The configuration passed to `JBController.launchRulesetsFor` or `queueRulesetsOf` to define a new ruleset.
/// Includes the economic parameters (weight, duration, decay), the metadata (permissions and hooks), the split
/// recipients, and the fund access limits.
/// @custom:member mustStartAtOrAfter The earliest timestamp the ruleset can begin. Pass 0 to start immediately after
/// the previous ruleset ends.
/// @custom:member duration How long the ruleset lasts in seconds. 0 = stays active until explicitly replaced.
/// @custom:member weight Tokens minted per unit of payment (18 decimals). Pass 1 to inherit decayed weight from the
/// previous ruleset. Pass 0 for no token issuance.
/// @custom:member weightCutPercent Decay rate per cycle, out of `JBConstants.MAX_WEIGHT_CUT_PERCENT`. 100,000,000 =
/// 10% cut. 0 = no decay.
/// @custom:member approvalHook Contract that must approve the *next* queued ruleset for it to take effect.
/// @custom:member metadata The ruleset's behavioral flags and parameters (see `JBRulesetMetadata`).
/// @custom:member splitGroups How payouts and reserved tokens are distributed during this ruleset.
/// @custom:member fundAccessLimitGroups How much the project can withdraw from each terminal per cycle.
struct JBRulesetConfig {
uint48 mustStartAtOrAfter;
uint32 duration;
uint112 weight;
uint32 weightCutPercent;
IJBRulesetApprovalHook approvalHook;
JBRulesetMetadata metadata;
JBSplitGroup[] splitGroups;
JBFundAccessLimitGroup[] fundAccessLimitGroups;
}
node_modules/@bananapus/core-v6/src/structs/JBRulesetMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Human-readable configuration for a ruleset's behavioral flags and parameters. This struct is packed into
/// 256 bits for on-chain storage (see `JBRulesetMetadataResolver` for the packing layout).
/// @custom:member reservedPercent Percentage of newly minted tokens set aside for the reserved token split group,
/// out of `JBConstants.MAX_RESERVED_PERCENT`. 5,000 = 50% reserved.
/// @custom:member cashOutTaxRate Tax applied when holders cash out tokens, out of
/// `JBConstants.MAX_CASH_OUT_TAX_RATE`. Higher rate = less reclaim per token. 0 = proportional, 10,000 = no reclaim
/// (100% tax).
/// @custom:member baseCurrency The currency used to interpret the ruleset's weight for token issuance. Convention:
/// `uint32(uint160(tokenAddress))` for tokens, or `JBCurrencyIds.ETH`/`JBCurrencyIds.USD` for well-known currencies.
/// @custom:member pausePay If `true`, the project cannot receive payments during this ruleset.
/// @custom:member pauseCreditTransfers If `true`, token credit transfers are disabled during this ruleset.
/// @custom:member allowOwnerMinting If `true`, the project owner (or MINT_TOKENS operator) can mint tokens on demand.
/// @custom:member allowSetCustomToken If `true`, the project can set a custom ERC-20 token via `setTokenFor`.
/// @custom:member allowTerminalMigration If `true`, terminals can be migrated to new implementations.
/// @custom:member allowSetTerminals If `true`, the project's terminal list can be modified.
/// @custom:member allowSetController If `true`, the project's controller can be changed.
/// @custom:member allowAddAccountingContext If `true`, new token accounting contexts can be added to terminals.
/// @custom:member allowAddPriceFeed If `true`, the project can register new price feeds in `JBPrices`.
/// @custom:member ownerMustSendPayouts If `true`, only the project owner can trigger payout distribution.
/// @custom:member holdFees If `true`, fees are accumulated but not processed until a future ruleset (or manually).
/// @custom:member scopeCashOutsToLocalBalances If `true`, omnichain cash-out calculations use only the local chain's
/// balances (not cross-chain aggregates).
/// @custom:member useDataHookForPay If `true`, the data hook is called before recording payments.
/// @custom:member useDataHookForCashOut If `true`, the data hook is called before recording cash outs.
/// @custom:member dataHook Contract called before pay/cash-out to potentially override token counts or add hooks.
/// @custom:member metadata 14 bits of application-specific metadata (upper 2 bits are ignored).
struct JBRulesetMetadata {
uint16 reservedPercent;
uint16 cashOutTaxRate;
uint32 baseCurrency;
bool pausePay;
bool pauseCreditTransfers;
bool allowOwnerMinting;
bool allowSetCustomToken;
bool allowTerminalMigration;
bool allowSetTerminals;
bool allowSetController;
bool allowAddAccountingContext;
bool allowAddPriceFeed;
bool ownerMustSendPayouts;
bool holdFees;
bool scopeCashOutsToLocalBalances;
bool useDataHookForPay;
bool useDataHookForCashOut;
address dataHook;
uint16 metadata;
}
node_modules/@bananapus/core-v6/src/structs/JBRulesetWithMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBRuleset} from "./JBRuleset.sol";
import {JBRulesetMetadata} from "./JBRulesetMetadata.sol";
/// @custom:member ruleset The ruleset.
/// @custom:member metadata The ruleset's metadata.
struct JBRulesetWithMetadata {
JBRuleset ruleset;
JBRulesetMetadata metadata;
}
node_modules/@bananapus/core-v6/src/structs/JBSplit.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBSplitHook} from "./../interfaces/IJBSplitHook.sol";
/// @notice Splits are used to send a percentage of a total token amount to a specific contract, project, or address.
/// Splits are used to send payouts and reserved tokens.
/// @dev 1. If a non-zero split hook contract is specified, this split's tokens are sent there along with this split's
/// properties.
/// @dev 2. Otherwise, if a non-zero project ID is specified, this split's tokens are used to `pay` it through its
/// terminal if possible, or sent to the project's owner if not. If this payment yields tokens, those go to the split's
/// `beneficiary`.
/// @dev 3. Otherwise, this split's tokens are sent directly to the `beneficiary`.
/// @dev To summarize, this split's tokens are sent according to the following priority: `split hook` > `projectId` >
/// `beneficiary`.
/// @custom:member percent The percent of the total token amount that this split sends. This number is out of
/// `JBConstants.SPLITS_TOTAL_PERCENT`.
/// @custom:member projectId The ID of a project to `pay`, if applicable. Resulting tokens are routed to `beneficiary`.
/// @custom:member beneficiary Receives this split's tokens if the `hook` and `projectId` are zero. If the `projectId`
/// is specified, the `beneficiary` receives any project tokens minted by this split. If `beneficiary` is `address(0)`,
/// the application processing the split decides on the recipient. For example, the terminal uses `msg.sender` for
/// payout splits, and the controller uses `msg.sender` for reserved token splits.
/// @custom:member preferAddToBalance If this split were to `pay` a project through its terminal, this flag indicates
/// whether it should prefer using the terminal's `addToBalance` function instead.
/// @custom:member lockedUntil The split cannot be changed until this timestamp. The `lockedUntil` timestamp can be
/// increased while a split is locked. If `lockedUntil` is zero, this split can be changed at any time. This lock is
/// enforced only when rewriting the same split table. Queueing a successor ruleset with a different `rulesetId` can
/// still replace future payout behavior before `lockedUntil`, so applications that need cross-ruleset continuity must
/// preserve those splits at the governance/configuration layer.
/// @custom:member hook A contract which will receive this split's tokens and properties, and can define custom
/// behavior.
struct JBSplit {
uint32 percent;
uint64 projectId;
address payable beneficiary;
bool preferAddToBalance;
uint48 lockedUntil;
IJBSplitHook hook;
}
node_modules/@bananapus/core-v6/src/structs/JBSplitGroup.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBSplit} from "./JBSplit.sol";
/// @custom:member groupId An identifier for the group. By convention, this ID is `uint256(uint160(tokenAddress))` for
/// payouts and `1` for reserved tokens.
/// @custom:member splits The splits in the group.
struct JBSplitGroup {
uint256 groupId;
JBSplit[] splits;
}
node_modules/@bananapus/core-v6/src/structs/JBSplitHookContext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBSplit} from "./JBSplit.sol";
/// @custom:member token The token to send to the split hook.
/// @custom:member amount The amount to send to the split hook, as a fixed point number.
/// @custom:member decimals The number of decimals in the amount.
/// @custom:member projectId The project the split belongs to.
/// @custom:member groupId The group the split belongs to. By convention, this ID is `uint256(uint160(tokenAddress))`
/// for payouts and `1` for reserved tokens.
/// @custom:member split The split which specified the hook.
struct JBSplitHookContext {
address token;
uint256 amount;
uint256 decimals;
uint256 projectId;
uint256 groupId;
JBSplit split;
}
node_modules/@bananapus/core-v6/src/structs/JBTerminalConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {JBAccountingContext} from "./JBAccountingContext.sol";
import {IJBTerminal} from "./../interfaces/IJBTerminal.sol";
/// @custom:member terminal The terminal to configure.
/// @custom:member accountingContextsToAccept The accounting contexts to accept from the terminal.
struct JBTerminalConfig {
IJBTerminal terminal;
JBAccountingContext[] accountingContextsToAccept;
}
node_modules/@bananapus/core-v6/src/structs/JBTokenAmount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @custom:member token The token the payment was made in.
/// @custom:member decimals The number of decimals included in the value fixed point number.
/// @custom:member currency The currency. By convention, this is `uint32(uint160(tokenAddress))` for tokens, or a
/// constant ID from e.g. `JBCurrencyIds` for other currencies.
/// @custom:member value The amount of tokens that was paid, as a fixed point number.
struct JBTokenAmount {
address token;
uint8 decimals;
uint32 currency;
uint256 value;
}
node_modules/@openzeppelin/contracts/metatx/ERC2771Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (metatx/ERC2771Context.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Context variant with ERC-2771 support. See {_msgSender} for the calldata format.
*
* WARNING: Avoid using this pattern in contracts that rely on a specific calldata length as they'll
* be affected by any forwarder whose `msg.data` is suffixed with the `from` address according to the ERC-2771
* specification adding the address size in bytes (20) to the calldata size. An example of an unexpected
* behavior could be an unintended fallback (or another function) invocation while trying to invoke the `receive`
* function only accessible if `msg.data.length == 0`.
*
* WARNING: The usage of `delegatecall` in this contract is dangerous and may result in context corruption.
* Any forwarded request to this contract triggering a `delegatecall` to itself will result in an invalid {_msgSender}
* recovery.
*/
abstract contract ERC2771Context is Context {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable _trustedForwarder;
/**
* @dev Initializes the contract with a trusted forwarder, which will be able to
* invoke functions on this contract on behalf of other accounts.
*
* NOTE: The trusted forwarder can be replaced by overriding {trustedForwarder}.
*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(address trustedForwarder_) {
_trustedForwarder = trustedForwarder_;
}
/**
* @dev Returns the address of the trusted forwarder.
*/
function trustedForwarder() public view virtual returns (address) {
return _trustedForwarder;
}
/**
* @dev Indicates whether any particular address is the trusted forwarder.
*/
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return forwarder == trustedForwarder();
}
/**
* @dev Override for `msg.sender`. Defaults to the original `msg.sender` whenever
* a call is not performed by the trusted forwarder or the calldata length is less than
* 20 bytes (an address length).
*/
function _msgSender() internal view virtual override returns (address) {
uint256 calldataLength = msg.data.length;
uint256 contextSuffixLength = _contextSuffixLength();
if (calldataLength >= contextSuffixLength && isTrustedForwarder(msg.sender)) {
unchecked {
return address(bytes20(msg.data[calldataLength - contextSuffixLength:]));
}
} else {
return super._msgSender();
}
}
/**
* @dev Override for `msg.data`. Defaults to the original `msg.data` whenever
* a call is not performed by the trusted forwarder or the calldata length is less than
* 20 bytes (an address length).
*/
function _msgData() internal view virtual override returns (bytes calldata) {
uint256 calldataLength = msg.data.length;
uint256 contextSuffixLength = _contextSuffixLength();
if (calldataLength >= contextSuffixLength && isTrustedForwarder(msg.sender)) {
unchecked {
return msg.data[:calldataLength - contextSuffixLength];
}
} else {
return super._msgData();
}
}
/**
* @dev ERC-2771 specifies the context as being a single address (20 bytes).
*/
function _contextSuffixLength() internal view virtual override returns (uint256) {
return 20;
}
}
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/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)
}
}
}
node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
node_modules/@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.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 `condition ? a : b`. 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. `condition ? a : b`) 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) {
unchecked {
// (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 buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 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 first 16 bytes (most significant half).
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;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.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 a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a 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 A 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/IStickyDeployer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBController} from "@bananapus/core-v6/src/interfaces/IJBController.sol";
import {IJBPayerTracker} from "@bananapus/core-v6/src/interfaces/IJBPayerTracker.sol";
import {IJBPriceFeed} from "@bananapus/core-v6/src/interfaces/IJBPriceFeed.sol";
import {IJBTerminal} from "@bananapus/core-v6/src/interfaces/IJBTerminal.sol";
import {IJBToken} from "@bananapus/core-v6/src/interfaces/IJBToken.sol";
import {IJBTokens} from "@bananapus/core-v6/src/interfaces/IJBTokens.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IStickyHook} from "./IStickyHook.sol";
/// @notice Deploys permanently configured projects that issue backing-priced shares for stakes and allow cash-outs
/// under their chosen tax and transfer policy.
interface IStickyDeployer is IJBPayerTracker {
/// @notice Emitted when a sticky project is deployed.
/// @param projectId The ID of the sticky project.
/// @param stakedToken The token the project accepts for staking.
/// @param token The share token issued to represent staked positions.
/// @param cashOutTaxRate The cash out curve parameter, out of `JBConstants.MAX_CASH_OUT_TAX_RATE`.
/// @param soulbound Whether the staked copy's transfers revert.
/// @param caller The address that deployed the sticky project.
event DeploySticky(
uint256 indexed projectId,
IERC20Metadata indexed stakedToken,
IJBToken token,
uint256 cashOutTaxRate,
bool soulbound,
address caller
);
/// @notice The controller used to launch and manage sticky projects.
/// @return controller The immutable project controller.
function CONTROLLER() external view returns (IJBController controller);
/// @notice The data hook that tracks staking positions for sticky projects.
/// @return hook The immutable pricing and accounting hook.
function HOOK() external view returns (IStickyHook hook);
/// @notice The terminal sticky projects accept their staked token through.
/// @return terminal The immutable staking terminal.
function TERMINAL() external view returns (IJBTerminal terminal);
/// @notice The contract managing token minting and burning for projects.
/// @return tokens The controller's token registry.
function TOKENS() external view returns (IJBTokens tokens);
/// @notice The project's cash out curve parameter, out of `JBConstants.MAX_CASH_OUT_TAX_RATE`.
/// @dev The retained proportion also depends on the fraction of supply redeemed; this is not a flat fee.
/// @param projectId The ID of the sticky project to get the cash out tax rate of.
/// @return rate The project's permanent tax rate, out of the protocol maximum.
function cashOutTaxRateOf(uint256 projectId) external view returns (uint256 rate);
/// @notice The share token address a launch produces for a launcher, project ID and configuration.
/// @dev The project ID enters the token's creation code, so a prediction holds only for the ID the launch
/// actually receives.
/// @param launcher The account that calls `deployStickyFor`.
/// @param projectId The ID of the sticky project the launch receives.
/// @param stakedToken The token the project accepts for staking.
/// @param name The name of the share token.
/// @param symbol The symbol of the share token.
/// @param projectUri The sticky project's metadata URI.
/// @param cashOutTaxRate The cash out curve parameter, out of `JBConstants.MAX_CASH_OUT_TAX_RATE`.
/// @param granters Addresses allowed to airdrop stakes to any holder.
/// @param soulbound Whether transfers between holders revert.
/// @return token The share token's address, whether or not it has been deployed.
function predictStickyTokenOf(
address launcher,
uint256 projectId,
IERC20Metadata stakedToken,
string calldata name,
string calldata symbol,
string calldata projectUri,
uint256 cashOutTaxRate,
address[] calldata granters,
bool soulbound
)
external
view
returns (address token);
/// @notice The immutable accounting feed supplying the denominator of the share issuance ratio.
/// @param projectId The ID of the sticky project.
/// @return feed The project's feed, or the zero address for an unknown project.
function priceFeedOf(uint256 projectId) external view returns (IJBPriceFeed feed);
/// @notice The token a sticky project accepts for staking.
/// @param projectId The ID of the sticky project to get the staked token of.
/// @return token The underlying token, or the zero address for an unknown project.
function stakedTokenOf(uint256 projectId) external view returns (IERC20Metadata token);
/// @notice Deploys a sticky project for a token.
/// @dev The `msg.value` must equal the project creation fee required by `JBProjects`.
/// @param stakedToken The token the project accepts for staking. Cannot be the share token of another project
/// launched by this deployer.
/// @param name The name of the share token issued to represent staked positions.
/// @param symbol The symbol of the share token issued to represent staked positions.
/// @param projectUri The sticky project's metadata URI.
/// @param cashOutTaxRate The cash out curve parameter, out of `JBConstants.MAX_CASH_OUT_TAX_RATE`. Zero uses
/// proportional share-owned backing; positive values apply the protocol's cash-out curve. The maximum returns no
/// backing. Terminal fee rules still apply.
/// @param granters Addresses allowed to airdrop stakes to any holder (e.g. the community's grant program).
/// Permanent — holders can additionally trust senders for their own position at any time.
/// @param soulbound Whether transfers between holders revert; otherwise moved shares receive fresh timestamps.
/// @return projectId The ID of the sticky project.
function deployStickyFor(
IERC20Metadata stakedToken,
string calldata name,
string calldata symbol,
string calldata projectUri,
uint256 cashOutTaxRate,
address[] calldata granters,
bool soulbound
)
external
payable
returns (uint256 projectId);
}
src/interfaces/IStickyHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IJBCashOutHook} from "@bananapus/core-v6/src/interfaces/IJBCashOutHook.sol";
import {IJBDirectory} from "@bananapus/core-v6/src/interfaces/IJBDirectory.sol";
import {IJBPayHook} from "@bananapus/core-v6/src/interfaces/IJBPayHook.sol";
import {IJBRulesetDataHook} from "@bananapus/core-v6/src/interfaces/IJBRulesetDataHook.sol";
import {StickyTranche} from "../structs/StickyTranche.sol";
/// @notice A data hook that tracks staking positions for sticky projects: per-epoch tranches, LIFO unstaking, net
/// stake buckets by joining epoch, and a holder-level streak clock.
interface IStickyHook is IJBRulesetDataHook, IJBPayHook, IJBCashOutHook {
/// @notice Emitted when the deployment authority permanently binds the project's launcher.
/// @param deployer The launcher authorized to register project tokens and granters.
/// @param caller The deployment authority that completed the binding.
event BindDeployer(address indexed deployer, address caller);
/// @notice Emitted when backing present without any shares is excluded from future holders' claims.
/// @param projectId The ID of the sticky project.
/// @param amount The total excluded underlying balance, in underlying token atoms.
/// @param caller The terminal that recorded the first payment of the new share supply.
event ExcludeOrphanedBalance(uint256 indexed projectId, uint256 amount, address caller);
/// @notice Emitted when an address is allowed to airdrop stakes to any holder of a sticky project.
/// @param projectId The ID of the sticky project the sender can airdrop to.
/// @param granter The address allowed to airdrop.
/// @param caller The address that set the granter.
event SetGranter(uint256 indexed projectId, address indexed granter, address caller);
/// @notice Emitted when a sticky project's share token is registered as its movement reporter.
/// @param projectId The ID of the sticky project.
/// @param token The Sticky share token allowed to report transfers and burns.
/// @param caller The address that registered the token.
event SetToken(uint256 indexed projectId, address token, address caller);
/// @notice Emitted when a holder allows or disallows a sender to add stakes to their position.
/// @param projectId The ID of the sticky project the trust applies to.
/// @param holder The holder whose position the sender can add to.
/// @param sender The sender being trusted or untrusted.
/// @param trusted Whether the sender is now trusted.
event SetTrustedSender(uint256 indexed projectId, address indexed holder, address indexed sender, bool trusted);
/// @notice Emitted when Sticky shares join the holder's newest tranche of the epoch or create a new one.
/// @param projectId The ID of the sticky project being staked to.
/// @param holder The address the staked position belongs to.
/// @param payer The payment payer or transfer sender whose shares joined the position.
/// @param count The shares added by a payment or incoming transfer, as a fixed point number with 18 decimals.
/// @param stakedBalance The holder's staked balance after the stake, as a fixed point number with 18 decimals.
/// @param caller The address that triggered the stake.
event Staked(
uint256 indexed projectId,
address indexed holder,
address payer,
uint256 count,
uint256 stakedBalance,
address caller
);
/// @notice Emitted when a holder's streak ends because their staked balance reached zero.
/// @param projectId The ID of the sticky project the streak belongs to.
/// @param holder The address whose streak ended.
/// @param duration The number of seconds the streak lasted.
/// @param caller The address that triggered the unstake which ended the streak.
event StreakEnded(uint256 indexed projectId, address indexed holder, uint256 duration, address caller);
/// @notice Emitted when a holder's streak starts because their staked balance became non-zero.
/// @param projectId The ID of the sticky project the streak belongs to.
/// @param holder The address whose streak started.
/// @param caller The address that triggered the stake which started the streak.
event StreakStarted(uint256 indexed projectId, address indexed holder, address caller);
/// @notice Emitted when Sticky shares burn or transfer away, consuming tranches newest-first.
/// @dev A voluntary burn or transfer does not reclaim backing; this event alone does not prove a cash out.
/// @param projectId The ID of the sticky project being unstaked from.
/// @param holder The address the staked position belongs to.
/// @param count The number of Sticky shares removed, as a fixed point number with 18 decimals.
/// @param stakedBalance The holder's staked balance after the unstake, as a fixed point number with 18 decimals.
/// @param caller The registered Sticky share token that reported the movement.
event Unstaked(
uint256 indexed projectId, address indexed holder, uint256 count, uint256 stakedBalance, address caller
);
/// @notice The address allowed to set a project's granters, once, at launch.
/// @return deployer The permanently bound deployer, zero until the one-time setup is completed.
function DEPLOYER() external view returns (address deployer);
/// @notice The only account allowed to bind the deployer once, with no operation authority after binding.
/// @return deploymentAuthority The explicit deployment-time binding authority.
function DEPLOYMENT_AUTHORITY() external view returns (address deploymentAuthority);
/// @notice The directory of terminals and controllers for projects.
/// @return directory The directory used to validate terminal callbacks.
function DIRECTORY() external view returns (IJBDirectory directory);
/// @notice The duration of one stake-age epoch. Tranches created in the same epoch merge, and net stake is
/// bucketed by the epoch it joined in.
/// @return duration The epoch duration, in seconds.
function EPOCH_DURATION() external view returns (uint256 duration);
/// @notice The duration of a holder's active streak, in seconds.
/// @param projectId The ID of the sticky project to check the streak of.
/// @param holder The address to check the streak of.
/// @return duration The number of seconds since the holder's staked balance last became non-zero, or 0 if nothing
/// is staked.
function currentStreakOf(uint256 projectId, address holder) external view returns (uint256 duration);
/// @notice Whether an address can airdrop stakes to any holder of a sticky project.
/// @param projectId The ID of the sticky project to check.
/// @param granter The address to check.
/// @return isGranter Whether the address is a project granter.
function isGranterOf(uint256 projectId, address granter) external view returns (bool isGranter);
/// @notice Whether a payment to a project has minted shares this hook has not yet recorded.
/// @dev Set by the registered share token on every mint and cleared by the terminal's after-pay callback, so the
/// distributor never reads a tenure denominator while the epoch buckets lag the share supply.
/// @param projectId The ID of the sticky project to check.
/// @return isPaying Whether a payment's minted shares are still waiting for their tranche.
function isPayingFor(uint256 projectId) external view returns (bool isPaying);
/// @notice Whether a holder allows a sender to add stakes to their position.
/// @param projectId The ID of the sticky project to check.
/// @param holder The holder whose position would be added to.
/// @param sender The sender to check.
/// @return isTrusted Whether the holder trusts the sender.
function isTrustedSenderOf(uint256 projectId, address holder, address sender) external view returns (bool isTrusted);
/// @notice The longest streak a holder has ever had, including their active streak.
/// @param projectId The ID of the sticky project to check the streak of.
/// @param holder The address to check the streak of.
/// @return duration The holder's longest streak duration, in seconds.
function longestStreakOf(uint256 projectId, address holder) external view returns (uint256 duration);
/// @notice The net stake still held from tranches created in an epoch, as a fixed point number with 18 decimals.
/// @param projectId The ID of the sticky project.
/// @param epoch The epoch, measured as `timestamp / EPOCH_DURATION`.
/// @return amount The epoch's net stake bucket.
function netStakedIn(uint256 projectId, uint256 epoch) external view returns (uint256 amount);
/// @notice The net stake still held from tranches created within an inclusive epoch range, as a fixed point
/// number with 18 decimals.
/// @param projectId The ID of the sticky project.
/// @param fromEpoch The first epoch to include.
/// @param toEpoch The last epoch to include.
/// @return amount The sum of the range's net stake buckets.
function netStakedWithin(
uint256 projectId,
uint256 fromEpoch,
uint256 toEpoch
)
external
view
returns (uint256 amount);
/// @notice Backing excluded when the most recent share supply began.
/// @dev While no shares exist, all current terminal backing is unowned even if this stored value is lower.
/// @param projectId The ID of the sticky project.
/// @return amount The excluded underlying balance, in underlying token atoms.
function orphanedBalanceOf(uint256 projectId) external view returns (uint256 amount);
/// @notice The total number of Sticky shares in a holder's position, as a fixed point number with 18 decimals.
/// @param projectId The ID of the sticky project to check the balance of.
/// @param holder The address to check the balance of.
/// @return balance The holder's current Sticky share balance.
function stakedBalanceOf(uint256 projectId, address holder) external view returns (uint256 balance);
/// @notice A holder's staked balance held in tranches created through an epoch, as a fixed point number with 18
/// decimals.
/// @param projectId The ID of the sticky project.
/// @param holder The holder whose tranches to read.
/// @param epoch The last epoch to include.
/// @return balance The staked balance from tranches created in or before the epoch.
function stakedBalanceThroughEpochOf(
uint256 projectId,
address holder,
uint256 epoch
)
external
view
returns (uint256 balance);
/// @notice The timestamp at which a holder's active streak started, or 0 if nothing is staked.
/// @param projectId The ID of the sticky project to check the streak of.
/// @param holder The address to check the streak of.
/// @return timestamp The active streak's start timestamp, or zero if the balance is zero.
function streakStartOf(uint256 projectId, address holder) external view returns (uint256 timestamp);
/// @notice The Sticky share token allowed to report transfers and burns for a project.
/// @param projectId The ID of the sticky project to get the token of.
/// @return token The project's registered Sticky share token.
function tokenOf(uint256 projectId) external view returns (address token);
/// @notice The number of tranches a holder has.
/// @param projectId The ID of the sticky project to check the tranches of.
/// @param holder The address to check the tranches of.
/// @return count The number of active tranches.
function trancheCountOf(uint256 projectId, address holder) external view returns (uint256 count);
/// @notice A holder's tranches, oldest first.
/// @dev Copies every active tranche. Use the paginated overload for positions with many deposits or transfers.
/// @param projectId The ID of the sticky project to get the tranches of.
/// @param holder The address to get the tranches of.
/// @return tranches The active tranches, oldest first.
function tranchesOf(uint256 projectId, address holder) external view returns (StickyTranche[] memory tranches);
/// @notice A bounded range of a holder's active tranches, oldest first.
/// @param projectId The ID of the sticky project.
/// @param holder The holder whose tranches to read.
/// @param start The zero-based index of the first tranche to read.
/// @param count The maximum number of tranches to return, capped at 256.
/// @return tranches The requested tranches, ending at the active count if fewer remain.
function tranchesOf(
uint256 projectId,
address holder,
uint256 start,
uint256 count
)
external
view
returns (StickyTranche[] memory tranches);
/// @notice Consumes the newest tranches for every positive Sticky share burn, including voluntary controller burns.
/// @dev Only the registered Sticky share token can report burns. Zero burns leave accounting unchanged.
/// @param projectId The ID of the sticky project.
/// @param holder The holder whose shares were burned.
/// @param amount The number of shares burned, as a fixed point number with 18 decimals.
function recordBurn(uint256 projectId, address holder, uint256 amount) external;
/// @notice Counts a share issuance whose tranche this hook has not yet recorded, flagging the project's payment as
/// in progress until the terminal's after-pay callback records it.
/// @dev Only the registered Sticky share token can report mints.
/// @param projectId The ID of the sticky project whose shares were issued.
function recordMint(uint256 projectId) external;
/// @notice Moves staked accounting between holders for a transferable Sticky share token: the sender's newest
/// tranches are consumed and the moved shares join the receiver's newest tranche of the current epoch, or a fresh
/// one. The receiver's existing streak continues.
/// @dev Can only be called by the project's registered Sticky share token. Zero and self transfers are no-ops.
/// @param projectId The ID of the sticky project the transfer belongs to.
/// @param from The holder the shares moved from.
/// @param to The holder the shares moved to.
/// @param amount The number of shares moved, as a fixed point number with 18 decimals.
function recordTransfer(uint256 projectId, address from, address to, uint256 amount) external;
/// @notice Permanently binds the deployed launcher authorized to register project tokens and granters.
/// @dev Only the explicit deployment authority can call once. The launcher must reference this hook, share its
/// directory and trusted forwarder, and have deployed code. Forwarded callers cannot complete this binding.
/// @param deployer The deployed launcher to bind permanently.
function setDeployer(address deployer) external;
/// @notice Allows addresses to airdrop stakes to any holder of a sticky project.
/// @dev Can only be called by the deployer, which calls it once at launch.
/// @param projectId The ID of the sticky project the senders can airdrop to.
/// @param granters The addresses allowed to airdrop.
function setGrantersFor(uint256 projectId, address[] calldata granters) external;
/// @notice Registers the Sticky share token allowed to report transfers and burns for a project.
/// @dev Can only be called by the deployer, which calls it once at launch.
/// @param projectId The ID of the sticky project.
/// @param token The Sticky share token.
function setTokenFor(uint256 projectId, address token) external;
/// @notice Allows or disallows a sender to add stakes to the caller's position.
/// @param projectId The ID of the sticky project the trust applies to.
/// @param sender The sender to trust or untrust.
/// @param trusted Whether the sender should be trusted.
function setTrustedSenderFor(uint256 projectId, address sender, bool trusted) external;
}
src/libraries/StickyPricing.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @notice Prices new Sticky shares against existing backing without diluting outstanding shares.
library StickyPricing {
//*********************************************************************//
// --------------------------- custom errors ------------------------- //
//*********************************************************************//
/// @notice Thrown when the payment's accounting precision exceeds the 36 decimals the terminal supports.
/// @param decimals The unsupported accounting precision.
error StickyPricing_UnsupportedDecimals(uint256 decimals);
//*********************************************************************//
// ----------------------- internal constants ------------------------ //
//*********************************************************************//
/// @notice The smallest initial issuance, in share atoms: one millionth of a whole underlying token.
/// @dev This keeps initial share precision useful without restricting later exits. Burns may leave fewer
/// shares; every later deposit must independently satisfy the rounding limit.
uint256 internal constant _MIN_INITIAL_SUPPLY = 1e12;
/// @notice One basis point of ideal share issuance is the largest permitted rounding loss.
uint256 internal constant _ROUNDING_DENOMINATOR = 10_000;
//*********************************************************************//
// ----------------------- internal helpers -------------------------- //
//*********************************************************************//
/// @notice Calculates the numerator of the exact share issuance ratio for a payment.
/// @dev Empty projects begin with decimal-normalized one-for-one issuance. Their previous backing must be
/// excluded separately. Returning zero lets terminal previews report an unissuable amount; the pay callback
/// must reject positive payments that issue nothing. The loss bound concerns shares, not cash-out rounding.
/// @param amount The accepted payment amount, in the underlying token's decimals.
/// @param supply The outstanding Sticky share supply, with 18 decimals.
/// @param backing The underlying backing belonging to those shares, in the underlying token's decimals.
/// @param decimals The underlying token's accounting decimals.
/// @return weight The share supply to pass to the terminal, or zero if issuance is unsafe. The project's
/// immutable price feed supplies the backing denominator in the same accounting precision as the payment.
// Isolate the pure pricing invariant so its boundary behavior can be exercised independently of callbacks.
// forge-lint: disable-next-line(internal-function-used-once)
function weightFrom(
uint256 amount,
uint256 supply,
uint256 backing,
uint8 decimals
)
internal
pure
returns (uint256 weight)
{
// Stay within the core's supported accounting precision before calculating the underlying unit scale.
if (decimals > 36) revert StickyPricing_UnsupportedDecimals(decimals);
// Express one whole underlying token in its accounting units for the initial one-for-one exchange rate.
uint256 scale = 10 ** decimals;
// Remember whether shares exist before substituting the initial issuance ratio below.
bool bootstrap = supply == 0;
// With no outstanding shares there is no existing holder exchange rate to preserve.
if (bootstrap) {
// Use one whole 18-decimal share as the numerator, without adding virtual shares to actual supply.
supply = 1e18;
// Pair it with one whole underlying token so initial issuance normalizes the token's decimals.
backing = scale;
} else if (backing == 0) {
// No finite exchange rate exists for unbacked shares; signal that the payment cannot issue shares.
return 0;
}
// Pass the numerator to the terminal; the project's price feed supplies the exact backing denominator.
weight = supply;
// Match the terminal's floor rounding to assess the number of shares the payment would actually receive.
uint256 issuedCount = Math.mulDiv({x: amount, y: supply, denominator: backing});
// Start an empty project with enough share atoms for useful initial precision.
if (bootstrap && issuedCount < _MIN_INITIAL_SUPPLY) return 0;
// Round the ideal issuance up to measure a conservative whole-atom bound on the payer's rounding loss.
uint256 idealCount = Math.mulDiv({x: amount, y: supply, denominator: backing, rounding: Math.Rounding.Ceil});
// Reject loss above one basis point of the ceiling, including issuance just above one share atom.
// Passing this check leaves the named return value set to the validated issuance numerator.
if (issuedCount < idealCount - idealCount / _ROUNDING_DENOMINATOR) return 0;
}
}
src/structs/StickyPaySnapshot.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The pricing state authenticated by the terminal's before-pay and after-pay hook calls.
/// @custom:member supply The share supply immediately before recording the payment.
/// @custom:member backing The terminal backing immediately before recording the payment, in underlying token atoms.
/// @custom:member orphanedBalance Backing excluded from all share holders because it existed without any shares.
struct StickyPaySnapshot {
uint256 supply;
uint256 backing;
uint256 orphanedBalance;
}
src/structs/StickyTranche.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice A holder's shares joined in one epoch. Additions in the same epoch merge into this tranche and refresh
/// its timestamp to the latest addition.
/// @custom:member amount The number of Sticky shares this tranche represents, as a fixed point number with 18
/// decimals.
/// @custom:member timestamp The timestamp of the latest positive addition to this tranche. Partial unstakes keep
/// the remainder's timestamp unchanged.
struct StickyTranche {
uint208 amount;
uint48 timestamp;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/",
"node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/",
"node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/permit2/lib/solmate/:ds-test/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/permit2/lib/solmate/:ds-test/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/",
"node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/:@openzeppelin/contracts/=node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/node_modules/@openzeppelin/contracts/",
"node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/:@openzeppelin/contracts/=node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/node_modules/@openzeppelin/contracts/",
"node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/:solady/=node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/node_modules/solady/",
"node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/:solady/=node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/node_modules/solady/",
"node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"node_modules/@uniswap/v4-core/lib/solmate/:ds-test/=node_modules/@uniswap/v4-core/lib/solmate/lib/ds-test/",
"node_modules/@uniswap/v4-core/lib/solmate/:ds-test/=node_modules/@uniswap/v4-core/lib/solmate/lib/ds-test/",
"node_modules/@uniswap/v4-periphery/lib/permit2/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-periphery/lib/permit2/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-periphery/lib/permit2/:solmate/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/solmate/",
"node_modules/@uniswap/v4-periphery/lib/permit2/:solmate/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/solmate/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/:solmate/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/solmate/",
"node_modules/@uniswap/v4-periphery/lib/v4-core/:solmate/=node_modules/@uniswap/v4-periphery/lib/v4-core/lib/solmate/",
"node_modules/@arbitrum/nitro-contracts/:@openzeppelin/contracts-upgradeable/=node_modules/@arbitrum/nitro-contracts/node_modules/@openzeppelin/contracts-upgradeable/",
"node_modules/@arbitrum/nitro-contracts/:@openzeppelin/contracts-upgradeable/=node_modules/@arbitrum/nitro-contracts/node_modules/@openzeppelin/contracts-upgradeable/",
"node_modules/@arbitrum/nitro-contracts/:@openzeppelin/contracts/=node_modules/@arbitrum/nitro-contracts/node_modules/@openzeppelin/contracts/",
"node_modules/@arbitrum/nitro-contracts/:@openzeppelin/contracts/=node_modules/@arbitrum/nitro-contracts/node_modules/@openzeppelin/contracts/",
"node_modules/@bananapus/721-hook-v6/:solady/=node_modules/@bananapus/721-hook-v6/node_modules/solady/",
"node_modules/@bananapus/721-hook-v6/:solady/=node_modules/@bananapus/721-hook-v6/node_modules/solady/",
"node_modules/@bananapus/suckers-v6/:@arbitrum/nitro-contracts/=node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/",
"node_modules/@bananapus/suckers-v6/:@arbitrum/nitro-contracts/=node_modules/@bananapus/suckers-v6/node_modules/@arbitrum/nitro-contracts/",
"node_modules/@bananapus/suckers-v6/:@openzeppelin/contracts-upgradeable/=node_modules/@bananapus/suckers-v6/node_modules/@openzeppelin/contracts-upgradeable/",
"node_modules/@bananapus/suckers-v6/:@openzeppelin/contracts-upgradeable/=node_modules/@bananapus/suckers-v6/node_modules/@openzeppelin/contracts-upgradeable/",
"node_modules/@bananapus/suckers-v6/:solady/=node_modules/@bananapus/suckers-v6/node_modules/solady/",
"node_modules/@bananapus/suckers-v6/:solady/=node_modules/@bananapus/suckers-v6/node_modules/solady/",
"node_modules/@offchainlabs/upgrade-executor/:@openzeppelin/contracts-upgradeable/=node_modules/@offchainlabs/upgrade-executor/node_modules/@openzeppelin/contracts-upgradeable/",
"node_modules/@offchainlabs/upgrade-executor/:@openzeppelin/contracts-upgradeable/=node_modules/@offchainlabs/upgrade-executor/node_modules/@openzeppelin/contracts-upgradeable/",
"node_modules/@offchainlabs/upgrade-executor/:@openzeppelin/contracts/=node_modules/@offchainlabs/upgrade-executor/node_modules/@openzeppelin/contracts/",
"node_modules/@offchainlabs/upgrade-executor/:@openzeppelin/contracts/=node_modules/@offchainlabs/upgrade-executor/node_modules/@openzeppelin/contracts/",
"node_modules/@sphinx-labs/contracts/:@openzeppelin/contracts/=node_modules/@sphinx-labs/contracts/node_modules/@openzeppelin/contracts/",
"node_modules/@sphinx-labs/contracts/:@openzeppelin/contracts/=node_modules/@sphinx-labs/contracts/node_modules/@openzeppelin/contracts/",
"node_modules/@sphinx-labs/core/:hardhat/=node_modules/@sphinx-labs/core/node_modules/hardhat/",
"node_modules/@sphinx-labs/core/:hardhat/=node_modules/@sphinx-labs/core/node_modules/hardhat/",
"node_modules/@sphinx-labs/plugins/:@eth-optimism/contracts/=node_modules/@sphinx-labs/plugins/node_modules/@eth-optimism/contracts/",
"node_modules/@sphinx-labs/plugins/:@eth-optimism/contracts/=node_modules/@sphinx-labs/plugins/node_modules/@eth-optimism/contracts/",
"node_modules/@sphinx-labs/plugins/:@openzeppelin/contracts/=node_modules/@sphinx-labs/plugins/node_modules/@openzeppelin/contracts/",
"node_modules/@sphinx-labs/plugins/:@openzeppelin/contracts/=node_modules/@sphinx-labs/plugins/node_modules/@openzeppelin/contracts/",
"node_modules/@uniswap/v3-periphery/:@openzeppelin/contracts/=node_modules/@uniswap/v3-periphery/node_modules/@openzeppelin/contracts/",
"node_modules/@uniswap/v3-periphery/:@openzeppelin/contracts/=node_modules/@uniswap/v3-periphery/node_modules/@openzeppelin/contracts/",
"node_modules/@uniswap/v3-periphery/:@uniswap/v3-core/=node_modules/@uniswap/v3-periphery/node_modules/@uniswap/v3-core/",
"node_modules/@uniswap/v3-periphery/:@uniswap/v3-core/=node_modules/@uniswap/v3-periphery/node_modules/@uniswap/v3-core/",
"node_modules/@uniswap/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-core/:openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"node_modules/@uniswap/v4-core/:solmate/=node_modules/@uniswap/v4-core/lib/solmate/",
"node_modules/@uniswap/v4-core/:solmate/=node_modules/@uniswap/v4-core/lib/solmate/",
"@arbitrum/=node_modules/@arbitrum/",
"@bananapus/=node_modules/@bananapus/",
"@chainlink/=node_modules/@chainlink/",
"@croptop/=node_modules/@croptop/",
"@eth-optimism/=node_modules/@eth-optimism/",
"@offchainlabs/=node_modules/@offchainlabs/",
"@openzeppelin/=node_modules/@openzeppelin/",
"@prb/=node_modules/@prb/",
"@rev-net/=node_modules/@rev-net/",
"@scroll-tech/=node_modules/@scroll-tech/",
"@sphinx-labs/=node_modules/@sphinx-labs/",
"@uniswap/=node_modules/@uniswap/",
"@zksync/=node_modules/@zksync/",
"base64-sol/=node_modules/base64-sol/",
"ds-test/=node_modules/@uniswap/v4-core/lib/solmate/lib/ds-test/",
"erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-gas-snapshot/",
"hardhat/=node_modules/hardhat/",
"openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"permit2/=node_modules/@uniswap/v4-periphery/lib/permit2/",
"solady/=node_modules/solady/",
"solmate/=node_modules/solmate/",
"v4-core/=node_modules/@uniswap/v4-periphery/lib/v4-core/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.