Verified contractExact--
CohortFlushFacet
Address0x2ada747e79664bd3d22c0bf109c454a64f89e837
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.36
- Same code
3 more contracts
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- Yes, 600,000 runs
- EVM version
- cancun
- License
- --
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,386,318
- Creation transaction
- 0x9e01f37911…08d05f3dff
29 files
- src/diamond/vault/facets/CohortFlushFacet.solmain4.94 KB
- node_modules/@chainlink/contracts-ccip/contracts/interfaces/IRouterClient.sol1.65 KB
- node_modules/@chainlink/contracts-ccip/contracts/libraries/Client.sol4.7 KB
- node_modules/@openzeppelin/contracts/security/Pausable.sol2.55 KB
- node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol3.13 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol844 B
- src/diamond/shared/CohortFlushCodec.sol7.62 KB
- src/diamond/shared/CohortWeeks.sol22.34 KB
- src/diamond/shared/DiamondErrors.sol336 B
- src/diamond/shared/OwnableMaster.sol2.04 KB
- src/diamond/vault/WiseTelecomNodesDiamondErrors.sol3.88 KB
- src/diamond/vault/WiseTelecomNodesDiamondEvents.sol14.52 KB
- src/diamond/vault/declarations/CohortAttributionDeclaration.sol446 B
- src/diamond/vault/declarations/CohortBookDeclaration.sol986 B
- src/diamond/vault/declarations/CohortContributionDeclaration.sol2.03 KB
- src/diamond/vault/declarations/CohortDisarmDeclaration.sol793 B
- src/diamond/vault/declarations/CohortDivestDeclaration.sol488 B
- src/diamond/vault/declarations/CohortFlushDeclaration.sol1.29 KB
- src/diamond/vault/declarations/CohortSelfDeclaration.sol575 B
- src/diamond/vault/declarations/CohortSelfLogDeclaration.sol1.2 KB
- src/diamond/vault/declarations/PayoutHubPointerDeclaration.sol611 B
- src/diamond/vault/declarations/ReferralPayoutDeclaration.sol465 B
- src/diamond/vault/declarations/ReferralRegistryDeclaration.sol415 B
- src/diamond/vault/declarations/ReferralRegistryPointerDeclaration.sol596 B
- src/diamond/vault/facets/CohortFlushPlanner.sol19.48 KB
- src/diamond/vault/facets/CohortFlushTransport.sol14.59 KB
- src/diamond/vault/facets/CohortPinnedBase.sol6.61 KB
- src/diamond/vault/interfaces/IReferralFlushHub.sol798 B
- src/diamond/vault/interfaces/IReferralRegistry.sol1.94 KB
src/diamond/vault/facets/CohortFlushFacet.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {IRouterClient} from "@chainlink/contracts-ccip/contracts/interfaces/IRouterClient.sol";
import {CohortFlushTransport} from "./CohortFlushTransport.sol";
import {CohortFlushCodec} from "../../shared/CohortFlushCodec.sol";
import {CohortWeeks} from "../../shared/CohortWeeks.sol";
/**
* @dev CohortFlushFacet: the referral flush entrypoints of a vault. A batch
* flush or a single referrer window settles the books, plans the entries
* and sends one envelope to the referral hub. A batch of more than one
* referrer takes only books whose settle would cross no week boundary
* (settled to the current week, or to the disarm instant while the book is
* parked; anyone advances a book with the permissionless `advanceBook`), so
* one call never walks more than one book's week boundaries; a single
* referrer settles inline. Only the batch lets an allowed flush bot open a
* book whose cursors are unset; the window never writes a cursor for
* anyone but the referrer. The quote and preview views are no-settle lower
* bounds and stay ungated.
*/
contract CohortFlushFacet is CohortFlushTransport {
function flushReferrals(
address[] calldata _referrers
)
external
payable
onlyDelegateCall
whenNotPaused
nonReentrant
{
_checkFlushBatch(
_referrers.length
);
_checkFlushArmed();
uint256 currentWeek = block.timestamp
/ CohortWeeks.WEEK;
for (uint256 i; i < _referrers.length; ++i) {
_checkFlushCaller(
_referrers[i]
);
if (_referrers.length > 1) {
_checkBookAdvanced(
_referrers[i]
);
}
_settleBeforePlan(
_referrers[i]
);
uint256 gapCursor = flushGapCursor[_referrers[i]];
_checkFlushOutageGate(
_referrers[i],
_cursorFromWeek(
_referrers[i],
currentWeek
),
gapCursor & CohortWeeks.CARRY_HALF_MASK,
gapCursor >> FLUSH_GAP_CURSOR_WEEK_SHIFT
);
}
FlushEntryData[] memory entries = _planFlushBatch(
_referrers
);
_commitFlush(
entries,
true
);
}
function flushReferralWindow(
address _referrer,
uint256 _fromWeek,
uint256 _fromGapIndex
)
external
payable
onlyDelegateCall
whenNotPaused
nonReentrant
{
require(
flushHub != ZERO_ADDRESS,
FlushHubNotSet()
);
_checkFlushArmed();
_checkFlushCaller(
_referrer
);
require(
_fromWeek <= block.timestamp / CohortWeeks.WEEK,
FlushWindowInvalid()
);
require(
_fromGapIndex <= cohortGapLog[_referrer].length,
FlushWindowInvalid()
);
_checkWindowStart(
_referrer,
_fromWeek,
_fromGapIndex
);
_settleBeforePlan(
_referrer
);
uint256 windowGapResume = _windowGapResumeWeek(
_referrer,
_fromGapIndex
);
_checkFlushOutageGate(
_referrer,
_fromWeek,
_fromGapIndex,
windowGapResume
);
FlushEntryData[] memory entries = new FlushEntryData[](1);
entries[0] = _planFlushEntry(
_referrer,
_fromWeek,
_fromGapIndex,
windowGapResume,
_flushWorkBudget()
);
_commitFlush(
entries,
false
);
}
function quoteFlushFee(
address[] calldata _referrers
)
external
view
returns (uint256)
{
_checkFlushBatch(
_referrers.length
);
if (flushHubChainSelector == 0) {
return 0;
}
require(
ccipRouter != ZERO_ADDRESS,
RouterNotSet()
);
FlushEntryData[] memory entries = _planFlushBatch(
_referrers
);
return IRouterClient(ccipRouter).getFee(
flushHubChainSelector,
_buildFlushMessage(
flushHub,
_packFlushEnvelope(
entries
)
)
);
}
function previewFlushEnvelope(
address[] calldata _referrers
)
external
view
returns (bytes memory)
{
_checkFlushBatch(
_referrers.length
);
return _packFlushEnvelope(
_planFlushBatch(
_referrers
)
);
}
}
node_modules/@chainlink/contracts-ccip/contracts/interfaces/IRouterClient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {Client} from "../libraries/Client.sol";
interface IRouterClient {
error UnsupportedDestinationChain(uint64 destChainSelector);
error InsufficientFeeTokenAmount();
error InvalidMsgValue();
/// @notice Checks if the given chain ID is supported for sending/receiving.
/// @param destChainSelector The chain to check.
/// @return supported is true if it is supported, false if not.
function isChainSupported(
uint64 destChainSelector
) external view returns (bool supported);
/// @param destinationChainSelector The destination chainSelector.
/// @param message The cross-chain CCIP message including data and/or tokens.
/// @return fee returns execution fee for the message.
/// delivery to destination chain, denominated in the feeToken specified in the message.
/// @dev Reverts with appropriate reason upon invalid message.
function getFee(
uint64 destinationChainSelector,
Client.EVM2AnyMessage memory message
) external view returns (uint256 fee);
/// @notice Request a message to be sent to the destination chain.
/// @param destinationChainSelector The destination chain ID.
/// @param message The cross-chain CCIP message including data and/or tokens.
/// @return messageId The message ID.
/// @dev Note if msg.value is larger than the required fee (from getFee) we accept.
/// the overpayment with no refund.
/// @dev Reverts with appropriate reason upon invalid message.
function ccipSend(
uint64 destinationChainSelector,
Client.EVM2AnyMessage calldata message
) external payable returns (bytes32);
}
node_modules/@chainlink/contracts-ccip/contracts/libraries/Client.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// End consumer library.
library Client {
/// @dev RMN depends on this struct, if changing, please notify the RMN maintainers.
struct EVMTokenAmount {
address token; // token address on the local chain.
uint256 amount; // Amount of tokens.
}
struct Any2EVMMessage {
bytes32 messageId; // MessageId corresponding to ccipSend on source.
uint64 sourceChainSelector; // Source chain selector.
bytes sender; // abi.decode(sender) if coming from an EVM chain.
bytes data; // payload sent in original message.
EVMTokenAmount[] destTokenAmounts; // Tokens and their amounts in their destination chain representation.
}
// If extraArgs is empty bytes, the default is 200k gas limit.
struct EVM2AnyMessage {
bytes receiver; // abi.encode(receiver address) for dest EVM chains.
bytes data; // Data payload.
EVMTokenAmount[] tokenAmounts; // Token transfers.
address feeToken; // Address of feeToken. address(0) means you will send msg.value.
bytes extraArgs; // Populate this with _argsToBytes(EVMExtraArgsV2).
}
// Tag to indicate only a gas limit. Only usable for EVM as destination chain.
bytes4 public constant EVM_EXTRA_ARGS_V1_TAG = 0x97a657c9;
struct EVMExtraArgsV1 {
uint256 gasLimit;
}
function _argsToBytes(
EVMExtraArgsV1 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(EVM_EXTRA_ARGS_V1_TAG, extraArgs);
}
// Tag to indicate a gas limit (or dest chain equivalent processing units) and Out Of Order Execution. This tag is
// available for multiple chain families. If there is no chain family specific tag, this is the default available
// for a chain.
// Note: not available for Solana VM based chains.
bytes4 public constant GENERIC_EXTRA_ARGS_V2_TAG = 0x181dcf10;
/// @param gasLimit: gas limit for the callback on the destination chain.
/// @param allowOutOfOrderExecution: if true, it indicates that the message can be executed in any order relative to
/// other messages from the same sender. This value's default varies by chain. On some chains, a particular value is
/// enforced, meaning if the expected value is not set, the message request will revert.
/// @dev Fully compatible with the previously existing EVMExtraArgsV2.
struct GenericExtraArgsV2 {
uint256 gasLimit;
bool allowOutOfOrderExecution;
}
// Extra args tag for chains that use the Solana VM.
bytes4 public constant SVM_EXTRA_ARGS_V1_TAG = 0x1f3b3aba;
struct SVMExtraArgsV1 {
uint32 computeUnits;
uint64 accountIsWritableBitmap;
bool allowOutOfOrderExecution;
bytes32 tokenReceiver;
// Additional accounts needed for execution of CCIP receiver. Must be empty if message.receiver is zero.
// Token transfer related accounts are specified in the token pool lookup table on SVM.
bytes32[] accounts;
}
/// @dev The maximum number of accounts that can be passed in SVMExtraArgs.
uint256 public constant SVM_EXTRA_ARGS_MAX_ACCOUNTS = 64;
/// @dev The expected static payload size of a token transfer when Borsh encoded and submitted to SVM.
/// TokenPool extra data and offchain data sizes are dynamic, and should be accounted for separately.
uint256 public constant SVM_TOKEN_TRANSFER_DATA_OVERHEAD = (4 + 32) // source_pool
+ 32 // token_address
+ 4 // gas_amount
+ 4 // extra_data overhead
+ 32 // amount
+ 32 // size of the token lookup table account
+ 32 // token-related accounts in the lookup table, over-estimated to 32, typically between 11 - 13
+ 32 // token account belonging to the token receiver, e.g ATA, not included in the token lookup table
+ 32 // per-chain token pool config, not included in the token lookup table
+ 32 // per-chain token billing config, not always included in the token lookup table
+ 32; // OffRamp pool signer PDA, not included in the token lookup table
/// @dev Number of overhead accounts needed for message execution on SVM.
/// @dev These are message.receiver, and the OffRamp Signer PDA specific to the receiver.
uint256 public constant SVM_MESSAGING_ACCOUNTS_OVERHEAD = 2;
/// @dev The size of each SVM account address in bytes.
uint256 public constant SVM_ACCOUNT_BYTE_SIZE = 32;
function _argsToBytes(
GenericExtraArgsV2 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(GENERIC_EXTRA_ARGS_V2_TAG, extraArgs);
}
function _svmArgsToBytes(
SVMExtraArgsV1 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(SVM_EXTRA_ARGS_V1_TAG, extraArgs);
}
}
node_modules/@openzeppelin/contracts/security/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}
src/diamond/shared/CohortFlushCodec.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {CohortWeeks} from "./CohortWeeks.sol";
/**
* @dev CohortFlushCodec: the envelope a spoke vault sends to the mainnet
* hub, a packed sequence of 32-byte words without ABI framing.
*
* Header `deliverer(160) | flushVersion(8) | crumbVersion(8) |
* entryCount(8) | flushStamp(64)`, bits 248+ zero; the stamp is the
* source build time. Each entry is the entry word `referrer(160) |
* crumbCount(8) | gapCount(8) | flags(8) | selfRunCount(8)`, bits 192+
* zero, flag bit 0 marking a designation word; the optional designation
* word `payout(160) | setAt(64) | chainRank(8)`, bits 232+ zero; then
* `selfRunCount` self runs `fromWeek(32) | toWeekExclusive(32) |
* selfAverage(80)`, bits 144+ zero, each a span of closed weeks with one
* realised weekly self average; then `crumbCount` pairs of (week, raw
* crumb word) and `gapCount` raw gap records. A week's referred average
* is read by the hub from that week's own crumb or gap record. The
* builder and the hub both enforce 1 to MAX_FLUSH_ENTRIES entries and at
* most MAX_FLUSH_WORK work units, a crumb, a self week and a gap week
* costing one each.
*/
library CohortFlushCodec {
uint256 internal constant FLUSH_VERSION = 2;
uint256 internal constant FLUSH_VERSION_SHIFT = 160;
uint256 internal constant FLUSH_CRUMB_VERSION_SHIFT = 168;
uint256 internal constant FLUSH_ENTRY_COUNT_SHIFT = 176;
uint256 internal constant FLUSH_STAMP_SHIFT = 184;
uint256 internal constant FLUSH_HEADER_RESERVED_SHIFT = 248;
uint256 internal constant FLUSH_ENTRY_CRUMBS_SHIFT = 160;
uint256 internal constant FLUSH_ENTRY_GAPS_SHIFT = 168;
uint256 internal constant FLUSH_ENTRY_FLAGS_SHIFT = 176;
uint256 internal constant FLUSH_ENTRY_SELF_RUNS_SHIFT = 184;
uint256 internal constant FLUSH_ENTRY_RESERVED_SHIFT = 192;
uint256 internal constant FLUSH_FLAG_DESIGNATION = 1;
uint256 internal constant SELF_RUN_WEEK_MASK = (1 << 32) - 1;
uint256 internal constant SELF_RUN_TO_SHIFT = 32;
uint256 internal constant SELF_RUN_AVERAGE_SHIFT = 64;
uint256 internal constant SELF_RUN_RESERVED_SHIFT = 144;
uint256 internal constant FLUSH_DESIGNATION_SET_AT_SHIFT = 160;
uint256 internal constant FLUSH_DESIGNATION_RANK_SHIFT = 224;
uint256 internal constant FLUSH_DESIGNATION_RESERVED_SHIFT = 232;
uint256 internal constant DESIGNATION_STAMP_SHIFT = 8;
uint256 internal constant MAX_FLUSH_ENTRIES = 16;
// A gas bound: 160 work units measured about 12.5M gas on the worst
// cold apply at the hub, under the EIP-7825 cap of 16,777,216.
uint256 internal constant MAX_FLUSH_WORK = 160;
function _packFlushHeader(
address _deliverer,
uint256 _entryCount,
uint256 _stamp
)
internal
pure
returns (uint256)
{
return uint256(uint160(_deliverer))
| (FLUSH_VERSION << FLUSH_VERSION_SHIFT)
| (CohortWeeks.CRUMB_VERSION << FLUSH_CRUMB_VERSION_SHIFT)
| (_entryCount << FLUSH_ENTRY_COUNT_SHIFT)
| (_stamp << FLUSH_STAMP_SHIFT);
}
function _flushHeaderDeliverer(
uint256 _word
)
internal
pure
returns (address)
{
return address(
uint160(_word)
);
}
function _flushHeaderVersion(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_VERSION_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
function _flushHeaderCrumbVersion(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_CRUMB_VERSION_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
function _flushHeaderEntryCount(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_ENTRY_COUNT_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
function _flushHeaderStamp(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_STAMP_SHIFT) & CohortWeeks.RING_LANE_MAX;
}
function _packFlushEntry(
address _referrer,
uint256 _crumbCount,
uint256 _gapCount,
uint256 _flags,
uint256 _selfRunCount
)
internal
pure
returns (uint256)
{
return uint256(uint160(_referrer))
| (_crumbCount << FLUSH_ENTRY_CRUMBS_SHIFT)
| (_gapCount << FLUSH_ENTRY_GAPS_SHIFT)
| (_flags << FLUSH_ENTRY_FLAGS_SHIFT)
| (_selfRunCount << FLUSH_ENTRY_SELF_RUNS_SHIFT);
}
function _flushEntrySelfRunCount(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_ENTRY_SELF_RUNS_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
function _flushEntryReferrer(
uint256 _word
)
internal
pure
returns (address)
{
return address(
uint160(_word)
);
}
function _flushEntryCrumbCount(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_ENTRY_CRUMBS_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
function _flushEntryGapCount(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_ENTRY_GAPS_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
function _flushEntryFlags(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_ENTRY_FLAGS_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
function _packSelfRun(
uint256 _fromWeek,
uint256 _toWeekExclusive,
uint256 _selfAverage
)
internal
pure
returns (uint256)
{
return _fromWeek
| (_toWeekExclusive << SELF_RUN_TO_SHIFT)
| (_selfAverage << SELF_RUN_AVERAGE_SHIFT);
}
function _selfRunFromWeek(
uint256 _run
)
internal
pure
returns (uint256)
{
return _run & SELF_RUN_WEEK_MASK;
}
function _selfRunToWeek(
uint256 _run
)
internal
pure
returns (uint256)
{
return (_run >> SELF_RUN_TO_SHIFT) & SELF_RUN_WEEK_MASK;
}
function _selfRunAverage(
uint256 _run
)
internal
pure
returns (uint256)
{
return (_run >> SELF_RUN_AVERAGE_SHIFT) & CohortWeeks.LANE_MASK_80;
}
function _packFlushDesignation(
address _payout,
uint256 _setAt,
uint256 _rank
)
internal
pure
returns (uint256)
{
return uint256(uint160(_payout))
| (_setAt << FLUSH_DESIGNATION_SET_AT_SHIFT)
| (_rank << FLUSH_DESIGNATION_RANK_SHIFT);
}
function _flushDesignationPayout(
uint256 _word
)
internal
pure
returns (address)
{
return address(
uint160(_word)
);
}
function _flushDesignationSetAt(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_DESIGNATION_SET_AT_SHIFT) & CohortWeeks.RING_LANE_MAX;
}
function _flushDesignationRank(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> FLUSH_DESIGNATION_RANK_SHIFT) & CohortWeeks.CARRY_BYTE_MASK;
}
}
src/diamond/shared/CohortWeeks.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev CohortWeeks: the week epoch, lane geometry and carry codecs of the
* referral cohort recorder, shared by the vault facets and the hub so no
* contract restates these numbers (`week = timestamp / WEEK`).
*
* The book word and every crumb word hold three 80-bit lanes (year-1,
* year-2, mature); a crumb word also sets bit 252 when written, and its
* format is frozen because the hub prices it. Ring slots pack four uint64
* lanes per storage word. The saturating helpers return the clipped
* remainder and never revert, since they run inside the transfer hook.
*
* Same-chain carry (moves only, staged and consumed in one transaction):
* word0 `referrer(160) | version(8) | pairCount(8)`, word1
* `trackedDelta(128) | mature(128)`, then two pairs per word, a pair being
* `amount(64) | slot(8) | ring(8)`. Bridge carry (cross-chain only), three
* header words `referrer(160) | version(8) | captureWeek(32) |
* pairCount(8)`, `trackedDelta(128) | assignedAt(64) | originRank(8)` and
* `mature(128)`, then the pairs two per word in the same pair format.
* `_bridgeCarryValid` rejects a payload wholesale unless its length and
* layout hold, every reserved bit is zero, its lanes sum to at most
* trackedDelta and trackedDelta is at most the amount the same message
* mints. Every carried pair lands at the slot of its own credit week,
* aged only by the week boundaries crossed between capture and landing
* (`_landedCarryPair`), so a relocation never changes a cohort's age. A
* destination clock behind the capture week takes the lag off the age,
* floored at zero: a slot ahead of the destination week is the one its
* next boundary graduates, so only credit younger than the lag lands in
* the destination's current week.
*
* Self crumb word: `currentWeekSeconds(80) | previousWeekSeconds(80) |
* settledAt(64)`. It is settled before every change of the tracked
* contribution, which keeps the completed previous week exact.
*/
library CohortWeeks {
uint256 internal constant WEEK = 1 weeks;
uint256 internal constant RING_SLOTS = 52;
// The 52-week year, the divisor of the commission rate: a rate is per
// 52 weeks, the length of one ring year, so every full ring year pays
// exactly the stated rate.
uint256 internal constant YEAR = RING_SLOTS * WEEK;
uint256 internal constant MAX_SETTLE_BOUNDARIES = 104;
uint256 internal constant LANE_MASK_80 = (1 << 80) - 1;
uint256 internal constant LANE_Y2_SHIFT = 80;
uint256 internal constant LANE_M_SHIFT = 160;
uint256 internal constant SELF_STAMP_SHIFT = 160;
uint256 internal constant SELF_STAMP_MASK = (1 << 64) - 1;
uint256 internal constant CRUMB_WRITTEN_BIT = 1 << 252;
uint256 internal constant CRUMB_VERSION = 1;
uint256 internal constant GAP_TO_SHIFT = 32;
uint256 internal constant GAP_MATURE_SHIFT = 64;
uint256 internal constant RING_LANE_MAX = type(uint64).max;
uint256 internal constant CARRY_VERSION = 1;
uint256 internal constant MAX_CARRY_PAIRS = 104;
uint256 internal constant MAX_CARRY_WORDS = 54;
uint256 internal constant CARRY_RING_YEAR1 = 0;
uint256 internal constant CARRY_RING_YEAR2 = 1;
uint256 internal constant CARRY_VERSION_SHIFT = 160;
uint256 internal constant CARRY_PAIR_COUNT_SHIFT = 168;
uint256 internal constant CARRY_BYTE_MASK = 0xff;
uint256 internal constant CARRY_HALF_SHIFT = 128;
uint256 internal constant CARRY_HALF_MASK = (1 << 128) - 1;
uint256 internal constant CARRY_PAIR_SLOT_SHIFT = 64;
uint256 internal constant CARRY_PAIR_RING_SHIFT = 72;
uint256 internal constant CARRY_PAIR_RESERVED_SHIFT = 80;
uint256 internal constant CARRY_LANE_MATURE = 2;
uint256 internal constant BRIDGE_CARRY_VERSION = 3;
uint256 internal constant BRIDGE_CARRY_HEADER_WORDS = 3;
uint256 internal constant BRIDGE_CARRY_HEADER_BYTES = 96;
// The longest bridge carry: three header words and 104 pairs.
uint256 internal constant BRIDGE_CARRY_BYTES = 1_760;
uint256 internal constant BRIDGE_CARRY_PAIR_COUNT_SHIFT = 200;
uint256 internal constant BRIDGE_CARRY_ASSIGNED_AT_SHIFT = 128;
uint256 internal constant BRIDGE_CARRY_RANK_SHIFT = 192;
uint256 internal constant BRIDGE_CARRY_CAPTURE_WEEK_SHIFT = 168;
uint256 internal constant BRIDGE_CARRY_CAPTURE_WEEK_MASK = (1 << 32) - 1;
uint256 internal constant BRIDGE_CARRY_ENVELOPE_RESERVED_SHIFT = 208;
uint256 internal constant BRIDGE_CARRY_TRACKED_RESERVED_SHIFT = 200;
uint256 internal constant SELF_LOG_WEEK_MASK = (1 << 32) - 1;
uint256 internal constant SELF_LOG_SECONDS_SHIFT = 32;
uint256 internal constant SELF_LOG_STAKE_SHIFT = 112;
function _packCarryEnvelope(
address _referrer,
uint256 _pairCount
)
internal
pure
returns (uint256)
{
return uint256(uint160(_referrer))
| (CARRY_VERSION << CARRY_VERSION_SHIFT)
| (_pairCount << CARRY_PAIR_COUNT_SHIFT);
}
function _carryEnvelopeReferrer(
uint256 _word
)
internal
pure
returns (address)
{
return address(
uint160(_word)
);
}
function _carryEnvelopeVersion(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> CARRY_VERSION_SHIFT) & CARRY_BYTE_MASK;
}
function _carryEnvelopePairCount(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> CARRY_PAIR_COUNT_SHIFT) & CARRY_BYTE_MASK;
}
function _packCarryAmounts(
uint256 _trackedDelta,
uint256 _mature
)
internal
pure
returns (uint256)
{
return _trackedDelta
| (_mature << CARRY_HALF_SHIFT);
}
function _carryTrackedDelta(
uint256 _word
)
internal
pure
returns (uint256)
{
return _word & CARRY_HALF_MASK;
}
function _carryMature(
uint256 _word
)
internal
pure
returns (uint256)
{
return _word >> CARRY_HALF_SHIFT;
}
function _packCarryPair(
uint256 _amount,
uint256 _slot,
uint256 _ring
)
internal
pure
returns (uint256)
{
return _amount
| (_slot << CARRY_PAIR_SLOT_SHIFT)
| (_ring << CARRY_PAIR_RING_SHIFT);
}
function _carryPairAmount(
uint256 _pair
)
internal
pure
returns (uint256)
{
return _pair & RING_LANE_MAX;
}
function _carryPairSlot(
uint256 _pair
)
internal
pure
returns (uint256)
{
return (_pair >> CARRY_PAIR_SLOT_SHIFT) & CARRY_BYTE_MASK;
}
function _carryPairRing(
uint256 _pair
)
internal
pure
returns (uint256)
{
return (_pair >> CARRY_PAIR_RING_SHIFT) & CARRY_BYTE_MASK;
}
function _packCarryPairsWord(
uint256 _pairLo,
uint256 _pairHi
)
internal
pure
returns (uint256)
{
return _pairLo
| (_pairHi << CARRY_HALF_SHIFT);
}
function _carryPairLo(
uint256 _word
)
internal
pure
returns (uint256)
{
return _word & CARRY_HALF_MASK;
}
function _carryPairHi(
uint256 _word
)
internal
pure
returns (uint256)
{
return _word >> CARRY_HALF_SHIFT;
}
function _packBridgeCarryEnvelope(
address _referrer,
uint256 _captureWeek,
uint256 _pairCount
)
internal
pure
returns (uint256)
{
return uint256(uint160(_referrer))
| (BRIDGE_CARRY_VERSION << CARRY_VERSION_SHIFT)
| (_captureWeek << BRIDGE_CARRY_CAPTURE_WEEK_SHIFT)
| (_pairCount << BRIDGE_CARRY_PAIR_COUNT_SHIFT);
}
function _packBridgeCarryTracked(
uint256 _trackedDelta,
uint256 _assignedAt,
uint256 _rank
)
internal
pure
returns (uint256)
{
return _trackedDelta
| (_assignedAt << BRIDGE_CARRY_ASSIGNED_AT_SHIFT)
| (_rank << BRIDGE_CARRY_RANK_SHIFT);
}
function _bridgeCarryAssignedAt(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> BRIDGE_CARRY_ASSIGNED_AT_SHIFT) & RING_LANE_MAX;
}
function _bridgeCarryRank(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> BRIDGE_CARRY_RANK_SHIFT) & CARRY_BYTE_MASK;
}
function _bridgeCarryCaptureWeek(
uint256 _word0
)
internal
pure
returns (uint256)
{
return (_word0 >> BRIDGE_CARRY_CAPTURE_WEEK_SHIFT) & BRIDGE_CARRY_CAPTURE_WEEK_MASK;
}
function _bridgeCarryPairCount(
uint256 _word0
)
internal
pure
returns (uint256)
{
return (_word0 >> BRIDGE_CARRY_PAIR_COUNT_SHIFT) & CARRY_BYTE_MASK;
}
function _packBridgeCarry(
uint256[] memory _words
)
internal
pure
returns (bytes memory)
{
return abi.encodePacked(
_words
);
}
function _unpackBridgeCarry(
bytes memory _data
)
internal
pure
returns (uint256[] memory words)
{
words = new uint256[](
_data.length / 32
);
for (uint256 i; i < words.length; ++i) {
uint256 word;
assembly {
word := mload(add(_data, mul(add(i, 1), 0x20)))
}
words[i] = word;
}
}
function _carryPairOf(
uint256[] memory _words,
uint256 _firstPairWord,
uint256 _index
)
internal
pure
returns (uint256)
{
uint256 word = _words[_firstPairWord + _index / 2];
return _index % 2 == 0
? _carryPairLo(
word
)
: _carryPairHi(
word
);
}
function _carryPairSums(
uint256[] memory _words,
uint256 _firstPairWord,
uint256 _pairCount
)
internal
pure
returns (
uint256 year1,
uint256 year2
)
{
for (uint256 i; i < _pairCount; ++i) {
uint256 pair = _carryPairOf(
_words,
_firstPairWord,
i
);
if (_carryPairRing(pair) == CARRY_RING_YEAR1) {
year1 += _carryPairAmount(
pair
);
} else {
year2 += _carryPairAmount(
pair
);
}
}
}
function _carryPairsValid(
uint256[] memory _words,
uint256 _firstPairWord,
uint256 _pairCount,
uint256 _laneSum,
bool _checkReserved
)
internal
pure
returns (
bool ok,
uint256 laneSum
)
{
laneSum = _laneSum;
if (
_pairCount % 2 == 1
&& _carryPairHi(_words[_words.length - 1]) != 0
) {
return (
false,
_laneSum
);
}
for (uint256 i; i < _pairCount; ++i) {
uint256 pair = _carryPairOf(
_words,
_firstPairWord,
i
);
if (
_checkReserved
&& pair >> CARRY_PAIR_RESERVED_SHIFT != 0
) {
return (
false,
_laneSum
);
}
if (
_carryPairSlot(pair) >= RING_SLOTS
|| _carryPairRing(pair) > CARRY_RING_YEAR2
) {
return (
false,
_laneSum
);
}
laneSum += _carryPairAmount(
pair
);
}
return (
true,
laneSum
);
}
function _bridgeCarryValid(
bytes memory _data,
uint256 _mintAmount
)
internal
pure
returns (bool)
{
if (
_data.length < BRIDGE_CARRY_HEADER_BYTES
|| _data.length > BRIDGE_CARRY_BYTES
|| _data.length % 32 != 0
) {
return false;
}
uint256[] memory words = _unpackBridgeCarry(
_data
);
uint256 pairCount = _bridgeCarryPairCount(
words[0]
);
if (
_carryEnvelopeVersion(words[0]) != BRIDGE_CARRY_VERSION
|| words[0] >> BRIDGE_CARRY_ENVELOPE_RESERVED_SHIFT != 0
|| words[1] >> BRIDGE_CARRY_TRACKED_RESERVED_SHIFT != 0
|| words[2] >> CARRY_HALF_SHIFT != 0
|| words.length != BRIDGE_CARRY_HEADER_WORDS + (pairCount + 1) / 2
) {
return false;
}
(
bool pairsOk,
uint256 laneSum
) = _carryPairsValid(
words,
BRIDGE_CARRY_HEADER_WORDS,
pairCount,
words[2],
true
);
if (pairsOk == false) {
return false;
}
uint256 trackedDelta = _carryTrackedDelta(
words[1]
);
if (_carryEnvelopeReferrer(words[0]) == address(0)) {
if (laneSum != 0 || pairCount != 0) {
return false;
}
} else {
if (laneSum > trackedDelta) {
return false;
}
}
if (trackedDelta == 0 && laneSum == 0) {
return false;
}
return trackedDelta <= _mintAmount;
}
function _landedCarryPair(
uint256 _pair,
uint256 _captureWeek,
uint256 _arrivalWeek
)
internal
pure
returns (
uint256 slot,
uint256 lane
)
{
uint256 age = (_captureWeek + RING_SLOTS - _carryPairSlot(_pair)) % RING_SLOTS
+ _carryPairRing(_pair) * RING_SLOTS;
if (_arrivalWeek > _captureWeek) {
age += _arrivalWeek - _captureWeek;
}
if (_captureWeek > _arrivalWeek) {
uint256 lag = _captureWeek - _arrivalWeek;
age = age > lag
? age - lag
: 0;
}
if (age >= 2 * RING_SLOTS) {
return (
0,
CARRY_LANE_MATURE
);
}
return (
(_arrivalWeek + 2 * RING_SLOTS - age) % RING_SLOTS,
age / RING_SLOTS
);
}
function _packSelfLogRecord(
uint256 _fromWeek,
uint256 _completedSeconds,
uint256 _stake
)
internal
pure
returns (uint256)
{
return _fromWeek
| (_completedSeconds << SELF_LOG_SECONDS_SHIFT)
| (_stake << SELF_LOG_STAKE_SHIFT);
}
function _selfLogFromWeek(
uint256 _record
)
internal
pure
returns (uint256)
{
return _record & SELF_LOG_WEEK_MASK;
}
function _selfLogSeconds(
uint256 _record
)
internal
pure
returns (uint256)
{
return (_record >> SELF_LOG_SECONDS_SHIFT) & LANE_MASK_80;
}
function _selfLogStake(
uint256 _record
)
internal
pure
returns (uint256)
{
return (_record >> SELF_LOG_STAKE_SHIFT) & LANE_MASK_80;
}
function _packGapRecord(
uint256 _fromWeek,
uint256 _toWeekExclusive,
uint256 _mature
)
internal
pure
returns (uint256)
{
return _fromWeek
| (_toWeekExclusive << GAP_TO_SHIFT)
| (_mature << GAP_MATURE_SHIFT);
}
function _gapRecordFromWeek(
uint256 _record
)
internal
pure
returns (uint256)
{
return _record & ((1 << GAP_TO_SHIFT) - 1);
}
function _gapRecordToWeek(
uint256 _record
)
internal
pure
returns (uint256)
{
return (_record >> GAP_TO_SHIFT) & ((1 << GAP_TO_SHIFT) - 1);
}
function _gapRecordMature(
uint256 _record
)
internal
pure
returns (uint256)
{
return (_record >> GAP_MATURE_SHIFT) & LANE_MASK_80;
}
function _laneY1(
uint256 _word
)
internal
pure
returns (uint256)
{
return _word & LANE_MASK_80;
}
function _laneY2(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> LANE_Y2_SHIFT) & LANE_MASK_80;
}
function _laneM(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> LANE_M_SHIFT) & LANE_MASK_80;
}
function _packLanes(
uint256 _y1,
uint256 _y2,
uint256 _m
)
internal
pure
returns (uint256)
{
return _y1
| (_y2 << LANE_Y2_SHIFT)
| (_m << LANE_M_SHIFT);
}
function _saturatingAddCapped(
uint256 _lane,
uint256 _add,
uint256 _cap
)
internal
pure
returns (
uint256 result,
uint256 clipped
)
{
uint256 sum = _lane + _add;
if (sum > _cap) {
return (
_cap,
sum - _cap
);
}
return (
sum,
0
);
}
function _saturatingAdd80(
uint256 _lane,
uint256 _add
)
internal
pure
returns (
uint256 result,
uint256 clipped
)
{
return _saturatingAddCapped(
_lane,
_add,
LANE_MASK_80
);
}
function _saturatingAdd64(
uint256 _lane,
uint256 _add
)
internal
pure
returns (
uint256 result,
uint256 clipped
)
{
return _saturatingAddCapped(
_lane,
_add,
RING_LANE_MAX
);
}
function _saturatingSub(
uint256 _value,
uint256 _sub
)
internal
pure
returns (
uint256 result,
uint256 clipped
)
{
if (_sub > _value) {
return (
0,
_sub - _value
);
}
return (
_value - _sub,
0
);
}
function _clampLane80(
uint256 _value
)
internal
pure
returns (uint256)
{
return _value < LANE_MASK_80
? _value
: LANE_MASK_80;
}
function _packSelfCrumb(
uint256 _currentSeconds,
uint256 _previousSeconds,
uint256 _settledAt
)
internal
pure
returns (uint256)
{
return _currentSeconds
| (_previousSeconds << LANE_Y2_SHIFT)
| (_settledAt << SELF_STAMP_SHIFT);
}
function _selfCrumbCurrent(
uint256 _word
)
internal
pure
returns (uint256)
{
return _word & LANE_MASK_80;
}
function _selfCrumbPrevious(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> LANE_Y2_SHIFT) & LANE_MASK_80;
}
function _selfCrumbSettledAt(
uint256 _word
)
internal
pure
returns (uint256)
{
return (_word >> SELF_STAMP_SHIFT) & SELF_STAMP_MASK;
}
function _settleSelfCrumb(
uint256 _word,
uint256 _tracked,
uint256 _to
)
internal
pure
returns (uint256)
{
uint256 settledAt = _selfCrumbSettledAt(
_word
);
if (settledAt >= _to) {
return _word;
}
uint256 stake = _clampLane80(
_tracked
);
uint256 fromWeek = settledAt / WEEK;
uint256 toWeek = _to / WEEK;
uint256 current = _selfCrumbCurrent(
_word
);
uint256 previous = _selfCrumbPrevious(
_word
);
if (toWeek == fromWeek) {
current = _clampLane80(
current + stake * (_to - settledAt)
);
} else {
previous = _completedPreviousSeconds(
current,
stake,
settledAt,
toWeek
);
current = _clampLane80(
stake * (_to - toWeek * WEEK)
);
}
return _packSelfCrumb(
current,
previous,
_to
);
}
function _completedPreviousSeconds(
uint256 _current,
uint256 _stake,
uint256 _settledAt,
uint256 _week
)
internal
pure
returns (uint256)
{
if (_settledAt / WEEK + 1 == _week) {
return _clampLane80(
_current + _stake * (_week * WEEK - _settledAt)
);
}
return _clampLane80(
_stake * WEEK
);
}
function _liveSecondsCohort(
uint256 _from,
uint256 _to,
uint256 _disarmedAt,
uint256 _rearmedAt
)
internal
pure
returns (uint256)
{
uint256 skipFrom = _from > _disarmedAt
? _from
: _disarmedAt;
uint256 skipTo = _to < _rearmedAt
? _to
: _rearmedAt;
if (skipTo <= skipFrom) {
return _to - _from;
}
return _to
- _from
- (skipTo - skipFrom);
}
}
src/diamond/shared/DiamondErrors.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Errors for the diamond proxy machinery — selector routing
* and lifecycle.
*/
error FacetNotFound();
error AlreadyInitialized();
error NoSelectorChangeQueued();
error SelectorTimelockNotElapsed();
error OnlyDelegateCall();
error NestedMulticall();
src/diamond/shared/OwnableMaster.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
error NoValue();
error NotMaster();
error NotProposed();
/**
* @dev Two-step ownership transfer, ported verbatim from
* `src/legacy/OwnableMasterLegacy.sol`. Storage layout is identical
* (slots 0 and 1) so a diamond inheriting this contract reproduces
* the legacy slot ordering for the master/proposedMaster pair.
*/
contract OwnableMaster {
address public master;
address public proposedMaster;
address internal constant ZERO_ADDRESS = address(0x0);
event MasterProposed(
address indexed proposer,
address indexed proposedMaster
);
event RenouncedOwnership(
address indexed previousMaster
);
modifier onlyProposed() {
_onlyProposed();
_;
}
modifier onlyMaster() {
_onlyMaster();
_;
}
function _onlyMaster()
private
view
{
if (msg.sender == master) {
return;
}
revert NotMaster();
}
function _onlyProposed()
private
view
{
if (msg.sender == proposedMaster) {
return;
}
revert NotProposed();
}
constructor(
address _master
) {
if (_master == ZERO_ADDRESS) {
revert NoValue();
}
master = _master;
}
function proposeOwner(
address _proposedOwner
)
external
onlyMaster
{
if (_proposedOwner == ZERO_ADDRESS) {
revert NoValue();
}
proposedMaster = _proposedOwner;
emit MasterProposed(
msg.sender,
_proposedOwner
);
}
function claimOwnership()
external
onlyProposed
{
master = msg.sender;
}
function renounceOwnership()
external
onlyMaster
{
master = ZERO_ADDRESS;
proposedMaster = ZERO_ADDRESS;
emit RenouncedOwnership(
msg.sender
);
}
}
src/diamond/vault/WiseTelecomNodesDiamondErrors.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Custom errors for the WiseTelecomNodes diamond. Selectors match
* the legacy error ABI so reverts decode identically.
*/
abstract contract WiseTelecomNodesDiamondErrors {
error NoRewards();
error NoInterest();
error InvalidValue();
error InvalidPosition();
error DepositExceedCap();
error DepositCapBelowSupply();
error DepositsDisabled();
error InterestRateTooHigh();
error OldVaultNoCode();
error OldVaultBadResponse();
error InsufficientBalance();
error SupplyChangeNotAllowed();
error InsufficientInterest();
error InterestRateProxyAlreadySet();
error NotInterestRateProxy();
error NotHookExecution();
error NoOverhang();
error NotSweeper();
error NoWorkerChangeProposed();
error WorkerTimelockNotElapsed();
error NoThirdPartyChangeProposed();
error ThirdPartyTimelockNotElapsed();
error NoTransferHookChangeProposed();
error TransferHookTimelockNotElapsed();
error NoDepositHookChangeProposed();
error DepositHookTimelockNotElapsed();
error NoWiseToBurn();
error WiseTokenNotSet();
error WiseBurnCooldownNotElapsed();
error GracePeriodNotElapsed();
error GracePeriodTooLong();
error GraceThresholdTooLow();
error DepositAccumWindowTooLong();
error Permit2NotDeployed();
error PeerVaultNotEnabled();
error NotPeerVault();
error MoveAmountTooSmall();
error SelfPeerNotAllowed();
error InterestRateProxyCannotMove();
error NoPeerVaultChangeProposed();
error PeerVaultTimelockNotElapsed();
// ---- Cross-chain bridge ----
error RouterNotSet();
error RouterAlreadySet();
error NotCcipRouter();
error CrossChainPeerNotEnabled();
error CrossChainPeerMismatch();
error NoCrossChainPeerChangeProposed();
error CrossChainPeerTimelockNotElapsed();
error InsufficientBridgeFee();
error BridgeRefundFailed();
error MessageAlreadyProcessed();
error ReferralDataTooLong();
error InvalidBridgeGasLimit();
// ---- Referral registry ----
error SelfReferral();
error ReferralRegistryNotSet();
error NoReferralRegistryChangeProposed();
error ReferralRegistryTimelockNotElapsed();
error NotReferralRegistry();
error CohortSyncDisabled();
error ReferralDataReserved();
error ReferralRegistryChangeWhileArmed();
// ---- Cohort recorder ----
error CohortHookNotInstalled();
error NothingToSeed();
error SeedingLatched();
// ---- Queue surface ----
error ZeroAmount();
error NotMember();
error MemberAlreadyLeft();
error IncentiveMismatch();
error QueMemberIdTooHigh();
error OrderNotReady();
error AmountTooHigh();
error IncentiveNotAllowed();
error AmountTooLow();
error NotProxyBenefactor();
error AmountReceivedTooLow();
error AmountSpentTooHigh();
error NoOrdersPresent();
error NegativeIncentiveNotAllowed();
error SameIncentive();
error ProtectedToken();
// ---- Auto-compound ----
error NotAutoCompoundBot();
error AutoCompoundNotAllowed();
error AutoCompoundFeeTooHigh();
error ExceedsPendingPayout();
// ---- Cohort flush ----
error FlushHubNotSet();
error NoFlushHubChangeProposed();
error FlushHubTimelockNotElapsed();
error NotFlushBot();
error NothingToFlush();
error FlushBatchTooLarge();
error FlushWindowInvalid();
error InsufficientFlushFee();
error FlushRefundFailed();
error InvalidFlushGasLimit();
error CohortBridgeInOutOfGas(
address user,
uint64 srcChainSelector
);
error FlushOutageGraceActive();
error FlushCadenceActive();
error FlushBookNotAdvanced();
}
src/diamond/vault/WiseTelecomNodesDiamondEvents.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Event signatures for the WiseTelecomNodes diamond. The legacy-
* parity block is byte-equivalent to the legacy event ABI so
* off-chain consumers decode unchanged; diamond-specific events
* are appended at the end.
*/
abstract contract WiseTelecomNodesDiamondEvents {
// ---- Legacy parity events ----
event ProxyBenefactorSet(
address proxyBeneFactor
);
event InterestMoved(
address indexed from,
address indexed to,
uint256 amount
);
event InterestRateProxySet(
address interestRateProxy
);
event SupplyChangeByOwnerNotAllowedSet(
bool supplyChangeByOwnerNotAllowed
);
event MintSupply(
address indexed to,
uint256 amount
);
event BurnSupply(
address indexed from,
uint256 amount
);
event Deposited(
address indexed user,
uint256 amount
);
event ThirdPartyAddressSet(
address thirdPartyAddress
);
event ThirdPartyAddressProposed(
address indexed proposedThirdParty,
uint256 executableAt
);
event ThirdPartyAddressProposalCancelled(
address indexed cancelledThirdParty
);
event TransferHookFacetSet(
address transferHookFacet
);
event TransferHookFacetProposed(
address indexed proposedTransferHookFacet,
uint256 executableAt
);
event TransferHookFacetProposalCancelled(
address indexed cancelledTransferHookFacet
);
event DepositHookFacetSet(
address depositHookFacet
);
event DepositHookFacetProposed(
address indexed proposedDepositHookFacet,
uint256 executableAt
);
event DepositHookFacetProposalCancelled(
address indexed cancelledDepositHookFacet
);
event InterestRateSet(
uint256 interestRate
);
event TotalDepositCapSet(
uint256 totalDepositCap
);
event DepositCapRelocated(
uint256 newTotalDepositCap
);
event DepositsDisabledSet(
bool depositsDisabled
);
event GracePeriodDurationSet(
uint256 gracePeriodDuration
);
event GraceThresholdAmountSet(
uint256 graceThresholdAmount
);
event GraceFreezeEnabledSet(
bool graceFreezeEnabled
);
event LargeDepositRegistered(
address indexed user,
uint256 balanceIncrease,
uint256 graceEndsAt
);
event DepositAccumWindowSet(
uint256 depositAccumWindow
);
event DepositWindowAccumulated(
address indexed user,
uint256 windowTotal,
uint256 windowEndsAt
);
event ClaimInterestSimple(
address indexed user,
uint256 interest
);
event CompoundInterest(
address indexed user,
uint256 interest
);
event ClaimInterestExactAmount(
address indexed user,
uint256 amount
);
event ProxyBalanceIncreased(
address indexed proxyUser,
uint256 amount
);
event ProxyBalanceDecreased(
address indexed proxyUser,
uint256 amount
);
event ProxyBeneFactorSet(
address indexed proxyBeneFactor
);
event InterestRateProxyProposal(
address indexed proxy,
bool isProposing
);
event InterestRateProxyClaimed(
address indexed proxy,
bool isClaimed
);
event WorkerAddressSet(
address indexed worker
);
event WorkerAddressProposed(
address indexed proposedWorker,
uint256 executableAt
);
event WorkerAddressProposalCancelled(
address indexed cancelledWorker
);
event BufferInterestRateRaised(
uint256 newBufferInterestRate
);
event OverhangSwept(
address indexed worker,
address indexed caller,
uint256 amount
);
event TotalCashedInterestChanged(
uint256 totalCashedInterest
);
event CashedInterestSet(
address indexed user,
uint256 previousAmount,
uint256 newAmount
);
event TokenRescued(
address indexed token,
address indexed to,
uint256 amount
);
event SweeperSet(
address indexed sweeper,
bool allowed
);
event WiseBurned(
address indexed caller,
uint256 amount,
uint256 percentageBps
);
event WiseTokenSet(
address wiseToken
);
event PeerVaultSet(
address indexed peer,
bool enabled
);
event PeerVaultProposed(
address indexed peer,
uint256 executableAt
);
event PeerVaultProposalCancelled(
address indexed peer
);
event MovedOut(
address indexed user,
address indexed dstVault,
uint256 srcAmount,
uint256 dstAmount
);
event MovedIn(
address indexed user,
address indexed srcVault,
uint256 amount
);
event MoveDust(
address indexed user,
address indexed dstVault,
uint256 dustAmount
);
// ---- Cross-chain bridge ----
event CcipRouterSet(
address indexed router
);
event CrossChainPeerProposed(
uint64 indexed chainSelector,
address indexed peer,
uint256 executableAt
);
event CrossChainPeerSet(
uint64 indexed chainSelector,
address indexed peer,
bool enabled
);
event CrossChainPeerProposalCancelled(
uint64 indexed chainSelector
);
event BridgeSent(
address indexed user,
uint64 indexed destChainSelector,
uint256 srcAmount,
uint256 dstAmount,
bytes32 messageId
);
event BridgeReceived(
address indexed user,
uint64 indexed srcChainSelector,
uint256 amount,
bytes32 messageId
);
event BridgeReferral(
address indexed user,
uint64 indexed srcChainSelector,
bytes32 indexed messageId,
bytes referralData
);
event ReferralEnabledSet(
bool enabled
);
event BridgeGasLimitSet(
uint256 gasLimit
);
// ---- Referral registry ----
event ReferralRegistrySet(
address referralRegistry
);
event ReferralRegistryProposed(
address indexed proposedReferralRegistry,
uint256 executableAt
);
event ReferralRegistryProposalCancelled(
address indexed cancelledReferralRegistry
);
// ---- Cohort recorder ----
event CohortContributionCredited(
address indexed user,
address indexed referrer,
uint256 amount
);
event CohortContributionSeeded(
address indexed user,
uint256 amount
);
event CohortContributionSynced(
address indexed user,
address indexed referrer,
uint256 oldContribution,
uint256 newContribution
);
event CohortAttributionCharged(
address indexed user,
address indexed referrer,
uint256 charged,
uint256 uncharged
);
event CohortDivestParked(
address indexed user
);
event CohortDivestDrained(
address indexed user
);
event CohortDivestParkSkipped(
address indexed user,
address indexed parked
);
event CohortBookSettled(
address indexed referrer,
uint256 fromTimestamp,
uint256 toTimestamp,
uint256 boundariesWalked
);
event CohortBookReduced(
address indexed referrer,
uint256 amount,
uint256 fromYear1,
uint256 fromYear2,
uint256 fromMature
);
event CohortGapRecorded(
address indexed referrer,
uint256 fromWeek,
uint256 toWeekExclusive,
uint256 maturePrincipal
);
event CohortLaneSaturated(
address indexed referrer,
uint256 laneKind,
uint256 index,
uint256 clippedAmount
);
event CohortReferrerLookupFailed(
address indexed user
);
event CohortSyncEnabledSet(
bool enabled
);
event CohortCarryStaged(
address indexed user,
address indexed dstVault,
address indexed referrer,
uint256 trackedDelta,
uint256 year1,
uint256 year2,
uint256 mature,
uint256 pairCount
);
event CohortCarryApplied(
address indexed user,
address indexed srcVault,
address indexed referrer,
address carriedReferrer,
uint256 trackedDelta,
uint256 year1,
uint256 year2,
uint256 mature,
uint256 pairCount
);
event CohortCarrySkipped(
address indexed user,
address indexed dstVault
);
event CohortCarryDiscarded(
address indexed user,
address indexed srcVault,
uint256 stagedAt
);
event CohortCarryBookDropped(
address indexed user,
address indexed srcVault,
address carriedReferrer,
uint256 trackedDelta,
uint256 mature,
uint256 pairCount
);
event CohortReferrerFlipApplied(
address indexed user,
address indexed oldReferrer,
address indexed newReferrer,
uint256 year1,
uint256 year2,
uint256 mature,
uint256 pairCount
);
event CohortBridgeCarrySent(
address indexed user,
uint64 indexed dstChainSelector,
address indexed referrer,
uint256 trackedDelta,
uint256 year1,
uint256 year2,
uint256 mature,
address bookReferrer
);
event CohortBridgeCarryApplied(
address indexed user,
uint64 indexed srcChainSelector,
address indexed effectiveReferrer,
address carriedReferrer,
uint256 trackedDelta,
uint256 year1,
uint256 year2,
uint256 mature
);
event CohortBridgeCarryDiscarded(
address indexed user,
uint64 indexed srcChainSelector
);
event CohortBridgeCarryBookDropped(
address indexed user,
uint64 indexed srcChainSelector,
address carriedReferrer,
uint256 year1,
uint256 year2,
uint256 mature
);
event CohortBridgeCarrySkipped(
address indexed user,
uint64 indexed dstChainSelector
);
event CohortBridgeHookFailed(
address indexed user,
uint64 indexed srcChainSelector
);
event CohortSelfCrumbSettled(
address indexed user,
uint256 settledAt,
uint256 currentWeekSeconds,
uint256 previousWeekSeconds
);
event CohortDisarmSpanSet(
uint256 disarmedAt,
uint256 rearmedAt
);
event CohortQuarantineReadFailed(
address indexed user,
uint64 indexed srcChainSelector
);
event CohortSelfLogged(
address indexed user,
uint256 fromWeek,
uint256 completedSeconds,
uint256 stake
);
// ---- Queue surface ----
event JoinQue(
address indexed member,
uint256 amount,
int256 incentive,
uint256 queMemberId
);
event LeaveQue(
address indexed member,
uint256 queMemberId,
int256 incentive,
uint256 amount
);
event ReduceQueAmount(
address indexed member,
uint256 queMemberId,
int256 incentive,
uint256 reduceBy
);
event OrderProcessed(
address indexed fulfiller,
address indexed member,
uint256 queMemberId,
int256 incentive,
uint256 amount,
bool isFullFulfill
);
event CompoundViaQueue(
address indexed user,
uint256 interestConsumed,
uint256 vaultTokensReceived,
uint256 remainderCompounded
);
event SwitchQueIncentive(
address indexed member,
uint256 fromId,
int256 fromIncentive,
uint256 toId,
int256 toIncentive,
uint256 amount
);
event SwitchQueIncentivePartial(
address indexed member,
uint256 fromId,
int256 fromIncentive,
uint256 toId,
int256 toIncentive,
uint256 amount
);
// ---- Diamond machinery ----
event SetupFinalized();
event SelectorProposed(
bytes4 indexed selector,
address indexed facet,
uint256 executableAt
);
event SelectorsProposed(
bytes4[] selectors,
address indexed facet,
uint256 executableAt
);
event SelectorUpdated(
bytes4 indexed selector,
address indexed facet
);
event SelectorProposalCancelled(
bytes4 indexed selector
);
event MinDepositAmountChanged(
uint256 minDepositAmount
);
event NegativeIncentivesNotAllowedSet(
bool negativeIncentivesNotAllowed
);
// ---- Auto-compound ----
event CompoundInterestOnBehalf(
address indexed user,
address indexed bot,
uint256 netAmount,
uint256 feeAmount
);
event AutoCompoundBotSet(
address indexed bot,
bool allowed
);
event AutoCompoundAllowedSet(
address indexed user,
bool allowed
);
event AutoCompoundFeeBpsSet(
uint256 autoCompoundFeeBps
);
// ---- Cohort flush ----
event FlushHubSet(
address flushHub,
uint64 flushHubChainSelector
);
event FlushHubProposed(
address indexed proposedFlushHub,
uint64 proposedFlushHubChainSelector,
uint256 executableAt
);
event FlushHubProposalCancelled(
address indexed cancelledFlushHub
);
event FlushBotAllowedSet(
address indexed bot,
bool allowed
);
event PublicFlushEnabledSet(
bool enabled
);
event FlushGasLimitSet(
uint64 flushGasLimit
);
event CohortFlushSent(
bytes32 indexed messageId,
uint64 indexed destChainSelector,
address indexed deliverer,
uint256 entryCount
);
event CohortFlushDelivered(
address indexed flushHub,
address indexed deliverer,
uint256 entryCount
);
event CohortReferrerFlushed(
address indexed referrer,
uint256 flushedThroughWeek,
uint256 flushedGapIndex,
uint256 gapResumeWeek
);
}
src/diamond/vault/declarations/CohortAttributionDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slot 90: `attributedContribution`, the slice of an
* account's tracked contribution that credited a referrer book. A clamp
* charges a book at most min(deficit, attributed), so attributed never
* exceeds tracked; zero by default.
*/
abstract contract CohortAttributionDeclaration {
mapping(address => uint256) internal attributedContribution;
}
src/diamond/vault/declarations/CohortBookDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slots 70 to 75: each referrer's book. `cohortBook`
* packs three 80-bit lanes (year-1, year-2, mature); `cohortLastSettle`
* is the settle cursor, zero for a book never touched; the two 52-slot
* rings are indexed by week mod 52; `cohortWeekLog` holds one frozen crumb
* word per settled week (written flag at bit 252); `cohortGapLog` holds
* `from | to << 32 | mature << 64` records for dormant tails. All zero by
* default, so a disarmed diamond behaves as before.
*/
abstract contract CohortBookDeclaration {
mapping(address => uint256) internal cohortBook;
mapping(address => uint256) internal cohortLastSettle;
mapping(address => uint64[52]) internal cohortRingYear1;
mapping(address => uint64[52]) internal cohortRingYear2;
mapping(address => mapping(uint256 => uint256)) internal cohortWeekLog;
mapping(address => uint256[]) internal cohortGapLog;
}
src/diamond/vault/declarations/CohortContributionDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slots 68 and 69: the recorder switch
* `cohortSyncEnabled` and each account's `trackedContribution`, which
* rises only on a deposit or compound and falls only through the clamp.
* The switch is off by default, so a live diamond with virgin tail storage
* behaves as before. The selector constants name the engine entrypoints the
* helper chain stubs call and take no storage.
*/
abstract contract CohortContributionDeclaration {
bool internal cohortSyncEnabled;
mapping(address => uint256) internal trackedContribution;
bytes4 internal constant COHORT_SYNC_SELECTOR = bytes4(
keccak256(
"applyCohortSync(address)"
)
);
bytes4 internal constant COHORT_CREDIT_SELECTOR = bytes4(
keccak256(
"applyCohortCredit(address,uint256)"
)
);
bytes4 internal constant COHORT_ADVANCE_SELECTOR = bytes4(
keccak256(
"applyCohortAdvance(address,uint256)"
)
);
bytes4 internal constant COHORT_SETTLE_SELECTOR = bytes4(
keccak256(
"applyCohortSettle(address)"
)
);
bytes4 internal constant COHORT_MOVE_OUT_SELECTOR = bytes4(
keccak256(
"applyCohortMoveOut(address,address,uint256,uint256,uint256)"
)
);
bytes4 internal constant COHORT_MOVE_IN_SELECTOR = bytes4(
keccak256(
"applyCohortMoveIn(address,address)"
)
);
bytes4 internal constant COHORT_FLIP_SELECTOR = bytes4(
keccak256(
"applyCohortFlip(address,address,address)"
)
);
bytes4 internal constant COHORT_BRIDGE_OUT_SELECTOR = bytes4(
keccak256(
"applyCohortBridgeOut(address,uint64,uint256,uint256,uint256)"
)
);
bytes4 internal constant COHORT_BRIDGE_IN_SELECTOR = bytes4(
keccak256(
"applyCohortBridgeIn(address,uint64,uint256,bytes)"
)
);
}
src/diamond/vault/declarations/CohortDisarmDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slots 93 and 94: the disarm span and the outage grace
* stamps (slot 93 byte offsets 0, 8, 16 and 24; slot 94 offsets 0 and 8).
* A span exists only while `cohortRearmedAt` is above `cohortDisarmedAt`;
* the grace ends are never lowered or cleared. Zero stamps, the default,
* describe no span, so every segment counts in full as before.
*/
abstract contract CohortDisarmDeclaration {
uint256 internal constant FLUSH_OUTAGE_GRACE = 1 days;
uint64 internal cohortDisarmedAt;
uint64 internal cohortRearmedAt;
uint64 internal referralReopenStamp;
uint64 internal referralPauseStamp;
uint64 internal referralPauseGraceEnd;
uint64 internal referralDisarmGraceEnd;
}
src/diamond/vault/declarations/CohortDivestDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slot 91: the deferred divest park, the one sender the
* transfer hook could not clamp (only one holding tracked contribution)
* and its park instant at byte offset 20. An occupied park is never
* overwritten and both fields clear together; empty by default.
*/
abstract contract CohortDivestDeclaration {
address internal pendingDivestSync;
uint64 internal pendingDivestParkedAt;
}
src/diamond/vault/declarations/CohortFlushDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slots 83 to 89: the flush transport. The hub pointer
* and chain selector with their timelocked change, each referrer's send
* cursors (`flushedThroughWeek`; `flushGapCursor` with the gap index in the
* low 128 bits and the resume week in the high 128), the courier allowlist,
* the public flush switch and the message gas limit (zero means the
* default). A zero hub, the virgin default, makes every flush revert
* FlushHubNotSet.
*/
abstract contract CohortFlushDeclaration {
address internal flushHub;
uint64 internal flushHubChainSelector;
address internal proposedFlushHub;
uint64 internal proposedFlushHubChainSelector;
uint256 internal flushHubChangeQueuedAt;
mapping(address => uint256) internal flushedThroughWeek;
mapping(address => uint256) internal flushGapCursor;
mapping(address => bool) internal allowedFlushBot;
bool internal publicFlushEnabled;
uint64 internal flushGasLimit;
uint256 internal constant FLUSH_HUB_CHANGE_DELAY = 3 days;
uint256 internal constant FLUSH_GAP_CURSOR_WEEK_SHIFT = 128;
uint64 internal constant FLUSH_GAS_LIMIT = 300_000;
uint64 internal constant MAX_FLUSH_GAS_LIMIT = 2_000_000;
}
src/diamond/vault/declarations/CohortSelfDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slot 92: `cohortSelfCrumb`, one word per account,
* `currentWeekSeconds(80) | previousWeekSeconds(80) | settledAt(64)` with
* bits 224 and up zero, settled before every change of the account's
* tracked contribution. A never-written word belongs to an account whose
* tracked contribution is zero, so it reads as no presence. The routed
* getter is `getCohortSelfCrumb`.
*/
abstract contract CohortSelfDeclaration {
mapping(address => uint256) internal cohortSelfCrumb;
}
src/diamond/vault/declarations/CohortSelfLogDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slot 95: the per-week self presence log of every
* user with a self crumb on this vault (the
* log once skipped users with no book and no flush, which dropped a
* referrer's weeks before its first flush here). A self settle piece
* that crosses a week boundary appends one record `fromWeek(32) |
* completedSeconds(80) | stake(80)` with bits 192 and up zero: the
* completed seconds of the week the settle started in and the stake held
* through every following full week up to the next record. `fromWeek`
* strictly increases along a log (a record needs a boundary crossing),
* which the planner's binary search relies on, and a log grows by at most
* one record per elapsed week. The flush reads a
* closed week's realised self presence from the log, so a week is priced
* from its own average however late it is flushed. An empty log, the
* default, reads zero, which a live diamond holds until the engine is
* armed. The field is internal; every push emits `CohortSelfLogged`.
*/
abstract contract CohortSelfLogDeclaration {
mapping(address => uint256[]) internal cohortSelfLog;
}
src/diamond/vault/declarations/PayoutHubPointerDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slots 80 to 82, retired: the payout hub pointer of a
* vault side payout rail that was removed before it shipped (the hub is
* its own pot and never draws on a vault). The words stay declared and
* unused so the shards behind them keep their slots; they are never
* written.
*/
abstract contract PayoutHubPointerDeclaration {
address internal payoutHub;
address internal proposedPayoutHub;
uint256 internal payoutHubChangeQueuedAt;
uint256 internal constant PAYOUT_HUB_CHANGE_DELAY = 3 days;
}
src/diamond/vault/declarations/ReferralPayoutDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slot 76, retired: `pendingReferralPayout` backed the
* vault half of a payout rail that was removed before it shipped (the hub
* is its own pot and never draws on a vault). The word stays declared and
* unused so the shards behind it keep their slots; it is never written.
*/
abstract contract ReferralPayoutDeclaration {
uint256 internal pendingReferralPayout;
}
src/diamond/vault/declarations/ReferralRegistryDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slot 67: the diamond's own `referrerOf` mapping,
* superseded by the per-chain ReferralRegistry. It stays declared and
* forever virgin only so every later slot keeps its number; internal, so
* it has no getter.
*/
abstract contract ReferralRegistryDeclaration {
mapping(address => address) internal referrerOf;
}
src/diamond/vault/declarations/ReferralRegistryPointerDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Tail shard at slots 77 to 79: the chain ReferralRegistry pointer and
* its timelocked change. A zero pointer turns referrals off in both
* directions, which is also the virgin default; an execute probes
* `referrerOf` for a 32-byte answer.
*/
abstract contract ReferralRegistryPointerDeclaration {
address internal referralRegistry;
address internal proposedReferralRegistry;
uint256 internal referralRegistryChangeQueuedAt;
uint256 internal constant REFERRAL_REGISTRY_CHANGE_DELAY = 3 days;
}
src/diamond/vault/facets/CohortFlushPlanner.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {CohortPinnedBase} from "./CohortPinnedBase.sol";
import {CohortFlushCodec} from "../../shared/CohortFlushCodec.sol";
import {CohortWeeks} from "../../shared/CohortWeeks.sol";
import {IReferralRegistry} from "../interfaces/IReferralRegistry.sol";
/**
* @dev CohortFlushPlanner: builds the flush envelope entries from storage.
* Everything sent is storage derived; the caller chooses only the
* referrers and the timing, so every caller sends the same numbers. Only
* closed weeks are planned: each carries its own crumb and its own
* completed self presence (read from the self log, or from the self crumb
* for weeks after its last settle, read the way the next settle would
* write them: a crumb settled before a disarm counts its stake up to the
* disarm and no presence after it, whether the span is closed or still
* open, and a zero length span counts as no span), sent
* as runs of equal weekly averages, so the hub prices a week from that
* week alone. Weeks, crumbs and gap slices are planned within
* MAX_FLUSH_ENTRIES, MAX_SETTLE_BOUNDARIES and MAX_FLUSH_WORK (a crumb, a
* self week and a gap week each cost one; LOCAL_FLUSH_WORK on the hub
* chain, where the same transaction also pays the hub intake), with
* GAP_WORK_RESERVE held for
* the gap lane; a gap record exhausted by its cursor is skipped even when
* no work is left, and a book parked at a disarm keeps its through week
* below the disarm week. The payout designation is read from the
* registry by a guarded staticcall in CCIP mode only.
*/
abstract contract CohortFlushPlanner is CohortPinnedBase {
uint256 internal constant GAP_WORK_RESERVE = 40;
uint256 internal constant LOCAL_FLUSH_WORK = 96;
uint256 internal constant LOCAL_FLUSH_ENTRIES = 6;
struct FlushEntryData {
address referrer;
uint256 designationWord;
uint256[] selfRuns;
uint256[] crumbWeeks;
uint256[] crumbWords;
uint256[] gapSlices;
uint256 throughWeek;
uint256 gapIndex;
uint256 gapResumeWeek;
uint256 workUsed;
}
function _windowGapResumeWeek(
address _referrer,
uint256 _fromGapIndex
)
internal
view
returns (uint256)
{
uint256 cursor = flushGapCursor[_referrer];
if (_fromGapIndex == cursor & CohortWeeks.CARRY_HALF_MASK) {
return cursor >> FLUSH_GAP_CURSOR_WEEK_SHIFT;
}
return 0;
}
function _gapWorkWaiting(
address _referrer,
uint256 _gapIndex,
uint256 _gapResumeWeek
)
internal
view
returns (bool)
{
uint256 length = cohortGapLog[_referrer].length;
if (_gapIndex >= length) {
return false;
}
uint256 record = cohortGapLog[_referrer][_gapIndex];
uint256 sliceFrom = CohortWeeks._gapRecordFromWeek(
record
);
if (_gapResumeWeek > sliceFrom) {
sliceFrom = _gapResumeWeek;
}
return sliceFrom < CohortWeeks._gapRecordToWeek(
record
);
}
function _flushWorkBudget()
internal
view
returns (uint256)
{
if (flushHubChainSelector == 0) {
return LOCAL_FLUSH_WORK;
}
return CohortFlushCodec.MAX_FLUSH_WORK;
}
function _planFlushBatch(
address[] calldata _referrers
)
internal
view
returns (FlushEntryData[] memory entries)
{
uint256 currentWeek = block.timestamp
/ CohortWeeks.WEEK;
uint256 budget = _flushWorkBudget();
entries = new FlushEntryData[](
_referrers.length
);
for (uint256 i; i < _referrers.length; ++i) {
uint256 gapCursor = flushGapCursor[_referrers[i]];
entries[i] = _planFlushEntry(
_referrers[i],
_cursorFromWeek(
_referrers[i],
currentWeek
),
gapCursor & CohortWeeks.CARRY_HALF_MASK,
gapCursor >> FLUSH_GAP_CURSOR_WEEK_SHIFT,
budget
);
budget -= entries[i].workUsed;
}
}
struct SelfCursor {
uint256 length;
uint256 index;
uint256 crumb;
uint256 tracked;
}
struct WeekPlan {
uint256[] crumbWeeks;
uint256[] crumbWords;
uint256[] selfRuns;
uint256 crumbCount;
uint256 runCount;
uint256 throughWeek;
uint256 workUsed;
}
function _selfCursorAt(
address _referrer,
uint256 _fromWeek
)
internal
view
returns (SelfCursor memory cursor)
{
uint256[] storage log = cohortSelfLog[_referrer];
cursor.length = log.length;
cursor.crumb = cohortSelfCrumb[_referrer];
cursor.tracked = trackedContribution[_referrer];
uint256 low;
uint256 high = cursor.length;
while (low < high) {
uint256 mid = (low + high) / 2;
uint256 midWeek = CohortWeeks._selfLogFromWeek(
log[mid]
);
if (midWeek <= _fromWeek) {
low = mid + 1;
} else {
high = mid;
}
}
cursor.index = low > 0
? low - 1
: 0;
}
function _selfWeekSeconds(
address _referrer,
SelfCursor memory _cursor,
uint256 _week
)
internal
view
returns (uint256)
{
uint256 settledAt = CohortWeeks._selfCrumbSettledAt(
_cursor.crumb
);
if (settledAt > 0 && _week >= settledAt / CohortWeeks.WEEK) {
return _unsettledSelfSeconds(
_cursor,
settledAt,
_week
);
}
if (_cursor.length == 0) {
return 0;
}
uint256[] storage log = cohortSelfLog[_referrer];
while (_cursor.index + 1 < _cursor.length) {
uint256 nextWeek = CohortWeeks._selfLogFromWeek(
log[_cursor.index + 1]
);
if (nextWeek > _week) {
break;
}
++_cursor.index;
}
uint256 record = log[_cursor.index];
uint256 fromWeek = CohortWeeks._selfLogFromWeek(
record
);
if (fromWeek > _week) {
return 0;
}
if (fromWeek == _week) {
return CohortWeeks._selfLogSeconds(
record
);
}
return CohortWeeks._clampLane80(
CohortWeeks._selfLogStake(
record
) * CohortWeeks.WEEK
);
}
function _unsettledSelfSeconds(
SelfCursor memory _cursor,
uint256 _settledAt,
uint256 _week
)
internal
view
returns (uint256)
{
uint256 stake = CohortWeeks._clampLane80(
_cursor.tracked
);
uint256 disarmedAt = cohortDisarmedAt;
uint256 rearmedAt = cohortRearmedAt;
if (
disarmedAt == 0
|| rearmedAt == disarmedAt
|| _settledAt >= (rearmedAt > disarmedAt ? rearmedAt : disarmedAt)
) {
return CohortWeeks._completedPreviousSeconds(
CohortWeeks._selfCrumbCurrent(
_cursor.crumb
),
stake,
_settledAt,
_week + 1
);
}
uint256 weekStart = _week
* CohortWeeks.WEEK;
uint256 weekEnd = weekStart
+ CohortWeeks.WEEK;
uint256 from = _settledAt > weekStart
? _settledAt
: weekStart;
uint256 total = _week == _settledAt / CohortWeeks.WEEK
? CohortWeeks._selfCrumbCurrent(
_cursor.crumb
)
: 0;
total += stake * _overlapSeconds(
from,
disarmedAt,
weekEnd
);
return CohortWeeks._clampLane80(
total
);
}
function _overlapSeconds(
uint256 _from,
uint256 _to,
uint256 _weekEnd
)
internal
pure
returns (uint256)
{
uint256 end = _to < _weekEnd
? _to
: _weekEnd;
return end > _from
? end - _from
: 0;
}
function _planFlushEntry(
address _referrer,
uint256 _fromWeek,
uint256 _gapIndex,
uint256 _gapResumeWeek,
uint256 _workBudget
)
internal
view
returns (FlushEntryData memory entry)
{
entry.referrer = _referrer;
if (flushHubChainSelector != 0) {
entry.designationWord = _readDesignationWord(
_referrer
);
}
uint256 weekBudget = _workBudget;
if (_gapWorkWaiting(
_referrer,
_gapIndex,
_gapResumeWeek
)) {
weekBudget = _workBudget > GAP_WORK_RESERVE
? _workBudget - GAP_WORK_RESERVE
: 0;
}
WeekPlan memory plan = _planWeeks(
_referrer,
_fromWeek,
weekBudget
);
entry.crumbWeeks = plan.crumbWeeks;
entry.crumbWords = plan.crumbWords;
entry.selfRuns = plan.selfRuns;
entry.throughWeek = plan.throughWeek;
uint256 gapWork;
(
entry.gapSlices,
entry.gapIndex,
entry.gapResumeWeek,
gapWork
) = _planGaps(
_referrer,
_gapIndex,
_gapResumeWeek,
_workBudget - plan.workUsed
);
entry.workUsed = plan.workUsed
+ gapWork;
}
function _planWeeks(
address _referrer,
uint256 _fromWeek,
uint256 _workBudget
)
internal
view
returns (WeekPlan memory plan)
{
uint256 lastWeek = _lastPlannableWeek(
_referrer,
_fromWeek
);
plan.throughWeek = lastWeek;
uint256 span = lastWeek + 1 > _fromWeek
? lastWeek + 1 - _fromWeek
: 0;
plan.crumbWeeks = new uint256[](span);
plan.crumbWords = new uint256[](span);
plan.selfRuns = new uint256[](span);
SelfCursor memory cursor = _selfCursorAt(
_referrer,
_fromWeek
);
for (uint256 week = _fromWeek; week <= lastWeek; ++week) {
if (
_planWeek(
_referrer,
week,
cursor,
plan,
_workBudget
) == false
) {
plan.throughWeek = week > 0
? week - 1
: 0;
break;
}
}
_shrinkWords(
plan.crumbWeeks,
plan.crumbCount
);
_shrinkWords(
plan.crumbWords,
plan.crumbCount
);
_shrinkWords(
plan.selfRuns,
plan.runCount
);
}
function _planWeek(
address _referrer,
uint256 _week,
SelfCursor memory _cursor,
WeekPlan memory _plan,
uint256 _workBudget
)
internal
view
returns (bool)
{
uint256 selfAvg = _selfWeekSeconds(
_referrer,
_cursor,
_week
) / CohortWeeks.WEEK;
uint256 word = cohortWeekLog[_referrer][_week];
bool hasCrumb = word & ~CohortWeeks.CRUMB_WRITTEN_BIT != 0;
uint256 cost = (selfAvg > 0 ? 1 : 0) + (hasCrumb ? 1 : 0);
if (_plan.workUsed + cost > _workBudget) {
return false;
}
_plan.workUsed += cost;
if (hasCrumb) {
_plan.crumbWeeks[_plan.crumbCount] = _week;
_plan.crumbWords[_plan.crumbCount] = word;
++_plan.crumbCount;
}
if (selfAvg == 0) {
return true;
}
if (_plan.runCount > 0) {
uint256 last = _plan.selfRuns[_plan.runCount - 1];
uint256 lastTo = CohortFlushCodec._selfRunToWeek(
last
);
uint256 lastAverage = CohortFlushCodec._selfRunAverage(
last
);
if (lastTo == _week && lastAverage == selfAvg) {
_plan.selfRuns[_plan.runCount - 1] = CohortFlushCodec._packSelfRun(
CohortFlushCodec._selfRunFromWeek(
last
),
_week + 1,
selfAvg
);
return true;
}
}
_plan.selfRuns[_plan.runCount] = CohortFlushCodec._packSelfRun(
_week,
_week + 1,
selfAvg
);
++_plan.runCount;
return true;
}
function _lastPlannableWeek(
address _referrer,
uint256 _fromWeek
)
internal
view
returns (uint256)
{
uint256 currentWeek = block.timestamp
/ CohortWeeks.WEEK;
uint256 lastWeek = currentWeek > 0
? currentWeek - 1
: 0;
uint256 scanCap = _fromWeek
+ CohortWeeks.MAX_SETTLE_BOUNDARIES
- 1;
if (scanCap < lastWeek) {
lastWeek = scanCap;
}
return _capParkedThroughWeek(
_referrer,
lastWeek
);
}
function _shrinkWords(
uint256[] memory _words,
uint256 _length
)
internal
pure
{
assembly {
mstore(_words, _length)
}
}
function _capParkedThroughWeek(
address _referrer,
uint256 _throughWeek
)
internal
view
returns (uint256)
{
uint256 disarmedAt = cohortDisarmedAt;
uint256 rearmedAt = cohortRearmedAt;
uint256 last = cohortLastSettle[_referrer];
if (last == 0 || _parkedAtDisarmCohort(last, disarmedAt, rearmedAt) == false) {
return _throughWeek;
}
uint256 cap = disarmedAt
/ CohortWeeks.WEEK
- 1;
return _throughWeek < cap
? _throughWeek
: cap;
}
function _planGaps(
address _referrer,
uint256 _gapIndex,
uint256 _gapResumeWeek,
uint256 _workBudget
)
internal
view
returns (
uint256[] memory slices,
uint256 gapIndex,
uint256 gapResumeWeek,
uint256 workUsed
)
{
(
uint256 count,
,
,
) = _walkGapSlices(
_referrer,
_gapIndex,
_gapResumeWeek,
_workBudget,
new uint256[](0)
);
slices = new uint256[](count);
(
,
gapIndex,
gapResumeWeek,
workUsed
) = _walkGapSlices(
_referrer,
_gapIndex,
_gapResumeWeek,
_workBudget,
slices
);
}
function _walkGapSlices(
address _referrer,
uint256 _gapIndex,
uint256 _gapResumeWeek,
uint256 _workBudget,
uint256[] memory _fill
)
internal
view
returns (
uint256 count,
uint256 gapIndex,
uint256 gapResumeWeek,
uint256 workUsed
)
{
uint256 length = cohortGapLog[_referrer].length;
uint256 left = _workBudget;
uint256 resume = _gapResumeWeek;
uint256 index = _gapIndex;
while (index < length) {
uint256 record = cohortGapLog[_referrer][index];
uint256 sliceFrom = CohortWeeks._gapRecordFromWeek(
record
);
if (resume > sliceFrom) {
sliceFrom = resume;
}
uint256 sliceTo = CohortWeeks._gapRecordToWeek(
record
);
if (sliceFrom >= sliceTo) {
++index;
resume = 0;
continue;
}
if (left == 0) {
break;
}
uint256 take = left < CohortWeeks.MAX_SETTLE_BOUNDARIES
? left
: CohortWeeks.MAX_SETTLE_BOUNDARIES;
if (take > sliceTo - sliceFrom) {
take = sliceTo - sliceFrom;
}
if (_fill.length > 0) {
_fill[count] = CohortWeeks._packGapRecord(
sliceFrom,
sliceFrom + take,
_clampGapMature(
CohortWeeks._gapRecordMature(
record
)
)
);
}
++count;
left -= take;
if (sliceFrom + take == sliceTo) {
++index;
resume = 0;
} else {
resume = sliceFrom + take;
}
}
return (
count,
index,
resume,
_workBudget - left
);
}
function _clampGapMature(
uint256 _mature
)
internal
pure
returns (uint256)
{
uint256 ceiling = CohortWeeks.LANE_MASK_80
/ CohortWeeks.WEEK;
return _mature < ceiling
? _mature
: ceiling;
}
function _cursorFromWeek(
address _referrer,
uint256 _currentWeek
)
internal
view
returns (uint256)
{
uint256 stored = flushedThroughWeek[_referrer];
if (stored > 0) {
return stored + 1;
}
if (_currentWeek < CohortWeeks.MAX_SETTLE_BOUNDARIES) {
return 0;
}
return _currentWeek
- CohortWeeks.MAX_SETTLE_BOUNDARIES
+ 1;
}
function _readDesignationWord(
address _owner
)
internal
view
returns (uint256)
{
address registry = referralRegistry;
if (registry == ZERO_ADDRESS) {
return 0;
}
bytes4 selector = IReferralRegistry.getPayoutDesignation.selector;
(
bool success,
uint256 word0,
uint256 word1,
) = _staticWordsCohort(
registry,
selector,
uint256(uint160(_owner)),
0,
0x24,
2
);
if (
success == false
|| word0 > type(uint160).max
|| word1 == 0
|| (word1 >> CohortFlushCodec.DESIGNATION_STAMP_SHIFT) > CohortWeeks.RING_LANE_MAX
) {
return 0;
}
return CohortFlushCodec._packFlushDesignation(
address(uint160(word0)),
word1 >> CohortFlushCodec.DESIGNATION_STAMP_SHIFT,
word1 & CohortWeeks.CARRY_BYTE_MASK
);
}
}
src/diamond/vault/facets/CohortFlushTransport.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {Client} from "@chainlink/contracts-ccip/contracts/libraries/Client.sol";
import {IRouterClient} from "@chainlink/contracts-ccip/contracts/interfaces/IRouterClient.sol";
import {CohortFlushPlanner} from "./CohortFlushPlanner.sol";
import {CohortFlushCodec} from "../../shared/CohortFlushCodec.sol";
import {CohortWeeks} from "../../shared/CohortWeeks.sol";
import {IReferralFlushHub} from "../interfaces/IReferralFlushHub.sol";
/**
* @dev CohortFlushTransport: the flush guards, the cursor writes and the
* hub send. A flush reverts FlushHubNotSet while the hub pointer is unset
* and needs an armed recorder, an installed hook and a set registry. The
* referrer's own flush writes its cursors, which only advance. A batch
* sent by an allowed flush bot opens a book whose through week cursor is
* still unset, writing both cursors exactly as the referrer's own batch
* would (a batch always plans from the stored cursor or the lookback edge,
* so it skips no week), and never moves a cursor some flush already
* stored, so a referrer need not flush once itself before a courier can
* carry its book; a book older than the lookback that a courier opens
* keeps its older weeks deliverable by the referrer's own window only, as
* after the referrer's own first batch. A window sent by anyone but the
* referrer and a batch sent by a public flush caller write no cursor; a
* third party window starts above both stored cursors, and every third
* party is refused inside the outage grace that follows a reopen. The
* envelope goes to the hub over CCIP, or directly on the hub chain, where
* a batch takes at most LOCAL_FLUSH_ENTRIES referrers because the same
* transaction pays the hub intake; any unused fee is refunded. The
* deliverer the hub sees is the caller only when the caller is an allowed
* flush bot; otherwise it is zero in a CCIP header and the referrer itself
* on the hub chain, whose intake refuses a zero deliverer. Either way only
* an allowlisted bot can earn the courier fee, and a referrer that flushes
* its own book from a second address earns nothing.
*/
abstract contract CohortFlushTransport is CohortFlushPlanner {
function _courierOf()
internal
view
returns (address)
{
return allowedFlushBot[msg.sender] == true
? msg.sender
: ZERO_ADDRESS;
}
function _settleBeforePlan(
address _referrer
)
internal
{
_cohortSettle(
_referrer
);
}
function _checkFlushBatch(
uint256 _count
)
internal
view
{
require(
flushHub != ZERO_ADDRESS,
FlushHubNotSet()
);
require(
_count > 0,
NothingToFlush()
);
require(
_count <= CohortFlushCodec.MAX_FLUSH_ENTRIES
&& (flushHubChainSelector > 0 || _count <= LOCAL_FLUSH_ENTRIES),
FlushBatchTooLarge()
);
}
function _checkBookAdvanced(
address _referrer
)
internal
view
{
uint256 last = cohortLastSettle[_referrer];
if (last == 0) {
return;
}
uint256 target = _parkedAtDisarmCohort(
last,
cohortDisarmedAt,
cohortRearmedAt
)
? cohortDisarmedAt
: block.timestamp;
require(
last / CohortWeeks.WEEK == target / CohortWeeks.WEEK,
FlushBookNotAdvanced()
);
}
function _checkFlushArmed()
internal
view
{
require(
cohortSyncEnabled,
CohortSyncDisabled()
);
require(
transferHookFacet != ZERO_ADDRESS,
CohortHookNotInstalled()
);
require(
referralRegistry != ZERO_ADDRESS,
ReferralRegistryNotSet()
);
}
function _checkFlushCaller(
address _referrer
)
internal
view
{
require(
_referrer != ZERO_ADDRESS,
InvalidValue()
);
if (_referrer == msg.sender) {
return;
}
require(
publicFlushEnabled == true
|| allowedFlushBot[msg.sender] == true,
NotFlushBot()
);
}
function _checkFlushOutageGate(
address _referrer,
uint256 _firstWeek,
uint256 _gapIndex,
uint256 _gapResumeWeek
)
internal
view
{
if (_referrer == msg.sender) {
return;
}
uint256 unpause = referralReopenStamp;
uint256 rearm = cohortRearmedAt;
uint256 reopen = unpause;
if (
rearm > cohortDisarmedAt
&& rearm > reopen
) {
reopen = rearm;
}
uint256 earliest = _firstWeek;
if (_gapIndex < cohortGapLog[_referrer].length) {
uint256 gapFirstWeek = CohortWeeks._gapRecordFromWeek(
cohortGapLog[_referrer][_gapIndex]
);
if (_gapResumeWeek > gapFirstWeek) {
gapFirstWeek = _gapResumeWeek;
}
if (gapFirstWeek < earliest) {
earliest = gapFirstWeek;
}
}
uint256 pauseDeadline = unpause
+ FLUSH_OUTAGE_GRACE
+ unpause
- referralPauseStamp;
if (referralPauseGraceEnd > pauseDeadline) {
pauseDeadline = referralPauseGraceEnd;
}
uint256 disarmDeadline = rearm
+ FLUSH_OUTAGE_GRACE
+ rearm
- cohortDisarmedAt;
if (referralDisarmGraceEnd > disarmDeadline) {
disarmDeadline = referralDisarmGraceEnd;
}
require(
(earliest + 1) * CohortWeeks.WEEK > reopen
|| (block.timestamp >= pauseDeadline
&& block.timestamp >= disarmDeadline),
FlushOutageGraceActive()
);
}
function _checkWindowStart(
address _referrer,
uint256 _fromWeek,
uint256 _fromGapIndex
)
internal
view
{
if (_referrer == msg.sender) {
return;
}
require(
_fromWeek > flushedThroughWeek[_referrer],
FlushWindowInvalid()
);
uint256 storedIndex = flushGapCursor[_referrer] & CohortWeeks.CARRY_HALF_MASK;
require(
_fromGapIndex >= storedIndex,
FlushWindowInvalid()
);
}
function _commitFlush(
FlushEntryData[] memory _entries,
bool _batch
)
internal
{
bool courierBatch = _batch
&& allowedFlushBot[msg.sender] == true;
for (uint256 i; i < _entries.length; ++i) {
if (
_entries[i].referrer == msg.sender
|| (
courierBatch
&& flushedThroughWeek[_entries[i].referrer] == 0
)
) {
_advanceFlushCursors(
_entries[i]
);
}
}
_dispatchFlush(
_entries
);
}
function _advanceFlushCursors(
FlushEntryData memory _entry
)
internal
{
bool changed;
if (_entry.throughWeek > flushedThroughWeek[_entry.referrer]) {
flushedThroughWeek[_entry.referrer] = _entry.throughWeek;
changed = true;
}
uint256 stored = flushGapCursor[_entry.referrer];
uint256 storedIndex = stored & CohortWeeks.CARRY_HALF_MASK;
uint256 storedResume = stored >> FLUSH_GAP_CURSOR_WEEK_SHIFT;
if (
_entry.gapIndex > storedIndex
|| (
_entry.gapIndex == storedIndex
&& _entry.gapResumeWeek > storedResume
)
) {
flushGapCursor[_entry.referrer] = _entry.gapIndex
| (_entry.gapResumeWeek << FLUSH_GAP_CURSOR_WEEK_SHIFT);
changed = true;
}
if (changed == false) {
return;
}
uint256 cursor = flushGapCursor[_entry.referrer];
emit CohortReferrerFlushed(
_entry.referrer,
flushedThroughWeek[_entry.referrer],
cursor & CohortWeeks.CARRY_HALF_MASK,
cursor >> FLUSH_GAP_CURSOR_WEEK_SHIFT
);
}
function _dispatchFlush(
FlushEntryData[] memory _entries
)
internal
{
address hub = flushHub;
uint64 destChainSelector = flushHubChainSelector;
if (destChainSelector == 0) {
_deliverFlushLocal(
hub,
_entries
);
_refundExcessFlushFee(
0
);
emit CohortFlushDelivered(
hub,
msg.sender,
_entries.length
);
return;
}
require(
ccipRouter != ZERO_ADDRESS,
RouterNotSet()
);
Client.EVM2AnyMessage memory message = _buildFlushMessage(
hub,
_packFlushEnvelope(
_entries
)
);
uint256 fee = IRouterClient(ccipRouter).getFee(
destChainSelector,
message
);
require(
msg.value >= fee,
InsufficientFlushFee()
);
bytes32 messageId = IRouterClient(ccipRouter).ccipSend{value: fee}(
destChainSelector,
message
);
_refundExcessFlushFee(
fee
);
emit CohortFlushSent(
messageId,
destChainSelector,
msg.sender,
_entries.length
);
}
function _deliverFlushLocal(
address _hub,
FlushEntryData[] memory _entries
)
internal
{
address courier = _courierOf();
for (uint256 i; i < _entries.length; ++i) {
address deliverer = courier == ZERO_ADDRESS
? _entries[i].referrer
: courier;
if (_entries[i].selfRuns.length > 0) {
IReferralFlushHub(_hub).reportSelf(
_entries[i].referrer,
_entries[i].selfRuns
);
}
if (_entries[i].crumbWeeks.length > 0) {
IReferralFlushHub(_hub).deliverCrumbs(
_entries[i].referrer,
deliverer,
_entries[i].crumbWeeks,
_entries[i].crumbWords
);
}
for (uint256 k; k < _entries[i].gapSlices.length; ++k) {
uint256 slice = _entries[i].gapSlices[k];
IReferralFlushHub(_hub).deliverGap(
_entries[i].referrer,
deliverer,
slice,
CohortWeeks._gapRecordFromWeek(
slice
),
CohortWeeks._gapRecordToWeek(
slice
)
- CohortWeeks._gapRecordFromWeek(
slice
)
);
}
}
}
function _packFlushEnvelope(
FlushEntryData[] memory _entries
)
internal
view
returns (bytes memory)
{
uint256 total = 1;
for (uint256 i; i < _entries.length; ++i) {
total += 1
+ (_entries[i].designationWord != 0 ? 1 : 0)
+ _entries[i].selfRuns.length
+ _entries[i].crumbWeeks.length * 2
+ _entries[i].gapSlices.length;
}
uint256[] memory out = new uint256[](total);
out[0] = CohortFlushCodec._packFlushHeader(
_courierOf(),
_entries.length,
block.timestamp
);
uint256 cursor = 1;
for (uint256 i; i < _entries.length; ++i) {
FlushEntryData memory entry = _entries[i];
uint256 flags = entry.designationWord != 0
? CohortFlushCodec.FLUSH_FLAG_DESIGNATION
: 0;
out[cursor] = CohortFlushCodec._packFlushEntry(
entry.referrer,
entry.crumbWeeks.length,
entry.gapSlices.length,
flags,
entry.selfRuns.length
);
++cursor;
if (flags != 0) {
out[cursor] = entry.designationWord;
++cursor;
}
for (uint256 k; k < entry.selfRuns.length; ++k) {
out[cursor] = entry.selfRuns[k];
++cursor;
}
for (uint256 k; k < entry.crumbWeeks.length; ++k) {
out[cursor] = entry.crumbWeeks[k];
out[cursor + 1] = entry.crumbWords[k];
cursor += 2;
}
for (uint256 k; k < entry.gapSlices.length; ++k) {
out[cursor] = entry.gapSlices[k];
++cursor;
}
}
return abi.encodePacked(
out
);
}
function _buildFlushMessage(
address _hub,
bytes memory _payload
)
internal
view
returns (Client.EVM2AnyMessage memory)
{
uint64 gasLimit = flushGasLimit == 0
? FLUSH_GAS_LIMIT
: flushGasLimit;
return Client.EVM2AnyMessage({
receiver: abi.encode(
_hub
),
data: _payload,
tokenAmounts: new Client.EVMTokenAmount[](0),
feeToken: ZERO_ADDRESS,
extraArgs: Client._argsToBytes(
Client.GenericExtraArgsV2({
gasLimit: gasLimit,
allowOutOfOrderExecution: true
})
)
});
}
function _refundExcessFlushFee(
uint256 _fee
)
internal
{
uint256 refund = msg.value
- _fee;
if (refund == 0) {
return;
}
(
bool ok,
) = payable(msg.sender).call{value: refund}(
""
);
require(
ok,
FlushRefundFailed()
);
}
}
src/diamond/vault/facets/CohortPinnedBase.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {OwnableMaster} from "../../shared/OwnableMaster.sol";
import {OnlyDelegateCall} from "../../shared/DiamondErrors.sol";
import {CohortWeeks} from "../../shared/CohortWeeks.sol";
import {WiseTelecomNodesDiamondErrors} from "../WiseTelecomNodesDiamondErrors.sol";
import {WiseTelecomNodesDiamondEvents} from "../WiseTelecomNodesDiamondEvents.sol";
import {ReferralRegistryDeclaration} from "../declarations/ReferralRegistryDeclaration.sol";
import {CohortContributionDeclaration} from "../declarations/CohortContributionDeclaration.sol";
import {CohortBookDeclaration} from "../declarations/CohortBookDeclaration.sol";
import {ReferralPayoutDeclaration} from "../declarations/ReferralPayoutDeclaration.sol";
import {ReferralRegistryPointerDeclaration} from "../declarations/ReferralRegistryPointerDeclaration.sol";
import {PayoutHubPointerDeclaration} from "../declarations/PayoutHubPointerDeclaration.sol";
import {CohortFlushDeclaration} from "../declarations/CohortFlushDeclaration.sol";
import {CohortAttributionDeclaration} from "../declarations/CohortAttributionDeclaration.sol";
import {CohortDivestDeclaration} from "../declarations/CohortDivestDeclaration.sol";
import {CohortSelfDeclaration} from "../declarations/CohortSelfDeclaration.sol";
import {CohortDisarmDeclaration} from "../declarations/CohortDisarmDeclaration.sol";
import {CohortSelfLogDeclaration} from "../declarations/CohortSelfLogDeclaration.sol";
/**
* @dev Genesis slots 0 to 66 of the diamond layout, pinned by label
* for the slim cohort facets. Slots 0 to 2 come from the same bases
* the declaration chain inherits first; the rest is __gap filler.
* Checked against the snapshot by script/check_storage_layout.sh.
*/
abstract contract CohortPinnedPrefix is
WiseTelecomNodesDiamondEvents,
WiseTelecomNodesDiamondErrors,
OwnableMaster,
Pausable,
ReentrancyGuard
{
mapping(address => uint256) internal _balances;
uint256[19] private __gap4;
mapping(bytes4 => address) internal selectorToFacet;
uint256[10] private __gap24;
bool private __pad34;
address internal ccipRouter;
uint256[10] private __gap35;
address internal transferHookFacet;
uint256[5] private __gap46;
uint256 internal gracePeriodDuration;
uint256 private __gap52;
mapping(address => uint256) internal lastLargeDepositAt;
bool internal graceFreezeEnabled;
uint256[12] private __gap55;
bool internal transient hookExecuting;
}
/**
* @dev Slim storage base of the cohort engine slices and the flush
* facet: the pinned genesis prefix, then the tail shards from slot 67
* inherited verbatim in declaration chain order, plus the few helper
* chain internals these facets call. The hook dispatch is reached only
* after the flush armed check, so it omits the disarmed and unset hook
* early returns of the helper chain. A new tail shard must be appended
* here as well before a slim facet reads it.
*/
abstract contract CohortPinnedBase is
CohortPinnedPrefix,
ReferralRegistryDeclaration,
CohortContributionDeclaration,
CohortBookDeclaration,
ReferralPayoutDeclaration,
ReferralRegistryPointerDeclaration,
PayoutHubPointerDeclaration,
CohortFlushDeclaration,
CohortAttributionDeclaration,
CohortDivestDeclaration,
CohortSelfDeclaration,
CohortDisarmDeclaration,
CohortSelfLogDeclaration
{
address internal immutable _self;
constructor()
OwnableMaster(msg.sender)
{
_self = address(this);
}
modifier onlyDelegateCall() {
_onlyDelegateCall();
_;
}
function _onlyDelegateCall()
internal
view
{
if (address(this) != _self) {
return;
}
revert OnlyDelegateCall();
}
function balanceOf(
address _account
)
internal
view
returns (uint256)
{
return _balances[_account];
}
function _checkGracePeriod(
address _user
)
internal
view
{
require(
lastLargeDepositAt[_user] == 0
|| block.timestamp >= lastLargeDepositAt[_user] + gracePeriodDuration,
GracePeriodNotElapsed()
);
}
function _parkedAtDisarmCohort(
uint256 _cursor,
uint256 _disarmedAt,
uint256 _rearmedAt
)
internal
view
returns (bool)
{
return _rearmedAt > _disarmedAt
&& _cursor <= _disarmedAt
&& block.timestamp < _rearmedAt + CohortWeeks.WEEK;
}
function _staticWordsCohort(
address _target,
bytes4 _selector,
uint256 _argument0,
uint256 _argument1,
uint256 _calldataLength,
uint256 _outWords
)
internal
view
returns (
bool success,
uint256 word0,
uint256 word1,
uint256 word2
)
{
assembly {
let ptr := mload(0x40)
mstore(ptr, _selector)
mstore(add(ptr, 0x04), _argument0)
mstore(add(ptr, 0x24), _argument1)
success := staticcall(
gas(),
_target,
ptr,
_calldataLength,
0x00,
0x00
)
if iszero(eq(returndatasize(), mul(_outWords, 32))) {
success := 0
}
if success {
returndatacopy(ptr, 0, mul(_outWords, 32))
word0 := mload(ptr)
word1 := mload(add(ptr, 0x20))
word2 := mload(add(ptr, 0x40))
}
}
}
function _cohortSettle(
address _referrer
)
internal
{
_runCohortHook(
abi.encodeWithSelector(
COHORT_SETTLE_SELECTOR,
_referrer
)
);
}
function _runCohortHook(
bytes memory _callData
)
internal
{
hookExecuting = true;
(
bool success,
bytes memory returnData
) = transferHookFacet.delegatecall(
_callData
);
hookExecuting = false;
if (success == false) {
assembly {
revert(add(returnData, 0x20), mload(returnData))
}
}
}
}
src/diamond/vault/interfaces/IReferralFlushHub.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev The reporter surface of the referral hub used by a flush on the hub
* chain itself, where the vault is the allowed reporter and delivers by
* direct call. Reverts bubble so a local delivery is never dropped.
*/
interface IReferralFlushHub {
function reportSelf(
address _referrer,
uint256[] calldata _selfRuns
)
external;
function deliverCrumbs(
address _referrer,
address _deliverer,
uint256[] calldata _weeks,
uint256[] calldata _words
)
external;
function deliverGap(
address _referrer,
address _deliverer,
uint256 _record,
uint256 _fromWeek,
uint256 _maxWeeks
)
external;
}
src/diamond/vault/interfaces/IReferralRegistry.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev The ReferralRegistry surface a vault calls: the write-once assign,
* the plain and flip-aware referrer reads, the same-chain carry mailbox,
* the bridge pair read and merge, the payout designation read, the seed
* latch and the sync quarantine flag. The engine reaches the mutating and
* cohort reads through guarded calls; the admin surface is operated on the
* registry directly.
*/
interface IReferralRegistry {
function assignReferrer(
address _user,
address _referrer
)
external;
function referrerOf(
address _user
)
external
view
returns (address);
function effectiveReferrerOf(
address _user,
address _vault
)
external
view
returns (address);
function getReferrerPair(
address _user
)
external
view
returns (
address referrer,
uint256 assignedAt,
uint256 rank
);
function mergeReferrer(
address _user,
address _referrer,
uint256 _assignedAt,
uint256 _rank
)
external;
function stageCarry(
address _dstVault,
address _user,
uint256[] calldata _payload
)
external;
function consumeCarry(
address _srcVault,
address _user
)
external
returns (
uint256 stagedAt,
uint256[] memory payload
);
function getPayoutDesignation(
address _owner
)
external
view
returns (
address payout,
uint256 stamp
);
function seedsLatched()
external
view
returns (bool);
function syncPeerQuarantined(
uint64 _chainSelector
)
external
view
returns (bool);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 600000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"@chainlink/contracts-ccip/=node_modules/@chainlink/contracts-ccip/",
"@chainlink/contracts/=node_modules/@chainlink/contracts/",
"@arbitrum/=node_modules/@arbitrum/",
"@eth-optimism/=node_modules/@eth-optimism/",
"@offchainlabs/=node_modules/@offchainlabs/",
"@scroll-tech/=node_modules/@scroll-tech/",
"@zksync/=node_modules/@zksync/",
"solady/=node_modules/solady/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.