Verified contractExact--
ReferralHubPayoutFacet
Address0x9284be101a1e69fe74146bd6941596f01cc3e7a5
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.36
- Same code
Only this contract
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,481
- Creation transaction
- 0xa85d89274d…7987020fa3
14 files
- src/hub/ReferralHubPayoutFacet.solmain6.48 KB
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol2.26 KB
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- node_modules/@openzeppelin/contracts/utils/Address.sol9.36 KB
- 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/hub/ReferralHubCheckpoints.sol2.77 KB
- src/hub/ReferralHubDeclarations.sol14.37 KB
- src/hub/ReferralHubFacetBase.sol799 B
- src/hub/ReferralHubIntake.sol21.21 KB
- src/hub/ReferralHubRates.sol5.98 KB
src/hub/ReferralHubPayoutFacet.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReferralHubIntake} from "./ReferralHubIntake.sol";
import {ReferralHubFacetBase} from "./ReferralHubFacetBase.sol";
/**
* @dev ReferralHubPayoutFacet: the claim rail (`claim`, `claimUpTo`,
* `claimAll` over several source chains) and the hub chain's own payout
* designation. Every bucket pays its owner's own address on the hub chain
* until a designation from the bucket's chain redirects it (the registry's
* `setPayoutAddress` on a spoke, carried by a flush or pushed, or this
* facet's `setPayoutAddress` on the hub chain; the newest stamp wins), so
* a referrer has to do nothing to be paid, and `payoutAddressOf` answers
* the address a claim would pay. A contract wallet that owns a spoke
* bucket (as referrer or as courier) and does not control the same
* address on the hub chain has that bucket payable to the address here,
* so such an owner designates on that spoke before its first commission
* accrues; an externally owned account loses nothing.
* The hub is its own pot: a claim pays from the USD the hub holds (funded
* by plain transfers; `totalPayable - totalClaimed` is the amount owed,
* `totalPayable` being kept equal to `totalAccrued` at every accrual and
* every claim), `PotDry` when it holds less. It never reaches the pricing.
*/
contract ReferralHubPayoutFacet is
ReferralHubIntake,
ReferralHubFacetBase
{
using SafeERC20 for IERC20;
function claim(
uint256 _chainId,
address _referrer
)
external
onlyDelegateCall
{
uint256 amount = claimable[_chainId][_referrer];
require(
amount > 0,
NothingClaimable()
);
_payClaim(
_chainId,
_referrer,
amount
);
}
function claimUpTo(
uint256 _chainId,
address _referrer,
uint256 _amount
)
external
onlyDelegateCall
{
uint256 entitled = claimable[_chainId][_referrer];
uint256 amount = _amount < entitled
? _amount
: entitled;
require(
amount > 0,
NothingClaimable()
);
uint256 covered = _coveredAmount();
if (amount > covered) {
amount = covered;
}
require(
amount > 0,
PotDry()
);
_payClaim(
_chainId,
_referrer,
amount
);
}
/**
* @dev Claims every listed bucket of `_referrer` that holds an amount
* and accepts the caller (the referrer or that bucket's resolved
* payout); every other bucket is skipped, a repeated chain id included.
* Each bucket pays up to the cover left after the buckets before it, as
* `claimUpTo` does, so a short pot pays what it can in list order and
* leaves the rest claimable. Reverts `NothingClaimable` when it pays
* nothing.
*/
function claimAll(
address _referrer,
uint256[] calldata _chainIds
)
external
onlyDelegateCall
returns (uint256 total)
{
for (uint256 i; i < _chainIds.length; ++i) {
uint256 chainId = _chainIds[i];
uint256 amount = claimable[chainId][_referrer];
if (
amount == 0
|| _claimSkipped(
chainId,
_referrer
)
) {
continue;
}
uint256 covered = _coveredAmount();
if (amount > covered) {
amount = covered;
}
if (amount == 0) {
continue;
}
_payClaim(
chainId,
_referrer,
amount
);
total += amount;
}
require(
total > 0,
NothingClaimable()
);
}
function setPayoutAddress(
address _payout
)
external
onlyDelegateCall
{
payoutStamp[block.chainid][msg.sender] = block.timestamp
<< PAYOUT_STAMP_SHIFT;
payoutAddress[block.chainid][msg.sender] = _payout;
emit PayoutAddressSet(
block.chainid,
msg.sender,
_payout
);
}
function payoutAddressOf(
uint256 _chainId,
address _owner
)
external
view
returns (address)
{
return _resolvedPayout(
_chainId,
_owner
);
}
function _payClaim(
uint256 _chainId,
address _referrer,
uint256 _amount
)
internal
{
address payout = _resolvedPayout(
_chainId,
_referrer
);
require(
msg.sender == _referrer
|| msg.sender == payout,
NotPayoutAuthorized()
);
claimable[_chainId][_referrer] = claimable[_chainId][_referrer]
- _amount;
totalClaimed = totalClaimed
+ _amount;
totalPayable = totalAccrued;
require(
_amount <= USD_TOKEN.balanceOf(
address(this)
),
PotDry()
);
USD_TOKEN.safeTransfer(
payout,
_amount
);
emit PayoutClaimed(
_chainId,
_referrer,
payout,
_amount
);
}
function _claimSkipped(
uint256 _chainId,
address _referrer
)
internal
view
returns (bool)
{
return msg.sender != _referrer
&& msg.sender != _resolvedPayout(
_chainId,
_referrer
);
}
function _coveredAmount()
internal
view
returns (uint256)
{
return USD_TOKEN.balanceOf(
address(this)
);
}
function _resolvedPayout(
uint256 _chainId,
address _owner
)
internal
view
returns (address)
{
address payout = payoutAddress[_chainId][_owner];
return payout == ZERO_ADDRESS
? _owner
: payout;
}
}
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
node_modules/@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
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/hub/ReferralHubCheckpoints.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {ReferralHubDeclarations} from "./ReferralHubDeclarations.sol";
import {CohortWeeks} from "../diamond/shared/CohortWeeks.sol";
/**
* @dev ReferralHubCheckpoints: the week buckets the ladder reads. Week W is
* priced only from W's own bucket, the realised averages its sources
* reported for W: no sample of another week, no carried score and no
* freshness window. A bucket only rises (every source report is final for
* its closed week and merged by maximum), so W's rates never fall and,
* after a later report, `settleWeeks` tops up what W already paid.
*/
abstract contract ReferralHubCheckpoints is ReferralHubDeclarations {
function ladderInputsAt(
address _referrer,
uint256 _week
)
external
view
returns (
uint256 referredInput,
uint256 selfInput
)
{
return _ladderInputsAt(
_referrer,
_week
);
}
function weekReportOf(
bytes32 _source,
address _referrer,
uint256 _week
)
external
view
returns (
uint256 referredAverage,
uint256 paidUnits
)
{
uint256 word = sourceWeekOf[_source][_referrer][_week];
return (
word & WEEK_HALF_MASK,
word >> WEEK_HALF_SHIFT
);
}
function weekSelfOf(
bytes32 _source,
address _referrer,
uint256 _week
)
external
view
returns (uint256)
{
return sourceSelfOf[_source][_referrer][_week];
}
function _ladderInputsAt(
address _referrer,
uint256 _week
)
internal
view
returns (
uint256 referredInput,
uint256 selfInput
)
{
uint256 word = weekInputsOf[_referrer][_week];
return (
word & WEEK_HALF_MASK,
word >> WEEK_HALF_SHIFT
);
}
function _requireWithinHorizon(
uint256 _week
)
internal
view
{
require(
_week <= block.timestamp / CohortWeeks.WEEK + MAX_SCHEDULE_HORIZON_WEEKS,
WeekOutOfRange()
);
}
function _lastAtOrBefore(
uint256 _length,
uint256 _week,
function(uint256) internal view returns (uint256) _weekAt
)
internal
view
returns (uint256 low)
{
uint256 high = _length - 1;
while (low < high) {
uint256 mid = (low + high + 1) / 2;
if (_weekAt(mid) <= _week) {
low = mid;
} else {
high = mid - 1;
}
}
}
}
src/hub/ReferralHubDeclarations.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {OwnableMaster} from "../diamond/shared/OwnableMaster.sol";
import {CohortWeeks} from "../diamond/shared/CohortWeeks.sol";
/**
* @dev Storage, constants, events and errors of the referral hub, shared by
* the hub diamond and every facet. Sources are keyed by bytes32 because the
* CREATE3 vaults share one address across chains, and claimables are kept
* per source chain. Week W's ladder inputs live in W's own bucket: the
* referred averages and the self averages, each summed over the sources.
* `sourceWeekOf[source][referrer][week]` holds a source's reported referred
* average for the week in the low half and the commission units already
* paid for it in the high half; `sourceSelfOf[source][referrer][week]` holds
* the source's reported self average; both are merged by maximum, so a
* source's report for a closed week only rises.
* `weekInputsOf[referrer][week]` holds the referred sum in the low half and
* the self sum in the high half. An average is at most three 80-bit lanes
* over one week by construction, so no half can overflow.
* `sourceChainIdOf` is the chain a source credits, written at its first
* delivery; `sourceListedFor` guards the per-referrer source list.
* `sourceSystemOf` tags a source with its vault system for indexers and the
* umbrella's accounting; pricing no longer reads it, and it freezes once
* the source delivered. MAX_SYSTEMS is permanent.
* `leverChangeQueuedAt` holds the proposal time of a queued master lever
* call, keyed by the hash of its canonical calldata (the setter rebuilds
* it from its decoded arguments, so trailing bytes never make a second
* usable key): a proposal is accepted only after `finalizeSetup`, and a
* grant (allowing a reporter, setting the router, setting a flush or
* designation source to a chain id) runs only as that exact call at least
* SELECTOR_CHANGE_DELAY after its proposal, the delay the vault side
* `payoutHub` pointer and every hub selector change already wait, and each
* proposal runs once; a revocation never waits.
* `elevationWindowsOf[referrer]` is the referrer's elevation history: one
* word per window, the from week in the low half and the until week in
* the high half (zero while open), at most MAX_ELEVATION_WINDOWS words;
* `elevatedFromWeek` and `elevatedUntilWeek` mirror the latest window.
* A week is priced as at the cap when any window holds it, so a grant
* after an end never changes the verdict of an earlier window.
* Threat model: only
* master-registered sources write, every write is a maximum or a cursor
* advance, and a cell is paid at most its cumulative due, so a replayed,
* reordered or duplicated delivery can never pay twice. The state the
* buckets retired (the score aggregates, checkpoints, freshness words,
* report retention and the remainder park) stays declared and unused, so
* the layout only ever grows at its tail.
*/
abstract contract ReferralHubDeclarations is OwnableMaster {
uint256 internal constant WEEK_HALF_SHIFT = 128;
uint256 internal constant WEEK_HALF_MASK = (1 << 128) - 1;
uint256 internal constant RATE_MASK = (1 << 16) - 1;
uint256 internal constant RATE_Y2_SHIFT = 16;
uint256 internal constant RATE_M_SHIFT = 32;
uint256 internal constant GAP_WEEK_MASK = (1 << 32) - 1;
uint256 internal constant BPS_DENOMINATOR = 10_000;
uint256 internal constant PAYOUT_STAMP_SHIFT = 8;
uint256 internal constant DESIGNATION_VERSION = 2;
uint256 internal constant DESIGNATION_PAYLOAD_LENGTH = 160;
uint256 internal constant MAX_DESIGNATION_FUTURE_DRIFT = 1 hours;
uint256 internal constant MAX_BOT_SHARE_BPS = 2_000;
uint256 internal constant MAX_SCHEDULE_HORIZON_WEEKS = 520;
struct RateTable {
uint32 effectiveFromWeek;
uint16 capBps;
uint16 y2RateBps;
uint16 mRateBps;
uint16 botShareBps;
uint16[8] tierBps;
uint96[8] thresholds;
}
// ---- Retired score state (unused, kept for the layout) ----
mapping(address => uint256) internal globalReferredScore;
mapping(address => uint256) internal globalSelfScore;
mapping(address => uint256[]) internal referrerCheckpoints;
mapping(bytes32 => mapping(address => uint256)) internal lastSourceReport;
// ---- The sources a referrer was ever reported from (and a retired report word) ----
mapping(address => bytes32[]) internal sourcesOf;
mapping(bytes32 => mapping(address => uint256)) internal previousSourceReport;
// ---- Week-versioned rate tables ----
RateTable[] internal rateTables;
// ---- Intake cursors + claimables ----
mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal paidCursor;
mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal paidRemainder;
mapping(uint256 => mapping(address => uint256)) public claimable;
uint256 public totalAccrued;
uint256 public totalClaimed;
uint256 public totalPayable;
// ---- Access + policy knobs ----
mapping(address => bool) public allowedReporter;
// Retired with the dwell-min schedule.
uint256[] internal dwellMinLog;
mapping(uint256 => mapping(address => address)) internal payoutAddress;
mapping(uint256 => mapping(address => uint256)) public payoutStamp;
// ---- Cross-chain flush mailbox ----
address public ccipRouter;
mapping(uint64 => mapping(address => uint256)) public flushSourceChainId;
mapping(uint64 => mapping(address => uint256)) public designationSourceChainId;
mapping(bytes32 => bytes32) public flushCommitment;
// Retired with the per-envelope score report.
mapping(bytes32 => mapping(address => uint256)) internal appliedScoreStamp;
// ---- Diamond proxy ----
IERC20 public USD_TOKEN;
mapping(bytes4 => address) public selectorToFacet;
mapping(bytes4 => address) public proposedSelectorFacet;
mapping(bytes4 => uint256) public selectorChangeQueuedAt;
bool public initialized;
uint256 internal constant SELECTOR_CHANGE_DELAY = 3 days;
// ---- Courier share cap ----
uint256 public delivererShareCap;
// ---- Vault systems ----
uint256 public constant MAX_SYSTEMS = 8;
mapping(bytes32 => uint256) public sourceSystemOf;
// ---- Week buckets ----
mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal sourceWeekOf;
mapping(address => mapping(uint256 => uint256)) internal weekInputsOf;
mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal sourceSelfOf;
mapping(bytes32 => uint256) public sourceChainIdOf;
mapping(address => mapping(bytes32 => bool)) internal sourceListedFor;
// ---- Lever timelock ----
mapping(bytes32 => uint256) public leverChangeQueuedAt;
// ---- Elevation (a referrer priced as at the cap for a week window) ----
mapping(address => uint256) public elevatedFromWeek;
mapping(address => uint256) public elevatedUntilWeek;
// ---- Elevation window history (every window keeps its verdict) ----
uint256 internal constant MAX_ELEVATION_WINDOWS = 8;
mapping(address => uint256[]) internal elevationWindowsOf;
// ---- Events ----
event RateTableScheduled(
uint256 indexed index,
uint256 effectiveFromWeek
);
event CrumbPriced(
bytes32 indexed source,
address indexed referrer,
uint256 indexed week,
address deliverer,
uint256 y1Increment,
uint256 y2Increment,
uint256 mIncrement,
uint256 paid
);
event GapPriced(
bytes32 indexed source,
address indexed referrer,
address deliverer,
uint256 fromWeek,
uint256 toWeekExclusive,
uint256 paid
);
event CrumbLaneRegression(
bytes32 indexed source,
address indexed referrer,
uint256 indexed week,
uint256 laneKind,
uint256 incoming,
uint256 cursor
);
event ReporterAllowedSet(
address indexed reporter,
bool allowed
);
event PayoutAddressSet(
uint256 indexed chainId,
address indexed owner,
address indexed payout
);
event PayoutClaimed(
uint256 indexed chainId,
address indexed referrer,
address indexed payout,
uint256 amount
);
event CcipRouterSet(
address indexed router
);
event FlushSourceSet(
uint64 indexed chainSelector,
address indexed vault,
uint256 chainId
);
event DesignationSourceSet(
uint64 indexed chainSelector,
address indexed registry,
uint256 chainId
);
event FlushReceived(
bytes32 indexed messageId,
uint64 indexed srcChainSelector,
address indexed vault,
uint256 chainId,
bytes payload
);
event FlushApplied(
bytes32 indexed messageId,
bytes32 indexed source,
uint256 entryCount
);
event DesignationPushReceived(
uint64 indexed srcChainSelector,
uint256 indexed chainId,
address indexed owner
);
event DelivererSharePaid(
uint256 indexed chainId,
address indexed deliverer,
address indexed referrer,
bytes32 messageId,
uint256 amount
);
event FlushDesignationSkipped(
uint256 indexed chainId,
address indexed owner,
uint256 stamp
);
event SetupFinalized();
event ReferrerElevated(
address indexed referrer,
uint256 fromWeek
);
event ReferrerElevationEnded(
address indexed referrer,
uint256 untilWeek
);
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 DelivererShareCapSet(
uint256 cap
);
event SourceListed(
address indexed referrer,
bytes32 indexed source,
uint256 chainId
);
event WeekReferredReported(
bytes32 indexed source,
address indexed referrer,
uint256 indexed week,
uint256 referredAverage
);
event WeekSelfReported(
bytes32 indexed source,
address indexed referrer,
uint256 indexed week,
uint256 selfAverage
);
event WeekRatesRaised(
address indexed referrer,
uint256 indexed week
);
event WeekToppedUp(
bytes32 indexed source,
address indexed referrer,
uint256 indexed week,
uint256 amount
);
event SourceSystemSet(
bytes32 indexed source,
uint256 systemId
);
event LeverChangeProposed(
bytes32 indexed changeHash,
bytes call,
uint256 executableAt
);
event LeverChangeCancelled(
bytes32 indexed changeHash
);
// ---- Errors ----
error ZeroAddress();
error NotReporter();
error FutureWeek();
error WeekNotClosed();
error InvalidSelfRun();
error LengthMismatch();
error BatchTooLarge();
error InvalidCrumbWord();
error InvalidGapRecord();
error InvalidWindow();
error TableNotFuture();
error TableNotOrdered();
error InvalidRateTable();
error NothingClaimable();
error PotDry();
error NotPayoutAuthorized();
error NotCcipRouter();
error UnknownFlushSource();
error FlushAlreadyReceived();
error UnknownFlushCommitment();
error FlushPayloadInvalid();
error BotShareTooHigh();
error SourceOnHubChain();
error WeekOutOfRange();
error SourceAlreadySet();
error SystemOutOfRange();
error LeverChangeNotQueued();
error LeverTimelockNotElapsed();
error SetupNotFinalized();
error ElevationNotFuture();
error AlreadyElevated();
error NotElevated();
error ElevationHistoryFull();
/**
* @dev Consumes the queued lever change a grant runs as. Before
* `finalizeSetup` the grant runs at once (the deploy wiring needs no
* proposal); afterwards only the exact call master queued at least
* SELECTOR_CHANGE_DELAY earlier passes, and the entry is cleared so
* each proposal runs once.
*/
function _consumeLeverChange(
bytes32 _changeHash
)
internal
{
if (initialized == false) {
return;
}
uint256 queuedAt = leverChangeQueuedAt[_changeHash];
require(
queuedAt > 0,
LeverChangeNotQueued()
);
require(
block.timestamp >= queuedAt + SELECTOR_CHANGE_DELAY,
LeverTimelockNotElapsed()
);
leverChangeQueuedAt[_changeHash] = 0;
}
/**
* @dev The launch ladder: thresholds 5k to 1M USD, tiers 1 to 8
* percent, cap 1_000 bps, year-2 500 bps, mature 100 bps, courier share
* 500 bps.
*/
function _seedGenesisRateTable()
internal
{
rateTables.push(
RateTable({
effectiveFromWeek: 0,
capBps: 1_000,
y2RateBps: 500,
mRateBps: 100,
botShareBps: 500,
tierBps: [
uint16(100),
200,
300,
400,
500,
600,
700,
800
],
thresholds: [
uint96(5_000 * 1e6),
10_000 * 1e6,
20_000 * 1e6,
30_000 * 1e6,
50_000 * 1e6,
100_000 * 1e6,
500_000 * 1e6,
1_000_000 * 1e6
]
})
);
emit RateTableScheduled(
0,
0
);
}
}
src/hub/ReferralHubFacetBase.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {ReferralHubDeclarations} from "./ReferralHubDeclarations.sol";
import {OwnableMaster} from "../diamond/shared/OwnableMaster.sol";
import {OnlyDelegateCall} from "../diamond/shared/DiamondErrors.sol";
/**
* @dev ReferralHubFacetBase: the delegatecall guard of the routed hub
* facets; a direct call to a facet address reverts OnlyDelegateCall.
*/
abstract contract ReferralHubFacetBase is ReferralHubDeclarations {
address internal immutable _self;
constructor()
OwnableMaster(
msg.sender
)
{
_self = address(this);
}
modifier onlyDelegateCall() {
require(
address(this) != _self,
OnlyDelegateCall()
);
_;
}
}
src/hub/ReferralHubIntake.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {ReferralHubRates} from "./ReferralHubRates.sol";
import {CohortWeeks} from "../diamond/shared/CohortWeeks.sol";
import {CohortFlushCodec} from "../diamond/shared/CohortFlushCodec.sol";
/**
* @dev ReferralHubIntake: the only writer of week buckets, paid cursors and
* claimables. Only closed weeks are taken. A crumb or gap week first reports
* its own referred average into W's bucket, a self run reports its weekly
* self average, and a source's report for W is final, merged by maximum;
* W's inputs are the sums of the sources' reports, referred and self.
* Every (source, referrer, week) is paid exactly `floor(sum of lane times
* rate / (BPS times YEAR))` over its cumulative cursor at W's current
* rates, so a replay pays nothing twice and a regressing lane emits
* CrumbLaneRegression and pays zero. A report that raises W's rates
* records the bucket and emits WeekRatesRaised; a report that raises them
* also re-settles its own source's cell, so a vault's later report never
* leaves its own earlier crumb or gap week underpaid, and the permissionless
* `settleWeeks` re-settles every other source already paid for W at W's
* current rates, so W's price never depends on the order its sources
* arrive in once settled, no top-up is ever negative because a bucket
* only rises, and an apply's gas is bounded by its work alone, never by
* how many sources a referrer is listed at. The referrer is always
* credited the full commission; the courier fee is paid by the protocol
* on top of a delivered increment, on that increment's own due at the
* week's current rates and never on a top-up (not even one a delivery
* collects for its own source), only when the deliverer is set and is not
* the referrer (a vault names the caller as deliverer only when the caller
* is one of its allowed flush bots), at the week's `botShareBps`, clamped by `delivererShareCap` when that cap is
* nonzero (zero means no cap); `totalAccrued` counts both. A source's word
* for a closed week is final, so a delivery that raises its referred
* average also moves its cursor and settles its own cell; one that raises
* the average with no lane above the cursor tops its own cell up the same
* way. A self run's average is at most one 80-bit lane over one week, the
* bound a crumb lane and a gap record already carry. Every credited amount
* is payable at once, to the owner's own address on the hub chain until a
* designation redirects it, so `totalPayable`, the amount the hub's pot
* owes, is kept equal to `totalAccrued`.
*/
abstract contract ReferralHubIntake is ReferralHubRates {
struct DeliveryOrigin {
uint256 chainId;
address deliverer;
bytes32 messageId;
}
function _listSource(
bytes32 _source,
address _referrer,
uint256 _chainId
)
internal
{
if (sourceListedFor[_referrer][_source] == true) {
return;
}
sourceListedFor[_referrer][_source] = true;
sourcesOf[_referrer].push(
_source
);
if (sourceChainIdOf[_source] == 0) {
sourceChainIdOf[_source] = _chainId;
}
emit SourceListed(
_referrer,
_source,
sourceChainIdOf[_source]
);
}
function _applySelfRun(
bytes32 _source,
address _referrer,
uint256 _run,
uint256 _chainId
)
internal
returns (uint256)
{
uint256 fromWeek = CohortFlushCodec._selfRunFromWeek(
_run
);
uint256 toWeek = CohortFlushCodec._selfRunToWeek(
_run
);
require(
_run >> CohortFlushCodec.SELF_RUN_RESERVED_SHIFT == 0
&& fromWeek < toWeek
&& toWeek <= block.timestamp / CohortWeeks.WEEK
&& toWeek - fromWeek <= CohortWeeks.MAX_SETTLE_BOUNDARIES,
InvalidSelfRun()
);
_listSource(
_source,
_referrer,
_chainId
);
uint256 average = CohortFlushCodec._selfRunAverage(
_run
);
require(
average <= CohortWeeks.LANE_MASK_80 / CohortWeeks.WEEK,
InvalidSelfRun()
);
for (uint256 week = fromWeek; week < toWeek; ++week) {
_recordSelf(
_source,
_referrer,
week,
average
);
}
return toWeek - fromWeek;
}
function _recordReferred(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _average
)
internal
returns (bool)
{
uint256 word = sourceWeekOf[_source][_referrer][_week];
uint256 previous = word & WEEK_HALF_MASK;
if (_average <= previous) {
return false;
}
uint256 ratesBefore = _packedRates(
_referrer,
_week
);
sourceWeekOf[_source][_referrer][_week] = word
- previous
+ _average;
weekInputsOf[_referrer][_week] += _average - previous;
emit WeekReferredReported(
_source,
_referrer,
_week,
_average
);
return _noteRatesRaised(
_referrer,
_week,
ratesBefore
);
}
function _recordSelf(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _average
)
internal
{
uint256 previous = sourceSelfOf[_source][_referrer][_week];
if (_average <= previous) {
return;
}
uint256 ratesBefore = _packedRates(
_referrer,
_week
);
sourceSelfOf[_source][_referrer][_week] = _average;
weekInputsOf[_referrer][_week] += (_average - previous) << WEEK_HALF_SHIFT;
emit WeekSelfReported(
_source,
_referrer,
_week,
_average
);
bool raised = _noteRatesRaised(
_referrer,
_week,
ratesBefore
);
if (raised == false) {
return;
}
_topUpSourceWeek(
_source,
_referrer,
_week
);
}
function _topUpSourceWeek(
bytes32 _source,
address _referrer,
uint256 _week
)
internal
{
uint256 amount = _settleSourceWeek(
_source,
_referrer,
_week,
_packedRates(
_referrer,
_week
)
);
if (amount > 0) {
emit WeekToppedUp(
_source,
_referrer,
_week,
amount
);
}
}
function _noteRatesRaised(
address _referrer,
uint256 _week,
uint256 _ratesBefore
)
internal
returns (bool)
{
uint256 rates = _packedRates(
_referrer,
_week
);
if (rates == _ratesBefore) {
return false;
}
emit WeekRatesRaised(
_referrer,
_week
);
return true;
}
function _settleWeekSources(
address _referrer,
uint256 _week
)
internal
{
uint256 rates = _packedRates(
_referrer,
_week
);
bytes32[] storage sources = sourcesOf[_referrer];
for (uint256 i; i < sources.length; ++i) {
uint256 amount = _settleSourceWeek(
sources[i],
_referrer,
_week,
rates
);
if (amount > 0) {
emit WeekToppedUp(
sources[i],
_referrer,
_week,
amount
);
}
}
}
function _packedRates(
address _referrer,
uint256 _week
)
internal
view
returns (uint256)
{
(
uint256 y1Bps,
uint256 y2Bps,
uint256 mBps
) = _weeklyRates(
_referrer,
_week
);
return y1Bps
| (y2Bps << RATE_Y2_SHIFT)
| (mBps << RATE_M_SHIFT);
}
function _settleSourceWeek(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _rates
)
internal
returns (uint256 amount)
{
uint256 cursorWord = paidCursor[_source][_referrer][_week];
if (cursorWord == 0) {
return 0;
}
uint256 due = _dueOf(
cursorWord,
_rates
);
uint256 word = sourceWeekOf[_source][_referrer][_week];
uint256 paidSoFar = word >> WEEK_HALF_SHIFT;
if (due <= paidSoFar) {
return 0;
}
amount = due - paidSoFar;
sourceWeekOf[_source][_referrer][_week] = (word & WEEK_HALF_MASK)
| (due << WEEK_HALF_SHIFT);
_creditClaimable(
sourceChainIdOf[_source],
_referrer,
amount
);
}
function _dueOf(
uint256 _cursorWord,
uint256 _rates
)
internal
pure
returns (uint256)
{
return (
CohortWeeks._laneY1(
_cursorWord
) * (_rates & RATE_MASK)
+ CohortWeeks._laneY2(
_cursorWord
) * ((_rates >> RATE_Y2_SHIFT) & RATE_MASK)
+ CohortWeeks._laneM(
_cursorWord
) * (_rates >> RATE_M_SHIFT)
) / (BPS_DENOMINATOR * CohortWeeks.YEAR);
}
function _deliverCrumb(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _word,
DeliveryOrigin memory _origin
)
internal
{
if (_word == 0) {
return;
}
require(
_word & ~_crumbWordMask() == 0,
InvalidCrumbWord()
);
require(
_week < block.timestamp / CohortWeeks.WEEK,
WeekNotClosed()
);
_listSource(
_source,
_referrer,
_origin.chainId
);
uint256 lanes = _word & ~CohortWeeks.CRUMB_WRITTEN_BIT;
bool raised = _recordReferred(
_source,
_referrer,
_week,
(
CohortWeeks._laneY1(
lanes
)
+ CohortWeeks._laneY2(
lanes
)
+ CohortWeeks._laneM(
lanes
)
) / CohortWeeks.WEEK
);
(
uint256 paid,
uint256 incrementWord
) = _priceWeek(
_source,
_referrer,
_week,
lanes,
_origin
);
if (incrementWord == 0 && raised == true) {
_topUpSourceWeek(
_source,
_referrer,
_week
);
}
if (incrementWord == 0) {
return;
}
emit CrumbPriced(
_source,
_referrer,
_week,
_origin.deliverer,
CohortWeeks._laneY1(
incrementWord
),
CohortWeeks._laneY2(
incrementWord
),
CohortWeeks._laneM(
incrementWord
),
paid
);
}
function _deliverGap(
bytes32 _source,
address _referrer,
uint256 _record,
uint256 _fromWeek,
uint256 _maxWeeks,
DeliveryOrigin memory _origin
)
internal
{
(
uint256 toWeekExclusive,
uint256 mature
) = _parseGapRecord(
_record,
_fromWeek,
_maxWeeks
);
_listSource(
_source,
_referrer,
_origin.chainId
);
uint256 end = _windowEnd(
_fromWeek,
_maxWeeks,
toWeekExclusive
);
(
uint256 paidTotal,
uint256 incrementTotal
) = _priceGapWindow(
_source,
_referrer,
mature,
_fromWeek,
end,
_origin
);
if (incrementTotal == 0) {
return;
}
emit GapPriced(
_source,
_referrer,
_origin.deliverer,
_fromWeek,
end,
paidTotal
);
}
function _parseGapRecord(
uint256 _record,
uint256 _fromWeek,
uint256 _maxWeeks
)
internal
view
returns (
uint256 toWeekExclusive,
uint256 mature
)
{
uint256 fromWeek = _record & GAP_WEEK_MASK;
toWeekExclusive = (_record >> CohortWeeks.GAP_TO_SHIFT) & GAP_WEEK_MASK;
mature = (_record >> CohortWeeks.GAP_MATURE_SHIFT) & CohortWeeks.LANE_MASK_80;
require(
fromWeek < toWeekExclusive
&& _record >> (CohortWeeks.GAP_MATURE_SHIFT + 80) == 0
&& mature <= CohortWeeks.LANE_MASK_80 / CohortWeeks.WEEK,
InvalidGapRecord()
);
require(
toWeekExclusive <= block.timestamp / CohortWeeks.WEEK,
FutureWeek()
);
require(
_maxWeeks > 0
&& _fromWeek >= fromWeek
&& _fromWeek < toWeekExclusive,
InvalidWindow()
);
}
function _windowEnd(
uint256 _fromWeek,
uint256 _maxWeeks,
uint256 _toWeekExclusive
)
internal
pure
returns (uint256)
{
uint256 window = _maxWeeks < CohortWeeks.MAX_SETTLE_BOUNDARIES
? _maxWeeks
: CohortWeeks.MAX_SETTLE_BOUNDARIES;
return _fromWeek + window < _toWeekExclusive
? _fromWeek + window
: _toWeekExclusive;
}
function _priceGapWindow(
bytes32 _source,
address _referrer,
uint256 _mature,
uint256 _fromWeek,
uint256 _end,
DeliveryOrigin memory _origin
)
internal
returns (
uint256 paidTotal,
uint256 incrementTotal
)
{
uint256 quantityWord = CohortWeeks._packLanes(
0,
0,
_mature * CohortWeeks.WEEK
);
for (uint256 week = _fromWeek; week < _end; ++week) {
_recordReferred(
_source,
_referrer,
week,
_mature
);
(
uint256 paid,
uint256 incrementWord
) = _priceWeek(
_source,
_referrer,
week,
quantityWord,
_origin
);
paidTotal += paid;
incrementTotal += incrementWord;
}
}
function _priceWeek(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _quantityWord,
DeliveryOrigin memory _origin
)
internal
returns (
uint256 paid,
uint256 incrementWord
)
{
incrementWord = _cursorIncrements(
_source,
_referrer,
_week,
_quantityWord
);
if (incrementWord == 0) {
return (
0,
0
);
}
uint256 rates = _packedRates(
_referrer,
_week
);
uint256 dueBefore = _dueOf(
paidCursor[_source][_referrer][_week],
rates
);
_advanceCursor(
_source,
_referrer,
_week,
_quantityWord
);
paid = _settleSourceWeek(
_source,
_referrer,
_week,
rates
);
_payCourierFee(
_referrer,
_week,
_dueOf(
paidCursor[_source][_referrer][_week],
rates
) - dueBefore,
_origin
);
}
function _cursorIncrements(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _quantityWord
)
internal
returns (uint256 incrementWord)
{
uint256 cursorWord = paidCursor[_source][_referrer][_week];
incrementWord = CohortWeeks._packLanes(
_laneIncrement(
_source,
_referrer,
_week,
0,
CohortWeeks._laneY1(
_quantityWord
),
CohortWeeks._laneY1(
cursorWord
)
),
_laneIncrement(
_source,
_referrer,
_week,
1,
CohortWeeks._laneY2(
_quantityWord
),
CohortWeeks._laneY2(
cursorWord
)
),
_laneIncrement(
_source,
_referrer,
_week,
2,
CohortWeeks._laneM(
_quantityWord
),
CohortWeeks._laneM(
cursorWord
)
)
);
}
function _advanceCursor(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _quantityWord
)
internal
{
uint256 cursorWord = paidCursor[_source][_referrer][_week];
paidCursor[_source][_referrer][_week] = CohortWeeks._packLanes(
_max(
CohortWeeks._laneY1(
_quantityWord
),
CohortWeeks._laneY1(
cursorWord
)
),
_max(
CohortWeeks._laneY2(
_quantityWord
),
CohortWeeks._laneY2(
cursorWord
)
),
_max(
CohortWeeks._laneM(
_quantityWord
),
CohortWeeks._laneM(
cursorWord
)
)
);
}
function _payCourierFee(
address _referrer,
uint256 _week,
uint256 _increment,
DeliveryOrigin memory _origin
)
internal
{
if (
_increment == 0
|| _origin.deliverer == ZERO_ADDRESS
|| _origin.deliverer == _referrer
) {
return;
}
uint256 fee = _increment * _tableFor(
_week
).botShareBps / BPS_DENOMINATOR;
uint256 cap = delivererShareCap;
if (cap > 0 && fee > cap) {
fee = cap;
}
if (fee == 0) {
return;
}
_creditClaimable(
_origin.chainId,
_origin.deliverer,
fee
);
emit DelivererSharePaid(
_origin.chainId,
_origin.deliverer,
_referrer,
_origin.messageId,
fee
);
}
function _creditClaimable(
uint256 _chainId,
address _account,
uint256 _amount
)
internal
{
claimable[_chainId][_account] += _amount;
totalAccrued += _amount;
totalPayable = totalAccrued;
}
function _laneIncrement(
bytes32 _source,
address _referrer,
uint256 _week,
uint256 _laneKind,
uint256 _incoming,
uint256 _cursor
)
internal
returns (uint256)
{
if (_incoming > _cursor) {
return _incoming - _cursor;
}
if (_incoming < _cursor) {
emit CrumbLaneRegression(
_source,
_referrer,
_week,
_laneKind,
_incoming,
_cursor
);
}
return 0;
}
function _crumbWordMask()
internal
pure
returns (uint256)
{
return CohortWeeks.LANE_MASK_80
| (CohortWeeks.LANE_MASK_80 << CohortWeeks.LANE_Y2_SHIFT)
| (CohortWeeks.LANE_MASK_80 << CohortWeeks.LANE_M_SHIFT)
| CohortWeeks.CRUMB_WRITTEN_BIT;
}
function _max(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
return _a > _b
? _a
: _b;
}
}
src/hub/ReferralHubRates.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {ReferralHubCheckpoints} from "./ReferralHubCheckpoints.sol";
import {CohortWeeks} from "../diamond/shared/CohortWeeks.sol";
/**
* @dev ReferralHubRates: the week-versioned rate tables and `_weeklyRates`,
* the only rate computation. Year-1 pays the referrer's tier ladder up to
* the cap; year-2 and mature pay only in weeks where the uncapped ladder
* reaches the cap. A table keeps capBps within BPS, y2RateBps within capBps,
* mRateBps within y2RateBps, rising tiers and thresholds and botShareBps
* within MAX_BOT_SHARE_BPS, and applies to future weeks only. Every bps
* field is a rate per 52-week year (`CohortWeeks.YEAR`, 364 days): a
* cohort's year one runs from its credit to the 52nd week boundary after
* its credit week starts, year two the 52 weeks after that. An elevated
* referrer (master whitelist, every window of `elevationWindowsOf`, the
* latest mirrored by `elevatedFromWeek` and `elevatedUntilWeek`, an until
* week of zero meaning open) is priced as at the cap for every week any of
* its windows holds, whatever its inputs, and keeps that verdict for good;
* the inputs are recorded all the same, so the natural rate stays
* derivable from `ladderInputsAt` and the table. A referrer never elevated
* costs one warm SLOAD per priced week, the empty history's length.
*/
abstract contract ReferralHubRates is ReferralHubCheckpoints {
function weeklyRates(
address _referrer,
uint256 _week
)
external
view
returns (
uint256 y1Bps,
uint256 y2Bps,
uint256 mBps
)
{
return _weeklyRates(
_referrer,
_week
);
}
function rateTableCount()
external
view
returns (uint256)
{
return rateTables.length;
}
function rateTableAt(
uint256 _index
)
external
view
returns (RateTable memory)
{
return rateTables[_index];
}
function _pushRateTable(
RateTable memory _table
)
internal
{
_requireWithinHorizon(
_table.effectiveFromWeek
);
require(
_table.effectiveFromWeek > block.timestamp / CohortWeeks.WEEK,
TableNotFuture()
);
require(
_table.effectiveFromWeek > rateTables[rateTables.length - 1].effectiveFromWeek,
TableNotOrdered()
);
require(
_table.capBps <= BPS_DENOMINATOR
&& _table.y2RateBps <= _table.capBps
&& _table.mRateBps <= _table.y2RateBps,
InvalidRateTable()
);
require(
_table.botShareBps <= MAX_BOT_SHARE_BPS,
BotShareTooHigh()
);
for (uint256 i; i < 8; ++i) {
require(
_table.tierBps[i] <= BPS_DENOMINATOR
&& (i == 0 || _table.tierBps[i] >= _table.tierBps[i - 1]),
InvalidRateTable()
);
require(
_table.thresholds[i] > 0
&& (i == 0 || _table.thresholds[i] > _table.thresholds[i - 1]),
InvalidRateTable()
);
}
rateTables.push(
_table
);
emit RateTableScheduled(
rateTables.length - 1,
_table.effectiveFromWeek
);
}
function _weeklyRates(
address _referrer,
uint256 _week
)
internal
view
returns (
uint256 y1Bps,
uint256 y2Bps,
uint256 mBps
)
{
RateTable storage table = _tableFor(
_week
);
if (
_isElevatedAt(
_referrer,
_week
)
) {
return (
table.capBps,
table.y2RateBps,
table.mRateBps
);
}
(
uint256 referredInput,
uint256 selfInput
) = _ladderInputsAt(
_referrer,
_week
);
y1Bps = _tierBps(
table,
selfInput
) + _tierBps(
table,
referredInput
);
if (y1Bps > table.capBps) {
y1Bps = table.capBps;
}
if (y1Bps == table.capBps) {
y2Bps = table.y2RateBps;
mBps = table.mRateBps;
}
}
function _isElevatedAt(
address _referrer,
uint256 _week
)
internal
view
returns (bool)
{
uint256[] storage windows = elevationWindowsOf[_referrer];
uint256 count = windows.length;
for (uint256 i; i < count; ++i) {
uint256 window = windows[i];
uint256 untilWeek = window >> WEEK_HALF_SHIFT;
if (
_week >= (window & WEEK_HALF_MASK)
&& (untilWeek == 0 || _week < untilWeek)
) {
return true;
}
}
return false;
}
function _tableFor(
uint256 _week
)
internal
view
returns (RateTable storage)
{
return rateTables[
_lastAtOrBefore(
rateTables.length,
_week,
_tableWeekAt
)
];
}
function _tableWeekAt(
uint256 _index
)
internal
view
returns (uint256)
{
return rateTables[_index].effectiveFromWeek;
}
function _tierBps(
RateTable storage _table,
uint256 _value
)
internal
view
returns (uint256)
{
for (uint256 i = 8; i > 0; --i) {
if (_value >= _table.thresholds[i - 1]) {
return _table.tierBps[i - 1];
}
}
return 0;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"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.