Verified contractExact--
QueueJoinLeaveFacet
Address0x1b8d60ea04e4e70d75b59e27c7f3c0ab891d14e9
- 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,251,916
- Creation transaction
- 0x2ae0b2a6fe…a5523471fb
72 files
- src/diamond/vault/facets/QueueJoinLeaveFacet.solmain8.02 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/token/ERC20/ERC20.sol12.85 KB
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- 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
- node_modules/@openzeppelin/contracts/utils/Context.sol844 B
- node_modules/@openzeppelin/contracts/utils/math/Math.sol12.79 KB
- src/diamond/shared/DiamondErrors.sol336 B
- src/diamond/shared/OwnableMaster.sol2.04 KB
- src/diamond/shared/pending/CohortWeeks.sol22.34 KB
- src/diamond/vault/WiseSovrenNodesDiamondErrors.sol3.91 KB
- src/diamond/vault/WiseSovrenNodesDiamondEvents.sol14.7 KB
- src/diamond/vault/WiseSovrenNodesDiamondStructs.sol794 B
- src/diamond/vault/WiseSovrenNodesIncentiveLadder.sol4.09 KB
- src/diamond/vault/WiseSovrenNodesQueueStructs.sol1.27 KB
- src/diamond/vault/declarations/AutoCompoundDeclaration.sol1 KB
- src/diamond/vault/declarations/BridgeReplayDeclaration.sol1.08 KB
- src/diamond/vault/declarations/BurnWiseRotationDeclaration.sol944 B
- src/diamond/vault/declarations/CashedInterestTotalDeclaration.sol1.31 KB
- src/diamond/vault/declarations/ConfigDeclaration.sol948 B
- src/diamond/vault/declarations/CrossChainDeclaration.sol1.97 KB
- src/diamond/vault/declarations/DepositAccumDeclaration.sol1.51 KB
- src/diamond/vault/declarations/DepositAccumPrevDeclaration.sol906 B
- src/diamond/vault/declarations/DepositGateDeclaration.sol1.11 KB
- src/diamond/vault/declarations/DepositHookDeclaration.sol1.82 KB
- src/diamond/vault/declarations/GracePeriodDeclaration.sol1.91 KB
- src/diamond/vault/declarations/HookGuardDeclaration.sol645 B
- src/diamond/vault/declarations/InterestRemainderDeclaration.sol1.34 KB
- src/diamond/vault/declarations/PeerVaultDeclaration.sol872 B
- src/diamond/vault/declarations/ProxyDeclaration.sol204 B
- src/diamond/vault/declarations/QueueConfigDeclaration.sol539 B
- src/diamond/vault/declarations/QueueStateDeclaration.sol762 B
- src/diamond/vault/declarations/ReferralDeclaration.sol1.52 KB
- src/diamond/vault/declarations/SelectorRoutingDeclaration.sol632 B
- src/diamond/vault/declarations/SweeperDeclaration.sol997 B
- src/diamond/vault/declarations/ThirdPartyDeclaration.sol772 B
- src/diamond/vault/declarations/TransferHookDeclaration.sol1.53 KB
- src/diamond/vault/declarations/UserStateDeclaration.sol277 B
- src/diamond/vault/declarations/WiseDeclaration.sol572 B
- src/diamond/vault/declarations/WiseSovrenNodesDeclarations.sol11.99 KB
- src/diamond/vault/declarations/WorkerDeclaration.sol908 B
- src/diamond/vault/declarations/pending/CohortAttributionDeclaration.sol446 B
- src/diamond/vault/declarations/pending/CohortBookDeclaration.sol986 B
- src/diamond/vault/declarations/pending/CohortContributionDeclaration.sol2.03 KB
- src/diamond/vault/declarations/pending/CohortDisarmDeclaration.sol793 B
- src/diamond/vault/declarations/pending/CohortDivestDeclaration.sol488 B
- src/diamond/vault/declarations/pending/CohortFlushDeclaration.sol1.29 KB
- src/diamond/vault/declarations/pending/CohortSelfDeclaration.sol575 B
- src/diamond/vault/declarations/pending/CohortSelfLogDeclaration.sol1.2 KB
- src/diamond/vault/declarations/pending/PayoutHubPointerDeclaration.sol611 B
- src/diamond/vault/declarations/pending/ReferralPayoutDeclaration.sol465 B
- src/diamond/vault/declarations/pending/ReferralRegistryDeclaration.sol415 B
- src/diamond/vault/declarations/pending/ReferralRegistryPointerDeclaration.sol596 B
- src/diamond/vault/facets/QueueFacetBase.sol1.96 KB
- src/diamond/vault/helpers/WiseSovrenNodesAdminHelper.sol982 B
- src/diamond/vault/helpers/WiseSovrenNodesBaseHelper.sol22.67 KB
- src/diamond/vault/helpers/WiseSovrenNodesBufferHelper.sol2.73 KB
- src/diamond/vault/helpers/WiseSovrenNodesCrossChainHelper.sol16.31 KB
- src/diamond/vault/helpers/WiseSovrenNodesHelper.sol3.17 KB
- src/diamond/vault/helpers/WiseSovrenNodesInterestHelper.sol13.11 KB
- src/diamond/vault/helpers/WiseSovrenNodesMoveHelper.sol8.45 KB
- src/diamond/vault/helpers/WiseSovrenNodesProxyHelper.sol861 B
- src/diamond/vault/helpers/WiseSovrenNodesQueueHelper.sol14.69 KB
- src/diamond/vault/helpers/WiseSovrenNodesQueueLowLevelHelper.sol22.91 KB
- src/diamond/vault/interfaces/IPeerVault.sol399 B
- src/diamond/vault/interfaces/pending/IReferralRegistry.sol1.94 KB
src/diamond/vault/facets/QueueJoinLeaveFacet.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {QueueFacetBase} from "./QueueFacetBase.sol";
/**
* @dev User-facing join / leave / reduce surface for the queue.
*/
contract QueueJoinLeaveFacet is QueueFacetBase {
constructor()
QueueFacetBase()
{}
function joinQue(
uint256 _amount,
int256 _incentive
)
external
onlyDelegateCall
whenNotPaused
setProxyBenefactor
nonReentrant
returns (
QueMember memory,
uint256
)
{
if (negativeIncentivesNotAllowed == true) {
require(
_incentive >= 0,
NegativeIncentiveNotAllowed()
);
}
_validateJoinQue(
_amount,
_incentive
);
(
QueMember memory member,
uint256 newId
) = _createQueMember(
_amount,
_incentive
);
_updateJoinQueState(
_amount,
_incentive
);
_setProxyBenefactor(
msg.sender
);
_transferTokensIn(
_amount
);
emit JoinQue(
msg.sender,
_amount,
_incentive,
newId
);
return (
member,
newId
);
}
function leaveQue(
uint256 _queMemberId,
int256 _incentive
)
external
onlyDelegateCall
setProxyBenefactor
nonReentrant
returns (
QueMember memory,
uint256 leftOverAmount
)
{
_validateLeaveQue(
_queMemberId,
_incentive
);
QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_incentive];
leftOverAmount = member.amount;
_validateMemberCanLeave(
member
);
_updateCurrentOrderIfNeeded(
_queMemberId,
_incentive,
member
);
_finalizeMemberRemoval(
_queMemberId,
member,
_incentive,
true
);
_setProxyBenefactor(
msg.sender
);
_transferTokensOut(
msg.sender,
leftOverAmount
);
emit LeaveQue(
msg.sender,
_queMemberId,
_incentive,
leftOverAmount
);
return (
member,
leftOverAmount
);
}
function reduceQueAmount(
uint256 _queMemberId,
int256 _incentive,
uint256 _reduceBy
)
external
onlyDelegateCall
setProxyBenefactor
nonReentrant
returns (
QueMember memory,
uint256 leftOverAmount
)
{
_validateReduceAmount(
_queMemberId,
_incentive,
_reduceBy
);
QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_incentive];
_validateMemberCanReduce(
member,
_reduceBy
);
_executeReduction(
member,
_reduceBy
);
_setProxyBenefactor(
msg.sender
);
_transferTokensOut(
msg.sender,
_reduceBy
);
emit ReduceQueAmount(
msg.sender,
_queMemberId,
_incentive,
_reduceBy
);
return (
member,
member.amount
);
}
/**
* @dev Moves a whole order from `_oldIncentive` into `_newIncentive`
* without the leave-then-rejoin token round-trip. It composes the
* exact same internal helpers `leaveQue` + `joinQue` use, in the
* same order, but omits `_transferTokensOut` / `_transferTokensIn`
* because the escrowed vault shares never leave the vault — so the
* final storage is identical to `leaveQue(id, old)` immediately
* followed by `joinQue(amount, new)`. Being share-movement-free, it
* never invokes the transfer hook; a swappable `transferHookFacet`
* (behind its 3-day timelock) does not cover this path.
*/
function switchQueIncentive(
uint256 _queMemberId,
int256 _oldIncentive,
int256 _newIncentive
)
external
onlyDelegateCall
whenNotPaused
setProxyBenefactor
nonReentrant
returns (
QueMember memory newMember,
uint256 newId
)
{
require(
_oldIncentive != _newIncentive,
SameIncentive()
);
if (negativeIncentivesNotAllowed == true) {
require(
_newIncentive >= 0,
NegativeIncentiveNotAllowed()
);
}
_validateLeaveQue(
_queMemberId,
_oldIncentive
);
QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_oldIncentive];
_validateMemberCanLeave(
member
);
uint256 amount = member.amount;
_validateJoinQue(
amount,
_newIncentive
);
_updateCurrentOrderIfNeeded(
_queMemberId,
_oldIncentive,
member
);
_finalizeMemberRemoval(
_queMemberId,
member,
_oldIncentive,
true
);
(
newMember,
newId
) = _createQueMember(
amount,
_newIncentive
);
_updateJoinQueState(
amount,
_newIncentive
);
emit SwitchQueIncentive(
msg.sender,
_queMemberId,
_oldIncentive,
newId,
_newIncentive,
amount
);
}
/**
* @dev Peels `_amount` off an order in `_oldIncentive` into a new
* order in `_newIncentive`, leaving the remainder in place. Composes
* the same helpers `reduceQueAmount` + `joinQue` use, minus the
* token round-trip, so the final storage is identical to
* `reduceQueAmount(id, old, amount)` followed by
* `joinQue(amount, new)`. `_amount` must be strictly less than the
* order amount (a whole-order move must use `switchQueIncentive`).
* Share-movement-free and hook-free, as above.
*/
function switchQueIncentivePartial(
uint256 _queMemberId,
int256 _oldIncentive,
int256 _newIncentive,
uint256 _amount
)
external
onlyDelegateCall
whenNotPaused
setProxyBenefactor
nonReentrant
returns (
QueMember memory newMember,
uint256 newId
)
{
require(
_oldIncentive != _newIncentive,
SameIncentive()
);
if (negativeIncentivesNotAllowed == true) {
require(
_newIncentive >= 0,
NegativeIncentiveNotAllowed()
);
}
_validateReduceAmount(
_queMemberId,
_oldIncentive,
_amount
);
QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_oldIncentive];
_validateMemberCanReduce(
member,
_amount
);
_validateJoinQue(
_amount,
_newIncentive
);
_executeReduction(
member,
_amount
);
(
newMember,
newId
) = _createQueMember(
_amount,
_newIncentive
);
_updateJoinQueState(
_amount,
_newIncentive
);
emit SwitchQueIncentivePartial(
msg.sender,
_queMemberId,
_oldIncentive,
newId,
_newIncentive,
_amount
);
}
}
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/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
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/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
node_modules/@openzeppelin/contracts/token/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);
}
}
}
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;
}
}
node_modules/@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
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/shared/pending/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/vault/WiseSovrenNodesDiamondErrors.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Custom errors for the WiseSovrenNodes diamond. Selectors match
* the legacy error ABI so reverts decode identically.
*/
abstract contract WiseSovrenNodesDiamondErrors {
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 FlushCursorVirgin();
error FlushCadenceActive();
error FlushBookNotAdvanced();
}
src/diamond/vault/WiseSovrenNodesDiamondEvents.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Event signatures for the WiseSovrenNodes 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 WiseSovrenNodesDiamondEvents {
// ---- 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 InterestSynced(
address indexed user,
uint256 syncedAt
);
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
);
event IncentiveAllowedSet(
int256 indexed incentive,
bool allowed
);
// ---- 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/WiseSovrenNodesDiamondStructs.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Struct-wrapped constructor arguments for the WiseSovrenNodes
* diamond. Solidity's stack only fits seven or so locals plus the
* EVM scratch slots, so the legacy 11-arg constructor was already
* close to the limit; adding the worker role pushed it over. Passing
* one memory pointer keeps stack pressure flat and matches the
* shape callers want anyway.
*/
struct WiseSovrenNodesInitParams {
address usdAddress;
address thirdPartyAddress;
address workerAddress;
address oldVault;
address[] initialDistributionAddresses;
uint256[] initialDistributionAmounts;
uint256 totalDepositCap;
uint256 interestRate;
uint8 decimalsValue;
string tokenName;
string tokenSymbol;
}
src/diamond/vault/WiseSovrenNodesIncentiveLadder.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev The single source of truth for the queue incentive ladder.
*
* An incentive is a signed basis-point adjustment to the face value
* of a queued order: a fulfiller pays
* `amount * (10000 - incentive) / 10000`. Positive tiers are
* discounts, where a leaver accepts less than face value to exit
* sooner. Negative tiers are premiums, where a buyer pays more than
* face value to take the position over.
*
* The discount side keeps the nine tiers of the original vault: zero
* plus 1, 2, 3, 5, 10, 15, 25 and 50 percent. The premium side is a
* flat ladder in twenty-percentage-point steps, so tier `i` charges
* `1 + i/5` times face value, from 1.2x at the first rung up to 50x
* at the two hundred and forty-fifth. Steps are flat rather than
* compounding, so the rungs are evenly spaced in price.
*
* Every consumer reads the ladder from here. The seeding loop that
* marks tiers allowed in the constructor, the solver's lane walk,
* the forecast facet and the cost-prediction views all enumerate the
* same arrays, which makes "allowed" and "reachable by the solver"
* the same set by construction. A tier that were allowed but absent
* from the traversal would accept orders that no quote could ever
* see, and a tier traversed but not allowed would be planned against
* and then revert on execution. The membership predicate
* `isLadderLane` lets the lane setter reject anything outside these
* arrays, so the guarantee holds for later admin calls and not only
* for the paths that read the arrays directly.
*
* Order matters as much as membership. Both arrays run best-price
* first from the buyer's point of view, deepest discount down to
* zero and then cheapest premium upward, because the solver consumes
* lanes in array order and its plan is only optimal if the array is
* sorted that way.
*
* The ladder is compiled in rather than passed at construction
* precisely so that it cannot drift: a constructor argument could
* seed a set that disagrees with the traversal arrays the solver was
* compiled against.
*/
library WiseSovrenNodesIncentiveLadder {
int256 internal constant PREMIUM_STEP = 2_000;
uint256 internal constant POSITIVE_LANE_COUNT = 9;
uint256 internal constant PREMIUM_LANE_COUNT = 245;
function positiveIncentives()
internal
pure
returns (int256[] memory lanes)
{
lanes = new int256[](POSITIVE_LANE_COUNT);
lanes[0] = 5_000;
lanes[1] = 2_500;
lanes[2] = 1_500;
lanes[3] = 1_000;
lanes[4] = 500;
lanes[5] = 300;
lanes[6] = 200;
lanes[7] = 100;
lanes[8] = 0;
}
function negativeIncentives()
internal
pure
returns (int256[] memory lanes)
{
lanes = new int256[](PREMIUM_LANE_COUNT);
for (uint256 i; i < PREMIUM_LANE_COUNT; ++i) {
lanes[i] = -PREMIUM_STEP * int256(i + 1);
}
}
function allIncentives()
internal
pure
returns (int256[] memory lanes)
{
int256[] memory positives = positiveIncentives();
lanes = new int256[](POSITIVE_LANE_COUNT + PREMIUM_LANE_COUNT);
for (uint256 i; i < POSITIVE_LANE_COUNT; ++i) {
lanes[i] = positives[i];
}
for (uint256 j; j < PREMIUM_LANE_COUNT; ++j) {
lanes[POSITIVE_LANE_COUNT + j] = -PREMIUM_STEP * int256(j + 1);
}
}
function isLadderLane(
int256 _incentive
)
internal
pure
returns (bool)
{
if (_incentive < 0) {
if (_incentive < -PREMIUM_STEP * int256(PREMIUM_LANE_COUNT)) {
return false;
}
return _incentive % PREMIUM_STEP == 0;
}
int256[] memory positives = positiveIncentives();
for (uint256 i; i < POSITIVE_LANE_COUNT; ++i) {
if (positives[i] == _incentive) {
return true;
}
}
return false;
}
}
src/diamond/vault/WiseSovrenNodesQueueStructs.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Shared structs for the queue surface of the merged
* WiseSovrenNodes diamond — held on a separate abstract so shards and
* helpers can reference them without circular imports.
*/
abstract contract WiseSovrenNodesQueueStructs {
struct QueMember {
address member;
uint256 amount;
uint256 tailPointer;
uint256 headPointer;
}
struct QueMemberWithId {
uint256 memberId;
int256 incentive;
address member;
uint256 amount;
uint256 tailPointer;
uint256 headPointer;
}
struct SolveForAmountVars {
int256[] incs;
int256[] tempIncentives;
uint256[] tempOrders;
uint256[] tempPartials;
uint256 orderIndex;
uint256 partialIndex;
}
struct PlanVars {
uint256 arraySize;
uint256 partialId;
uint256 fullIndex;
uint256 current;
uint256 ordersConsidered;
bool hasPartial;
}
struct FulfillOrderBulkVars {
int256[] incentives;
uint256[] orders;
uint256[] partials;
uint256 partialAmount;
uint256 minReceiveAmount;
uint256 maxUsdToSpend;
}
}
src/diamond/vault/declarations/AutoCompoundDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Auto-compound tail shard. `isAutoCompoundBot` is the
* master-set keeper allowlist, `autoCompoundAllowed` the per-user
* opt-in and `autoCompoundFeeBps` the keeper reward in basis points
* of the compounded interest (100 = 1%), capped at
* `MAX_AUTO_COMPOUND_FEE_BPS`. All three default to zero, so a
* diamond routing the facet with zeroed tail storage compounds
* nothing until configured. Appended as a tail shard so it takes
* fresh slots 64-66 and moves no pre-existing slot; first shard
* activated onto live diamonds post-genesis, whose frozen
* dispatchers cannot serve the getters, so their selectors are
* routed alongside the functions.
*/
abstract contract AutoCompoundDeclaration {
mapping(address => bool) public isAutoCompoundBot;
mapping(address => bool) public autoCompoundAllowed;
uint256 public autoCompoundFeeBps;
uint256 internal constant MAX_AUTO_COMPOUND_FEE_BPS = 500;
}
src/diamond/vault/declarations/BridgeReplayDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Bridge-hardening tail shard. `processedMessageId[id]` records
* every CCIP message this vault has already minted against, so a
* re-delivered `ccipReceive` can never mint twice — a defense-in-depth
* idempotency guard layered on top of CCIP's own exactly-once delivery.
*
* `proposedCrossChainPeer[selector]` and `proposedCrossChainPeerDecimals`
* stage a pending cross-chain peer so that repointing an already-enabled
* lane is bound by the same `CROSS_CHAIN_PEER_CHANGE_DELAY` timelock as a
* first-time enable: the live `crossChainPeer` mapping only moves on
* `executeCrossChainPeerChange`, never on `proposeCrossChainPeer`.
*
* Appended last in the declarations linearisation so it takes fresh tail
* slots and moves no pre-existing slot.
*/
abstract contract BridgeReplayDeclaration {
mapping(bytes32 => bool) public processedMessageId;
mapping(uint64 => address) public proposedCrossChainPeer;
mapping(uint64 => uint8) public proposedCrossChainPeerDecimals;
}
src/diamond/vault/declarations/BurnWiseRotationDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Rotating WISE-burn shard. `burnWise` no longer burns the whole
* accumulated balance in one call; instead each successful burn takes
* a rotating slice of the current balance from a fixed looping
* basis-point sequence and advances `burnWiseIndex` by one (wrapping).
* `lastBurnWiseAt` records the last successful burn timestamp per
* caller so a single address cannot spam the permissionless surface
* more than once per `BURN_WISE_COOLDOWN`. The percentage sequence
* itself lives in a `pure` helper on {BurnWiseFacet} because
* Solidity has no constant arrays. Appended last as a tail shard so it
* takes fresh slots and moves no pre-existing slot.
*/
abstract contract BurnWiseRotationDeclaration {
uint256 public burnWiseIndex;
mapping(address => uint256) public lastBurnWiseAt;
uint256 internal constant BURN_WISE_COOLDOWN = 1 days;
}
src/diamond/vault/declarations/CashedInterestTotalDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Global cashed-interest ledger shard. `totalCashedInterest`
* mirrors the sum of the per-user `cashedInterest` mapping at all
* times: accrual (`_assignInterest`) adds the banked pending
* interest, `_prepareClaim` subtracts the zeroed bucket,
* `_prepareExactAmountClaim` subtracts the debited amount, and the
* constructor migration seed (`_migrateInterest`) applies the
* per-address delta so duplicate distribution addresses cannot
* double-count. `_executeMoveInterestTo` shifts interest between
* users and is net-zero for the sum, so it deliberately leaves the
* accumulator untouched. Every mutation emits
* `TotalCashedInterestChanged` with the new running total. The
* accumulator feeds `_calculateNeededBuffer` so the sweeper-gated
* `sweepOverhang` reserves the settled, already-claimable interest
* liability on top of the two-week forward buffer and can no longer
* strand pending claims. Declared `internal` rather than `public`:
* the single external surface is
* `CashedInterestFacet.getTotalCashedInterest()`. Appended
* as a tail shard so it takes a fresh tail slot and moves no
* pre-existing slot.
*/
abstract contract CashedInterestTotalDeclaration {
uint256 internal totalCashedInterest;
}
src/diamond/vault/declarations/ConfigDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Vault configuration storage shard. USD_TOKEN sits in storage
* (was `immutable` in legacy) so it survives DELEGATECALL into
* facets.
*/
abstract contract ConfigDeclaration {
IERC20 public USD_TOKEN;
uint256 public interestRate;
uint8 internal decimalsSet;
address public thirdPartyAddress;
address public InterestRateProxy;
address public currentProxyBenefactor;
bool public supplyChangeByOwnerNotAllowed;
uint256 public totalDepositCap;
bytes4 public constant IERC20Decimals = bytes4(keccak256("decimals()"));
uint256 internal constant SECONDS_IN_YEAR = 31_540_000;
uint256 internal constant PRECISION_RATE = 10_000;
uint256 internal constant PRECISION_FACTOR_E18 = 1e18;
uint256 internal constant MAX_INTEREST_RATE = 20_000;
}
src/diamond/vault/declarations/CrossChainDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Cross-chain bridge shard. `ccipRouter` is the Chainlink CCIP
* router this diamond sends through and is authenticated as the sole
* caller of `ccipReceive`; it is set once and never rotated.
* `crossChainPeer[selector]` is the sibling vault (same underlying
* stablecoin) on the chain identified by that CCIP `selector`, and
* `crossChainPeerEnabled[selector]` gates both outbound bridging to
* and inbound minting from that chain. `crossChainPeerDecimals`
* records the peer's share decimals so `bridgeToVault` can scale the
* amount the same way `moveBetweenVaults` does on-chain.
*
* `crossChainPeerChangeQueuedAt` backs a propose/execute flow behind
* `CROSS_CHAIN_PEER_CHANGE_DELAY` (3 days) that mirrors the selector
* routing timelock: instant while the diamond is still being wired
* (before `finalizeSetup`), timelocked afterwards, so a compromised
* master cannot instantly register a malicious peer that would mint
* unbacked shares. `BRIDGE_GAS_LIMIT` is the callback budget CCIP
* grants the destination `ccipReceive` for the mint path.
*
* Unlike the same-chain mover, peer registration deliberately has NO
* `_peer != address(this)` guard: the deterministic CREATE3 rollout
* gives every vault in a mesh the identical canonical address, so
* `RegisterCrossChainPeers` registers this diamond's own address as
* the peer for every remote selector. Such a guard would brick the
* production mesh wiring.
*/
abstract contract CrossChainDeclaration {
address public ccipRouter;
mapping(uint64 => address) public crossChainPeer;
mapping(uint64 => bool) public crossChainPeerEnabled;
mapping(uint64 => uint8) public crossChainPeerDecimals;
mapping(uint64 => uint256) public crossChainPeerChangeQueuedAt;
uint256 internal constant CROSS_CHAIN_PEER_CHANGE_DELAY = 3 days;
uint256 internal constant BRIDGE_GAS_LIMIT = 200_000;
}
src/diamond/vault/declarations/DepositAccumDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Two-bucket deposit-accumulator shard backing
* `GraceAccumHookFacet`. `depositAccumWindow` is the master-set
* bucket length in seconds over which sub-threshold share-balance
* increases of one user sum toward `graceThresholdAmount`; `0` — the
* shipped default, never seeded by the constructor or any deploy
* script — keeps the accumulator off so the installed hook
* reproduces the inline single-call semantics exactly until master
* arms it (instant, no timelock, `setDepositAccumWindow`, bounded by
* `MAX_GRACE_PERIOD`). `depositWindowStart` anchors the user's
* current bucket and `depositWindowTotal` is its running total; the
* full previous bucket is carried forward in
* `depositWindowPrevTotal` (its own follow-up tail shard,
* `DepositAccumPrevDeclaration`) and the hook always tests
* previous plus current, so deposits landing within one window of
* each other can never dodge the sum by straddling a bucket
* boundary (lookback bounded by two windows). All per-user records
* are cleared whenever a stamp happens, so post-stamp dust cannot
* re-stamp while another full cumulative threshold does. Appended
* as a tail shard so it takes fresh slots and moves no pre-existing
* slot.
*/
abstract contract DepositAccumDeclaration {
uint256 public depositAccumWindow;
mapping(address => uint256) public depositWindowStart;
mapping(address => uint256) public depositWindowTotal;
}
src/diamond/vault/declarations/DepositAccumPrevDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Previous-bucket extension of the deposit-accumulator shard
* (`DepositAccumDeclaration`), split out so the earlier tail
* shards keep their slots. `depositWindowPrevTotal` carries a user's
* full previous accumulation bucket forward; `applyDepositAccumHook`
* always tests it together with the current `depositWindowTotal`, so
* deposits within one `depositAccumWindow` of each other can never
* dodge the `graceThresholdAmount` sum by straddling a bucket
* boundary, while co-counting never reaches back two full windows.
* Cleared alongside the other window records on every stamp and on a
* two-window skip. Appended as a tail shard so it takes a fresh
* tail slot and moves no pre-existing slot.
*/
abstract contract DepositAccumPrevDeclaration {
mapping(address => uint256) public depositWindowPrevTotal;
}
src/diamond/vault/declarations/DepositGateDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Deposit-gate tail shard. `depositsDisabled` lets master switch
* off new capital inflow — the direct and Permit2 deposit paths, the
* only entrypoints that mint fresh shares from underlying — on a chain
* while everything else keeps working: withdrawals, queue joins and
* leaves, incentive switches, ERC20 transfers, outbound bridging and
* inbound `ccipReceive` mints are all unaffected. Queue operations
* only move already-minted shares between holders and the escrow, so
* they bring in no new capital and are never gated. This is the
* dormant-chain mechanism for the multichain rollout — a vault deploys
* fully wired into the bridge mesh but closed for deposits, and
* activation later is a single `setDepositsDisabled(false)`. It
* defaults to `false`, so an untouched vault behaves exactly as before.
*
* Packs into the free bytes of the `referralEnabled` / `bridgeGasLimit`
* slot, so it moves no pre-existing slot.
*/
abstract contract DepositGateDeclaration {
bool public depositsDisabled;
}
src/diamond/vault/declarations/DepositHookDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Swappable deposit-hook shard. `depositHookFacet` is an
* optional facet `_registerLargeDeposit` DELEGATECALLs with the
* decorated call's positive share-balance delta as the large-deposit
* detection policy. When it is `ZERO_ADDRESS` the inline single-call
* threshold check runs unchanged, so an already-deployed diamond
* that upgrades the interest helper without installing the facet
* behaves exactly as before. `proposedDepositHookFacet` +
* `depositHookChangeQueuedAt` back the propose/execute flow: instant
* while the diamond is still in setup (before `finalizeSetup`, like
* the transfer hook) so the deploy can install the initial hook at
* genesis, then 3-day timelocked afterwards so a compromised master
* cannot instantly repoint the stamping path; proposing
* `ZERO_ADDRESS` reverts back to the inline default. The deposit hook
* writes accumulator state, so it guards on the transient
* `hookExecuting` flag (`HookGuardDeclaration`) that only
* `_runDepositHook` sets: routing `DEPOSIT_HOOK_SELECTOR` into the
* diamond is therefore harmless — an external caller cannot satisfy
* the flag and can never stamp arbitrary users. Appended as a tail
* shard: `depositHookFacet` packs into the
* free bytes of the `graceFreezeEnabled` slot and the remaining
* fields take fresh slots, so no pre-existing slot moves.
*/
abstract contract DepositHookDeclaration {
address public depositHookFacet;
address public proposedDepositHookFacet;
uint256 public depositHookChangeQueuedAt;
uint256 internal constant DEPOSIT_HOOK_CHANGE_DELAY = 3 days;
bytes4 internal constant DEPOSIT_HOOK_SELECTOR = bytes4(
keccak256(
"applyDepositAccumHook(address,uint256)"
)
);
}
src/diamond/vault/declarations/GracePeriodDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Grace-period tail shard. A single call that grows a user's
* share balance by `graceThresholdAmount` or more through a deposit
* or compound path stamps `lastLargeDepositAt[user]`; until
* `gracePeriodDuration` has elapsed the user cannot claim, compound
* or reassign interest, nor relocate the position to another vault
* (same-chain `moveBetweenVaults` or cross-chain `bridgeToVault`),
* while plain deposits, withdrawals stay open and interest keeps
* accruing. Queue fulfillment receipts, plain ERC20 transfers and
* bridge or peer mints never stamp. `graceThresholdAmount == 0`
* disables the trigger entirely,
* so an already-deployed diamond that upgrades to the gated facets
* with zeroed tail storage behaves exactly as before until master
* calls the setters. A nonzero threshold must be at least one whole
* share token (`10 ** decimalsSet`) so a dust-level threshold cannot
* grace-stamp every ordinary deposit. `MAX_GRACE_PERIOD` bounds the
* configurable duration so a misconfigured master cannot lock
* extraction indefinitely. The swappable freeze hook (`GraceFreezeHookFacet`)
* only enforces the transfer / queue freeze while the master-toggled
* `graceFreezeEnabled` bool is `true` (default `false`, flipped
* instantly with no timelock via `setGraceFreezeEnabled`), so the
* freeze can be switched on or off at any time independently of the
* always-on interest-extraction gate.
*
* Appended last in the declarations linearisation so it takes fresh
* tail slots and moves no pre-existing slot.
*/
abstract contract GracePeriodDeclaration {
uint256 public gracePeriodDuration;
uint256 public graceThresholdAmount;
mapping(address => uint256) public lastLargeDepositAt;
bool public graceFreezeEnabled;
uint256 internal constant MAX_GRACE_PERIOD = 365 days;
}
src/diamond/vault/declarations/HookGuardDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Transient re-entrancy-style flag marking that execution is
* currently inside an internal hook DELEGATECALL (`_runDepositHook`
* or `_runTransferHook`). Both hook facets require it, so a hook can
* only ever run as part of the decorated internal path and never as a
* standalone external call — even if its selector is deliberately
* routed into the diamond. Held in transient storage, so it costs no
* persistent slot and self-clears at the end of every transaction.
*/
abstract contract HookGuardDeclaration {
bool internal transient hookExecuting;
}
src/diamond/vault/declarations/InterestRemainderDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Per-user interest-remainder shard. `interestRemainder` carries
* the sub-unit fraction of accrued interest that the floored
* `_calculateInterest` would otherwise discard on every sync. On each
* `_assignInterest` the scaled pending interest (the `_calculateInterest`
* numerator before the final `/ PRECISION_FACTOR_E18`) is added to the
* carried remainder, only the whole units are banked into
* `cashedInterest`, and the leftover (always `< PRECISION_FACTOR_E18`,
* i.e. less than one base unit of interest) is stored back here. This
* makes accrual lossless across an arbitrary number of syncs: banking N
* tiny intervals now equals banking one interval of the summed duration,
* so a hostile force-sync (a 1-wei transfer or `moveMyInterestTo`
* targeting the victim every block) can no longer floor a small holder's
* interest to zero. Written only by `_assignInterest`; never counted in
* `totalCashedInterest` until it crosses a whole unit and banks, so the
* INT-7 accumulator identity and the BUF-3 sweep reserve are unaffected.
* Appended last as a tail shard so it takes fresh slot 63 and moves no
* pre-existing slot.
*/
abstract contract InterestRemainderDeclaration {
mapping(address => uint256) public interestRemainder;
}
src/diamond/vault/declarations/PeerVaultDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Peer-vault shard. `peerVault[other] == true` means this
* diamond accepts `mintFromPeer` calls from `other` and lets its
* users move tokens out to `other`. Enabling a peer is timelocked
* via `proposePeerVault` + `executePeerVaultChange` behind a 3-day
* `PEER_VAULT_CHANGE_DELAY` (matching the worker-rotation shape
* from Step 15) so a compromised master cannot instantly register
* a malicious peer that would mint unbacked tokens. Disabling is
* instant via `removePeerVault` as a safety brake — removing a
* misbehaving peer should not wait three days.
*/
abstract contract PeerVaultDeclaration {
mapping(address => bool) public peerVault;
mapping(address => uint256) public peerVaultChangeQueuedAt;
uint256 internal constant PEER_VAULT_CHANGE_DELAY = 3 days;
}
src/diamond/vault/declarations/ProxyDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Proxy-locked balances shard.
*/
abstract contract ProxyDeclaration {
mapping(address => uint256) public proxyBalance;
}
src/diamond/vault/declarations/QueueConfigDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Queue configuration shard for the merged diamond. The vault
* itself is the custodian and the USD token lives in `USD_TOKEN`
* (slot 8), so the legacy `forwardVault` / `usdToken` fields are
* dropped. `PRECISION_RATE` is inherited from {ConfigDeclaration}.
*/
abstract contract QueueConfigDeclaration {
uint256 public minDepositAmount;
bool public negativeIncentivesNotAllowed;
uint256 internal constant MAX_ORDERS_TO_CONSIDER_LIMIT = 100;
}
src/diamond/vault/declarations/QueueStateDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {WiseSovrenNodesQueueStructs} from "../WiseSovrenNodesQueueStructs.sol";
/**
* @dev Order-book and linked-list state for the queue surface.
* Appended after the vault shards so the vault's slot layout stays
* stable.
*/
abstract contract QueueStateDeclaration is WiseSovrenNodesQueueStructs {
mapping(uint256 => mapping(int256 => QueMember)) public QueMemberByIdAndIncentive;
mapping(int256 => uint256) public earliestValidQueMemberByIncentive;
mapping(int256 => uint256) public currentOrderIdByIncentive;
mapping(int256 => bool) public incentiveAllowed;
mapping(int256 => uint256) public activeOrderCountByIncentive;
uint256 public totalActiveOrders;
}
src/diamond/vault/declarations/ReferralDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Referral / cross-chain-data tail shard. The bridge wire format
* always carries a `bytes referralData` field (empty by default), so a
* future referral system can transport data cross-chain without another
* message-format change. `referralEnabled` gates whether an inbound
* bridge that carries a non-empty `referralData` surfaces it via the
* `BridgeReferral` event; it defaults to `false`, so until master flips
* it the bridge behaves exactly as before and the payload is ignored.
*
* `bridgeGasLimit` overrides the destination `ccipReceive` callback
* budget when non-zero, so a future referral consumer that writes
* storage on arrival can raise the budget with no redeploy; `0` (the
* unset default) falls back to `BRIDGE_GAS_LIMIT`. `MAX_REFERRAL_BYTES`
* caps the payload so a caller cannot inflate the message past the CCIP
* size ceiling or the destination gas budget, and `MAX_BRIDGE_GAS_LIMIT`
* bounds the configurable budget.
*
* Appended last in the declarations linearisation so it takes fresh tail
* slots and moves no pre-existing slot. `referralEnabled` and
* `bridgeGasLimit` pack into a single slot.
*/
abstract contract ReferralDeclaration {
bool public referralEnabled;
uint64 public bridgeGasLimit;
uint256 internal constant MAX_REFERRAL_BYTES = 256;
uint256 internal constant MAX_BRIDGE_GAS_LIMIT = 5_000_000;
uint256 internal constant LEGACY_BRIDGE_PAYLOAD_LENGTH = 64;
}
src/diamond/vault/declarations/SelectorRoutingDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Diamond-routing storage: selector→facet table, proposal
* queue, and the `initialized` latch. New shards are appended after
* it in the declarations linearisation, so its slots stay stable
* across future facet additions.
*/
abstract contract SelectorRoutingDeclaration {
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;
}
src/diamond/vault/declarations/SweeperDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Sweeper allowlist shard. `isSweeper` gates who may trigger
* `sweepOverhang`: only allowlisted addresses can move the
* overhang. The constructor seeds the worker, the third party and
* the deployer (`_seedSweepers`); on the deterministic CREATE3
* path the bootstrap shim additionally grants the pending master
* and revokes its own constructor-seeded grant before handing off
* ownership. Master can grant or revoke further sweepers via
* `setSweeper`. The grant is instant (no timelock) because the
* trigger is the only thing gated — swept funds can only ever
* reach the 3-day-timelocked `workerAddress`, and the sweep can
* never take the balance below the reserved buffer plus the
* `totalCashedInterest` liability. Appended as a tail shard so it
* takes a fresh tail slot and moves no pre-existing slot.
*/
abstract contract SweeperDeclaration {
mapping(address => bool) public isSweeper;
}
src/diamond/vault/declarations/ThirdPartyDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Third-party custodian rotation shard. `thirdPartyAddress`
* (declared in {ConfigDeclaration}) receives every forwarded
* deposit, so redirecting it is the single most sensitive config
* change. `proposedThirdPartyAddress` + `thirdPartyChangeQueuedAt`
* back a 3-day propose/execute flow (same shape as the worker
* rotation) so a compromised master cannot instantly reroute deposit
* inflow. Appended last as a tail shard so it takes fresh slots and
* moves no pre-existing slot.
*/
abstract contract ThirdPartyDeclaration {
address public proposedThirdPartyAddress;
uint256 public thirdPartyChangeQueuedAt;
uint256 internal constant THIRD_PARTY_CHANGE_DELAY = 3 days;
}
src/diamond/vault/declarations/TransferHookDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Swappable transfer-hook shard. `transferHookFacet` is an
* optional facet the ERC20 `transfer`/`transferFrom` (and the queue
* internal move) DELEGATECALL as a transfer-time policy hook. When it
* is `ZERO_ADDRESS` — the shipped default — the inline hook is a
* no-op, so a bare transfer moves tokens only and interest is
* reassigned exclusively through the explicit `moveMyInterestTo`; the
* swap capability is latent and off unless a master opts in.
* `proposedTransferHookFacet` + `transferHookChangeQueuedAt`
* back the propose/execute flow: instant while the diamond is still in
* setup (before `finalizeSetup`, like the selector routing and
* cross-chain peers) so the deploy can install the initial hook at
* genesis, then 3-day timelocked afterwards (same shape as the
* third-party rotation) so a compromised master cannot instantly
* repoint the most sensitive path; proposing `ZERO_ADDRESS` reverts
* back to the inline default. Appended last as a tail shard so it takes
* fresh slots and moves no pre-existing slot.
*/
abstract contract TransferHookDeclaration {
address public transferHookFacet;
address public proposedTransferHookFacet;
uint256 public transferHookChangeQueuedAt;
uint256 internal constant TRANSFER_HOOK_CHANGE_DELAY = 3 days;
bytes4 internal constant TRANSFER_HOOK_SELECTOR = bytes4(
keccak256(
"applyTransferHook(address,address)"
)
);
}
src/diamond/vault/declarations/UserStateDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Per-user state: interest accounting.
*/
abstract contract UserStateDeclaration {
mapping(address => uint256) public lastSyncTimeStamp;
mapping(address => uint256) public cashedInterest;
}
src/diamond/vault/declarations/WiseDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev WISE-token shard. `WISE_TOKEN` is the token `burnWise` burns.
* It lives in storage rather than a bytecode constant so the diamond
* can be deployed on chains that have no WISE token — there it stays
* `address(0)` and `burnWise` reverts `WiseTokenNotSet` — and later be
* pointed at a bridged WISE by master through `setWiseToken`. Appended
* last so it takes a fresh tail slot and moves no pre-existing slot.
*/
abstract contract WiseDeclaration {
address public WISE_TOKEN;
}
src/diamond/vault/declarations/WiseSovrenNodesDeclarations.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {OwnableMaster} from "../../shared/OwnableMaster.sol";
import {WiseSovrenNodesDiamondEvents} from "../WiseSovrenNodesDiamondEvents.sol";
import {WiseSovrenNodesDiamondErrors} from "../WiseSovrenNodesDiamondErrors.sol";
import {WiseSovrenNodesInitParams} from "../WiseSovrenNodesDiamondStructs.sol";
import {WiseSovrenNodesIncentiveLadder} from "../WiseSovrenNodesIncentiveLadder.sol";
import {ConfigDeclaration} from "./ConfigDeclaration.sol";
import {UserStateDeclaration} from "./UserStateDeclaration.sol";
import {ProxyDeclaration} from "./ProxyDeclaration.sol";
import {WorkerDeclaration} from "./WorkerDeclaration.sol";
import {PeerVaultDeclaration} from "./PeerVaultDeclaration.sol";
import {SelectorRoutingDeclaration} from "./SelectorRoutingDeclaration.sol";
import {QueueStateDeclaration} from "./QueueStateDeclaration.sol";
import {QueueConfigDeclaration} from "./QueueConfigDeclaration.sol";
import {CrossChainDeclaration} from "./CrossChainDeclaration.sol";
import {WiseDeclaration} from "./WiseDeclaration.sol";
import {BridgeReplayDeclaration} from "./BridgeReplayDeclaration.sol";
import {ThirdPartyDeclaration} from "./ThirdPartyDeclaration.sol";
import {TransferHookDeclaration} from "./TransferHookDeclaration.sol";
import {BurnWiseRotationDeclaration} from "./BurnWiseRotationDeclaration.sol";
import {ReferralDeclaration} from "./ReferralDeclaration.sol";
import {DepositGateDeclaration} from "./DepositGateDeclaration.sol";
import {GracePeriodDeclaration} from "./GracePeriodDeclaration.sol";
import {DepositHookDeclaration} from "./DepositHookDeclaration.sol";
import {DepositAccumDeclaration} from "./DepositAccumDeclaration.sol";
import {CashedInterestTotalDeclaration} from "./CashedInterestTotalDeclaration.sol";
import {SweeperDeclaration} from "./SweeperDeclaration.sol";
import {DepositAccumPrevDeclaration} from "./DepositAccumPrevDeclaration.sol";
import {HookGuardDeclaration} from "./HookGuardDeclaration.sol";
import {InterestRemainderDeclaration} from "./InterestRemainderDeclaration.sol";
import {AutoCompoundDeclaration} from "./AutoCompoundDeclaration.sol";
import {ReferralRegistryDeclaration} from "./pending/ReferralRegistryDeclaration.sol";
import {CohortContributionDeclaration} from "./pending/CohortContributionDeclaration.sol";
import {CohortBookDeclaration} from "./pending/CohortBookDeclaration.sol";
import {ReferralPayoutDeclaration} from "./pending/ReferralPayoutDeclaration.sol";
import {ReferralRegistryPointerDeclaration} from "./pending/ReferralRegistryPointerDeclaration.sol";
import {PayoutHubPointerDeclaration} from "./pending/PayoutHubPointerDeclaration.sol";
import {CohortFlushDeclaration} from "./pending/CohortFlushDeclaration.sol";
import {CohortAttributionDeclaration} from "./pending/CohortAttributionDeclaration.sol";
import {CohortDivestDeclaration} from "./pending/CohortDivestDeclaration.sol";
import {CohortSelfDeclaration} from "./pending/CohortSelfDeclaration.sol";
import {CohortDisarmDeclaration} from "./pending/CohortDisarmDeclaration.sol";
import {CohortSelfLogDeclaration} from "./pending/CohortSelfLogDeclaration.sol";
/**
* @title WiseSovrenNodesDeclarations
* @dev Storage composer for the WiseSovrenNodes diamond. Inherits, in
* order: OwnableMaster, Pausable, ReentrancyGuard, ERC20, then the
* vault-specific shards — matching the legacy slot ordering for the
* shared bases. USD_TOKEN sits in storage rather than `immutable`
* because immutables don't survive DELEGATECALL into facets.
*
* The rate validator rejects only a rate above `MAX_INTEREST_RATE`;
* a genesis rate of zero is deliberately legal and safe by
* construction, since the rate is only ever a multiplier and never a
* divisor: at zero, `_assignInterest` banks nothing and merely
* restamps `lastSyncTimeStamp`, and the sweep reserve degenerates to
* exactly `totalCashedInterest`. `bufferInterestRate` starts at the
* genesis rate and only ever ratchets up, so lowering the user rate
* never shrinks the sweep reserve.
*
* Accrual is measured from each holder's own `lastSyncTimeStamp` and
* `setInterestRate` writes no checkpoint, so a rate change is a
* plain master call and a holder's un-banked window is priced at
* whatever rate is current when it banks. When that window should be
* preserved at the outgoing rate across a change, the interest-admin
* facet's `syncInterestBulk` banks it first.
*
* The constructor seeds only the discount half of the incentive
* ladder. The premium half is 245 further lanes, and writing them
* here would cost roughly 5.4 million gas inside the one transaction
* that also creates the diamond and wires every selector, pushing
* that transaction over the 16,777,216 gas ceiling a single
* transaction may not exceed. The premium lanes are therefore opened
* by the master through `setIncentivesAllowed` in a following
* transaction, before the setup is finalised. Both halves come from
* the same ladder library, so the two paths cannot describe
* different ladders.
*/
abstract contract WiseSovrenNodesDeclarations is
WiseSovrenNodesDiamondEvents,
WiseSovrenNodesDiamondErrors,
OwnableMaster,
Pausable,
ReentrancyGuard,
ERC20,
ConfigDeclaration,
UserStateDeclaration,
ProxyDeclaration,
WorkerDeclaration,
PeerVaultDeclaration,
SelectorRoutingDeclaration,
QueueStateDeclaration,
QueueConfigDeclaration,
CrossChainDeclaration,
WiseDeclaration,
BridgeReplayDeclaration,
ThirdPartyDeclaration,
TransferHookDeclaration,
BurnWiseRotationDeclaration,
ReferralDeclaration,
DepositGateDeclaration,
GracePeriodDeclaration,
DepositHookDeclaration,
DepositAccumDeclaration,
CashedInterestTotalDeclaration,
SweeperDeclaration,
DepositAccumPrevDeclaration,
HookGuardDeclaration,
InterestRemainderDeclaration,
AutoCompoundDeclaration,
ReferralRegistryDeclaration,
CohortContributionDeclaration,
CohortBookDeclaration,
ReferralPayoutDeclaration,
ReferralRegistryPointerDeclaration,
PayoutHubPointerDeclaration,
CohortFlushDeclaration,
CohortAttributionDeclaration,
CohortDivestDeclaration,
CohortSelfDeclaration,
CohortDisarmDeclaration,
CohortSelfLogDeclaration
{
constructor(
WiseSovrenNodesInitParams memory _params
)
OwnableMaster(msg.sender)
ERC20(
_params.tokenName,
_params.tokenSymbol
)
{
_validateConstructorInputs(
_params
);
USD_TOKEN = IERC20(
_params.usdAddress
);
thirdPartyAddress = _params.thirdPartyAddress;
workerAddress = _params.workerAddress;
totalDepositCap = _params.totalDepositCap;
interestRate = _params.interestRate;
bufferInterestRate = _params.interestRate;
decimalsSet = _params.decimalsValue;
InterestRateProxy = address(this);
_seedSweepers(
_params.workerAddress,
_params.thirdPartyAddress
);
_performInitialMinting(
_params.initialDistributionAddresses,
_params.initialDistributionAmounts
);
_migrateInterest(
_params.oldVault,
_params.initialDistributionAddresses
);
_initializeIncentives();
minDepositAmount = 50
* 10
** decimalsSet;
gracePeriodDuration = 45 days;
graceThresholdAmount = 10_000
* 10
** decimalsSet;
}
function _initializeIncentives()
internal
{
int256[] memory allowed = WiseSovrenNodesIncentiveLadder.positiveIncentives();
for (uint256 i = 0; i < allowed.length; i++) {
incentiveAllowed[allowed[i]] = true;
}
}
function _validateConstructorInputs(
WiseSovrenNodesInitParams memory _params
)
internal
pure
{
if (
_params.totalDepositCap == 0
|| _params.usdAddress == ZERO_ADDRESS
|| _params.thirdPartyAddress == ZERO_ADDRESS
|| _params.workerAddress == ZERO_ADDRESS
) {
revert InvalidValue();
}
if (_params.interestRate > MAX_INTEREST_RATE) {
revert InterestRateTooHigh();
}
}
function _performInitialMinting(
address[] memory _initialDistributionAddresses,
uint256[] memory _initialDistributionAmounts
)
internal
{
for (uint256 i = 0; i < _initialDistributionAddresses.length; i++) {
if (totalSupply() + _initialDistributionAmounts[i] > totalDepositCap) {
revert DepositExceedCap();
}
_mint(
_initialDistributionAddresses[i],
_initialDistributionAmounts[i]
);
lastSyncTimeStamp[_initialDistributionAddresses[i]] = block.timestamp;
}
}
function _migrateInterest(
address _oldVault,
address[] memory _initialDistributionAddresses
)
internal
{
if (_oldVault != ZERO_ADDRESS) {
if (_oldVault.code.length == 0) {
revert OldVaultNoCode();
}
for (uint256 i = 0; i < _initialDistributionAddresses.length; i++) {
(
bool ok,
bytes memory returnValue
) = _oldVault.staticcall(
abi.encodeWithSignature(
"getTotalInterestUser(address)",
_initialDistributionAddresses[i]
)
);
require(
ok,
"old vault call failed"
);
if (returnValue.length != 32) {
revert OldVaultBadResponse();
}
uint256 migratedInterest = abi.decode(
returnValue,
(uint256)
);
uint256 previousInterest = cashedInterest[
_initialDistributionAddresses[i]
];
cashedInterest[_initialDistributionAddresses[i]] = migratedInterest;
totalCashedInterest = totalCashedInterest
+ migratedInterest
- previousInterest;
}
emit TotalCashedInterestChanged(
totalCashedInterest
);
}
}
/**
* @dev Seeds the sweeper allowlist at genesis: the worker, the
* third party and the deployer (`msg.sender` — the real owner
* on a direct deploy, the bootstrap shim on the deterministic
* CREATE3 path, where the shim grants the pending master and
* revokes itself before handing off ownership).
*/
function _seedSweepers(
address _worker,
address _thirdParty
)
internal
{
isSweeper[_worker] = true;
emit SweeperSet(
_worker,
true
);
isSweeper[_thirdParty] = true;
emit SweeperSet(
_thirdParty,
true
);
isSweeper[msg.sender] = true;
emit SweeperSet(
msg.sender,
true
);
}
/**
* @dev Returns the per-deployment `decimalsSet`. Lives on the
* diamond so it's reachable regardless of facet routing.
*/
function decimals()
public
view
virtual
override
returns (uint8)
{
return decimalsSet;
}
}
src/diamond/vault/declarations/WorkerDeclaration.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Worker-role shard. `workerAddress` receives the overhang
* sweep. `bufferInterestRate` is a ratchet-up shadow of
* `interestRate` used only for `_calculateNeededBuffer`: master can
* lower the user-facing rate but the buffer requirement only grows,
* never shrinks. `proposedWorkerAddress` + `workerChangeQueuedAt`
* back a 3-day propose/execute flow for rotating the worker (same
* shape as the selector-routing timelock) so a compromised master
* can't instantly redirect the sweep recipient.
*/
abstract contract WorkerDeclaration {
address public workerAddress;
uint256 public bufferInterestRate;
address public proposedWorkerAddress;
uint256 public workerChangeQueuedAt;
uint256 internal constant SECONDS_IN_TWO_WEEKS = 14 days;
uint256 internal constant WORKER_CHANGE_DELAY = 3 days;
}
src/diamond/vault/declarations/pending/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/pending/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/pending/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/pending/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/pending/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/pending/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/pending/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/pending/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/pending/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/pending/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/pending/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/pending/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/QueueFacetBase.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {WiseSovrenNodesQueueHelper} from "../helpers/WiseSovrenNodesQueueHelper.sol";
import {WiseSovrenNodesDeclarations} from "../declarations/WiseSovrenNodesDeclarations.sol";
import {WiseSovrenNodesInitParams} from "../WiseSovrenNodesDiamondStructs.sol";
import {OnlyDelegateCall} from "../../shared/DiamondErrors.sol";
/**
* @dev Common base for the queue action facets (admin / join-leave /
* fulfill). Carries the order-processing helper but not the heavier
* UI/view layer, which lives only on {QueueViewFacet}. Mirrors
* {FacetBase}: placeholder constructor args satisfy
* `_validateConstructorInputs`, and `_self` lets `onlyDelegateCall`
* reject direct calls — facet storage is never read because facets
* are only entered via DELEGATECALL.
*/
abstract contract QueueFacetBase is WiseSovrenNodesQueueHelper {
address internal immutable _self;
constructor()
WiseSovrenNodesDeclarations(
WiseSovrenNodesInitParams({
usdAddress: address(0x000000000000000000000000000000000000dEaD),
thirdPartyAddress: address(0x000000000000000000000000000000000000dEaD),
workerAddress: address(0x000000000000000000000000000000000000dEaD),
oldVault: address(0),
initialDistributionAddresses: new address[](0),
initialDistributionAmounts: new uint256[](0),
totalDepositCap: 1,
interestRate: 0,
decimalsValue: 18,
tokenName: "FACET",
tokenSymbol: "FACET"
})
)
{
_self = address(this);
}
modifier onlyDelegateCall() {
_onlyDelegateCall();
_;
}
function _onlyDelegateCall()
internal
view
{
if (address(this) != _self) {
return;
}
revert OnlyDelegateCall();
}
}
src/diamond/vault/helpers/WiseSovrenNodesAdminHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {WiseSovrenNodesBaseHelper} from "./WiseSovrenNodesBaseHelper.sol";
/**
* @dev Master-side supply controls. Mint/burn are gated by
* `supplyChangeAllowed` at the facet boundary and become
* permanently disabled once `disAllowSupplyChangeByOwner` is called.
*/
abstract contract WiseSovrenNodesAdminHelper is WiseSovrenNodesBaseHelper {
function _executeMintSupply(
address _to,
uint256 _amount
)
internal
{
_checkDepositCap(
_amount
);
_mint(
_to,
_amount
);
emit MintSupply(
_to,
_amount
);
}
function _executeBurnSupply(
address _from,
uint256 _amount
)
internal
{
_burn(
_from,
_amount
);
emit BurnSupply(
_from,
_amount
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesBaseHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {WiseSovrenNodesDeclarations} from "../declarations/WiseSovrenNodesDeclarations.sol";
import {IReferralRegistry} from "../interfaces/pending/IReferralRegistry.sol";
/**
* @dev Base helper layer: access modifiers (`supplyChangeAllowed`),
* small validators, field setters, and the interest-rate-proxy
* validation gate.
*/
abstract contract WiseSovrenNodesBaseHelper is WiseSovrenNodesDeclarations {
modifier supplyChangeAllowed() {
_supplyChangeAllowed();
_;
}
function _supplyChangeAllowed()
internal
view
{
require(
supplyChangeByOwnerNotAllowed == false,
SupplyChangeNotAllowed()
);
}
function _validateInterestRateProxy()
internal
view
{
require(
msg.sender == InterestRateProxy,
NotInterestRateProxy()
);
}
function _updateProxyBenefactor(
address _proxyBeneFactor
)
internal
{
currentProxyBenefactor = _proxyBeneFactor;
emit ProxyBenefactorSet(
_proxyBeneFactor
);
}
function _updateInterestRate(
uint256 _interestRate
)
internal
{
require(
_interestRate <= MAX_INTEREST_RATE,
InterestRateTooHigh()
);
interestRate = _interestRate;
emit InterestRateSet(
_interestRate
);
if (_interestRate > bufferInterestRate) {
bufferInterestRate = _interestRate;
emit BufferInterestRateRaised(
_interestRate
);
}
}
function _updateThirdPartyAddress(
address _thirdPartyAddress
)
internal
{
thirdPartyAddress = _thirdPartyAddress;
emit ThirdPartyAddressSet(
_thirdPartyAddress
);
}
function _proposeThirdPartyAddress(
address _thirdPartyAddress
)
internal
{
require(
_thirdPartyAddress != ZERO_ADDRESS,
InvalidValue()
);
proposedThirdPartyAddress = _thirdPartyAddress;
thirdPartyChangeQueuedAt = block.timestamp;
emit ThirdPartyAddressProposed(
_thirdPartyAddress,
block.timestamp + THIRD_PARTY_CHANGE_DELAY
);
}
function _applyThirdPartyAddressChange()
internal
{
require(
thirdPartyChangeQueuedAt > 0,
NoThirdPartyChangeProposed()
);
require(
block.timestamp >= thirdPartyChangeQueuedAt + THIRD_PARTY_CHANGE_DELAY,
ThirdPartyTimelockNotElapsed()
);
address newThirdParty = proposedThirdPartyAddress;
proposedThirdPartyAddress = ZERO_ADDRESS;
thirdPartyChangeQueuedAt = 0;
_updateThirdPartyAddress(
newThirdParty
);
}
function _cancelThirdPartyAddressChange()
internal
{
address cancelled = proposedThirdPartyAddress;
proposedThirdPartyAddress = ZERO_ADDRESS;
thirdPartyChangeQueuedAt = 0;
emit ThirdPartyAddressProposalCancelled(
cancelled
);
}
function _updateTransferHookFacet(
address _facet
)
internal
{
transferHookFacet = _facet;
emit TransferHookFacetSet(
_facet
);
}
function _proposeTransferHookFacet(
address _facet
)
internal
{
proposedTransferHookFacet = _facet;
transferHookChangeQueuedAt = block.timestamp;
emit TransferHookFacetProposed(
_facet,
block.timestamp + TRANSFER_HOOK_CHANGE_DELAY
);
}
function _applyTransferHookFacetChange()
internal
{
require(
transferHookChangeQueuedAt > 0,
NoTransferHookChangeProposed()
);
if (initialized) {
require(
block.timestamp >= transferHookChangeQueuedAt + TRANSFER_HOOK_CHANGE_DELAY,
TransferHookTimelockNotElapsed()
);
}
address newFacet = proposedTransferHookFacet;
require(
newFacet == ZERO_ADDRESS
|| newFacet.code.length > 0,
InvalidValue()
);
proposedTransferHookFacet = ZERO_ADDRESS;
transferHookChangeQueuedAt = 0;
_updateTransferHookFacet(
newFacet
);
}
function _cancelTransferHookFacetChange()
internal
{
address cancelled = proposedTransferHookFacet;
proposedTransferHookFacet = ZERO_ADDRESS;
transferHookChangeQueuedAt = 0;
emit TransferHookFacetProposalCancelled(
cancelled
);
}
function _updateDepositHookFacet(
address _facet
)
internal
{
depositHookFacet = _facet;
emit DepositHookFacetSet(
_facet
);
}
function _proposeDepositHookFacet(
address _facet
)
internal
{
proposedDepositHookFacet = _facet;
depositHookChangeQueuedAt = block.timestamp;
emit DepositHookFacetProposed(
_facet,
block.timestamp + DEPOSIT_HOOK_CHANGE_DELAY
);
}
function _applyDepositHookFacetChange()
internal
{
require(
depositHookChangeQueuedAt > 0,
NoDepositHookChangeProposed()
);
if (initialized) {
require(
block.timestamp >= depositHookChangeQueuedAt + DEPOSIT_HOOK_CHANGE_DELAY,
DepositHookTimelockNotElapsed()
);
}
address newFacet = proposedDepositHookFacet;
require(
newFacet == ZERO_ADDRESS
|| newFacet.code.length > 0,
InvalidValue()
);
proposedDepositHookFacet = ZERO_ADDRESS;
depositHookChangeQueuedAt = 0;
_updateDepositHookFacet(
newFacet
);
}
function _cancelDepositHookFacetChange()
internal
{
address cancelled = proposedDepositHookFacet;
proposedDepositHookFacet = ZERO_ADDRESS;
depositHookChangeQueuedAt = 0;
emit DepositHookFacetProposalCancelled(
cancelled
);
}
function _updateReferralRegistry(
address _registry
)
internal
{
referralRegistry = _registry;
emit ReferralRegistrySet(
_registry
);
}
function _proposeReferralRegistry(
address _registry
)
internal
{
proposedReferralRegistry = _registry;
referralRegistryChangeQueuedAt = block.timestamp;
emit ReferralRegistryProposed(
_registry,
block.timestamp + REFERRAL_REGISTRY_CHANGE_DELAY
);
}
function _applyReferralRegistryChange()
internal
{
require(
referralRegistryChangeQueuedAt > 0,
NoReferralRegistryChangeProposed()
);
if (initialized) {
require(
block.timestamp >= referralRegistryChangeQueuedAt + REFERRAL_REGISTRY_CHANGE_DELAY,
ReferralRegistryTimelockNotElapsed()
);
}
address newRegistry = proposedReferralRegistry;
require(
newRegistry == ZERO_ADDRESS
|| _probeReferralRegistry(newRegistry),
InvalidValue()
);
proposedReferralRegistry = ZERO_ADDRESS;
referralRegistryChangeQueuedAt = 0;
_updateReferralRegistry(
newRegistry
);
}
function _cancelReferralRegistryChange()
internal
{
address cancelled = proposedReferralRegistry;
proposedReferralRegistry = ZERO_ADDRESS;
referralRegistryChangeQueuedAt = 0;
emit ReferralRegistryProposalCancelled(
cancelled
);
}
function _probeReferralRegistry(
address _registry
)
internal
view
returns (bool)
{
if (_registry.code.length == 0) {
return false;
}
(
bool success,
bytes memory returnData
) = _registry.staticcall(
abi.encodeWithSelector(
IReferralRegistry.referrerOf.selector,
address(this)
)
);
return success
&& returnData.length == 32;
}
function _updateFlushHub(
address _hub,
uint64 _chainSelector
)
internal
{
flushHub = _hub;
flushHubChainSelector = _chainSelector;
emit FlushHubSet(
_hub,
_chainSelector
);
}
function _proposeFlushHub(
address _hub,
uint64 _chainSelector
)
internal
{
proposedFlushHub = _hub;
proposedFlushHubChainSelector = _chainSelector;
flushHubChangeQueuedAt = block.timestamp;
emit FlushHubProposed(
_hub,
_chainSelector,
block.timestamp + FLUSH_HUB_CHANGE_DELAY
);
}
function _applyFlushHubChange()
internal
{
require(
flushHubChangeQueuedAt > 0,
NoFlushHubChangeProposed()
);
if (initialized) {
require(
block.timestamp >= flushHubChangeQueuedAt + FLUSH_HUB_CHANGE_DELAY,
FlushHubTimelockNotElapsed()
);
}
address newHub = proposedFlushHub;
uint64 newSelector = proposedFlushHubChainSelector;
require(
newHub != ZERO_ADDRESS
|| newSelector == 0,
InvalidValue()
);
proposedFlushHub = ZERO_ADDRESS;
proposedFlushHubChainSelector = 0;
flushHubChangeQueuedAt = 0;
_updateFlushHub(
newHub,
newSelector
);
}
function _cancelFlushHubChange()
internal
{
address cancelled = proposedFlushHub;
proposedFlushHub = ZERO_ADDRESS;
proposedFlushHubChainSelector = 0;
flushHubChangeQueuedAt = 0;
emit FlushHubProposalCancelled(
cancelled
);
}
function _proposeWorkerAddress(
address _worker
)
internal
{
require(
_worker != ZERO_ADDRESS,
InvalidValue()
);
proposedWorkerAddress = _worker;
workerChangeQueuedAt = block.timestamp;
emit WorkerAddressProposed(
_worker,
block.timestamp + WORKER_CHANGE_DELAY
);
}
function _applyWorkerAddressChange()
internal
{
require(
workerChangeQueuedAt > 0,
NoWorkerChangeProposed()
);
require(
block.timestamp >= workerChangeQueuedAt + WORKER_CHANGE_DELAY,
WorkerTimelockNotElapsed()
);
address newWorker = proposedWorkerAddress;
workerAddress = newWorker;
proposedWorkerAddress = ZERO_ADDRESS;
workerChangeQueuedAt = 0;
emit WorkerAddressSet(
newWorker
);
}
function _cancelWorkerAddressChange()
internal
{
address cancelled = proposedWorkerAddress;
proposedWorkerAddress = ZERO_ADDRESS;
workerChangeQueuedAt = 0;
emit WorkerAddressProposalCancelled(
cancelled
);
}
function _updateTotalDepositCap(
uint256 _totalDepositCap
)
internal
{
require(
_totalDepositCap >= totalSupply(),
DepositCapBelowSupply()
);
totalDepositCap = _totalDepositCap;
emit TotalDepositCapSet(
_totalDepositCap
);
}
function _checkDepositCap(
uint256 _amount
)
internal
view
{
if (totalSupply() + _amount > totalDepositCap) {
revert DepositExceedCap();
}
}
/**
* @dev Relocation-out cap transfer: the burned relocation amount takes
* its deposit-cap budget with it, keeping local room
* (`totalDepositCap - totalSupply()`) unchanged. The checked subtraction
* cannot underflow because `totalSupply() <= totalDepositCap` holds
* globally (genesis mint is cap-checked, local mints are cap-checked,
* relocations shift cap and supply equally and the cap setter floors at
* the live supply) and the burn of `_amount <= totalSupply()` precedes
* every call. A Panic here is a corrupted-state canary — do not replace
* the subtraction with a saturating clamp.
*/
function _reduceDepositCap(
uint256 _amount
)
internal
{
totalDepositCap -= _amount;
emit DepositCapRelocated(
totalDepositCap
);
}
/**
* @dev Relocation-in cap transfer: the imported amount brings its
* deposit-cap budget along, so the subsequent uncapped mint can never
* push `totalSupply()` above `totalDepositCap`. Must be called before
* the paired `_mint`.
*/
function _raiseDepositCap(
uint256 _amount
)
internal
{
totalDepositCap += _amount;
emit DepositCapRelocated(
totalDepositCap
);
}
function _disableSupplyChangeByOwner()
internal
{
supplyChangeByOwnerNotAllowed = true;
emit SupplyChangeByOwnerNotAllowedSet(
true
);
}
function _updateWiseToken(
address _wiseToken
)
internal
{
WISE_TOKEN = _wiseToken;
emit WiseTokenSet(
_wiseToken
);
}
function _setDepositsDisabled(
bool _disabled
)
internal
{
depositsDisabled = _disabled;
emit DepositsDisabledSet(
_disabled
);
}
function _setGracePeriodDuration(
uint256 _duration
)
internal
{
require(
_duration <= MAX_GRACE_PERIOD,
GracePeriodTooLong()
);
gracePeriodDuration = _duration;
emit GracePeriodDurationSet(
_duration
);
}
function _setGraceThresholdAmount(
uint256 _amount
)
internal
{
if (_amount > 0) {
require(
_amount >= 10 ** decimalsSet,
GraceThresholdTooLow()
);
}
graceThresholdAmount = _amount;
emit GraceThresholdAmountSet(
_amount
);
}
function _setGraceFreezeEnabled(
bool _enabled
)
internal
{
graceFreezeEnabled = _enabled;
emit GraceFreezeEnabledSet(
_enabled
);
}
function _setCohortSyncEnabled(
bool _enabled
)
internal
{
if (_enabled == true) {
require(
transferHookFacet != ZERO_ADDRESS,
CohortHookNotInstalled()
);
require(
referralRegistry != ZERO_ADDRESS,
ReferralRegistryNotSet()
);
cohortSyncEnabled = true;
_cohortSync(
ZERO_ADDRESS
);
} else {
cohortSyncEnabled = false;
}
emit CohortSyncEnabledSet(
_enabled
);
}
function _cohortSync(
address _user
)
internal
{
if (cohortSyncEnabled == false) {
return;
}
_runCohortHook(
abi.encodeWithSelector(
COHORT_SYNC_SELECTOR,
_user
)
);
}
function _cohortCredit(
address _user,
uint256 _amount
)
internal
{
if (cohortSyncEnabled == false) {
return;
}
_runCohortHook(
abi.encodeWithSelector(
COHORT_CREDIT_SELECTOR,
_user,
_amount
)
);
}
function _cohortAdvance(
address _referrer,
uint256 _maxBoundaries
)
internal
{
if (cohortSyncEnabled == false) {
return;
}
_runCohortHook(
abi.encodeWithSelector(
COHORT_ADVANCE_SELECTOR,
_referrer,
_maxBoundaries
)
);
}
function _cohortSettle(
address _referrer
)
internal
{
if (cohortSyncEnabled == false) {
return;
}
_runCohortHook(
abi.encodeWithSelector(
COHORT_SETTLE_SELECTOR,
_referrer
)
);
}
function _cohortMoveOut(
address _user,
address _dstVault,
uint256 _burnedAmount,
uint256 _scaleNumerator,
uint256 _scaleDenominator
)
internal
{
if (cohortSyncEnabled == false) {
return;
}
_runCohortHook(
abi.encodeWithSelector(
COHORT_MOVE_OUT_SELECTOR,
_user,
_dstVault,
_burnedAmount,
_scaleNumerator,
_scaleDenominator
)
);
}
function _cohortMoveIn(
address _user,
address _srcVault
)
internal
{
if (cohortSyncEnabled == false) {
return;
}
_runCohortHook(
abi.encodeWithSelector(
COHORT_MOVE_IN_SELECTOR,
_user,
_srcVault
)
);
}
function _cohortFlip(
address _user,
address _oldReferrer,
address _newReferrer
)
internal
{
require(
selectorToFacet[COHORT_FLIP_SELECTOR] != ZERO_ADDRESS,
CohortSyncDisabled()
);
_runRoutedCohortHook(
COHORT_FLIP_SELECTOR,
abi.encodeWithSelector(
COHORT_FLIP_SELECTOR,
_user,
_oldReferrer,
_newReferrer
)
);
}
function _cohortBridgeOut(
address _user,
uint64 _dstChainSelector,
uint256 _burnedAmount,
uint256 _scaleNumerator,
uint256 _scaleDenominator
)
internal
returns (bytes memory)
{
if (cohortSyncEnabled == false) {
return "";
}
(
bool ran,
bytes memory returnData
) = _runRoutedCohortHook(
COHORT_BRIDGE_OUT_SELECTOR,
abi.encodeWithSelector(
COHORT_BRIDGE_OUT_SELECTOR,
_user,
_dstChainSelector,
_burnedAmount,
_scaleNumerator,
_scaleDenominator
)
);
if (ran == false) {
_cohortSync(
_user
);
return "";
}
return abi.decode(
returnData,
(bytes)
);
}
function _cohortBridgeIn(
address _user,
uint64 _srcChainSelector,
uint256 _mintedAmount,
bytes memory _payload
)
internal
returns (bool)
{
if (cohortSyncEnabled == false) {
return false;
}
address facet = selectorToFacet[COHORT_BRIDGE_IN_SELECTOR];
if (facet == ZERO_ADDRESS) {
return false;
}
hookExecuting = true;
uint256 gasForwarded = gasleft();
(
bool success,
bytes memory returnData
) = facet.delegatecall(
abi.encodeWithSelector(
COHORT_BRIDGE_IN_SELECTOR,
_user,
_srcChainSelector,
_mintedAmount,
_payload
)
);
hookExecuting = false;
if (success == false || returnData.length != 32) {
if (gasleft() <= gasForwarded / 64) {
revert CohortBridgeInOutOfGas(
_user,
_srcChainSelector
);
}
emit CohortBridgeHookFailed(
_user,
_srcChainSelector
);
return false;
}
return abi.decode(
returnData,
(bool)
);
}
function _runRoutedCohortHook(
bytes4 _selector,
bytes memory _callData
)
internal
returns (
bool,
bytes memory
)
{
address facet = selectorToFacet[_selector];
bytes memory empty;
if (facet == ZERO_ADDRESS) {
return (
false,
empty
);
}
hookExecuting = true;
(
bool success,
bytes memory returnData
) = facet.delegatecall(
_callData
);
hookExecuting = false;
if (success == false) {
assembly {
revert(add(returnData, 0x20), mload(returnData))
}
}
return (
true,
returnData
);
}
function _runCohortHook(
bytes memory _callData
)
internal
{
address facet = transferHookFacet;
if (facet == ZERO_ADDRESS) {
return;
}
hookExecuting = true;
(
bool success,
bytes memory returnData
) = facet.delegatecall(
_callData
);
hookExecuting = false;
if (success == false) {
assembly {
revert(add(returnData, 0x20), mload(returnData))
}
}
}
function _setSweeper(
address _sweeper,
bool _allowed
)
internal
{
if (_sweeper == ZERO_ADDRESS) {
revert InvalidValue();
}
isSweeper[_sweeper] = _allowed;
emit SweeperSet(
_sweeper,
_allowed
);
}
function _setDepositAccumWindow(
uint256 _window
)
internal
{
require(
_window <= MAX_GRACE_PERIOD,
DepositAccumWindowTooLong()
);
depositAccumWindow = _window;
emit DepositAccumWindowSet(
_window
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesBufferHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {WiseSovrenNodesInterestHelper} from "./WiseSovrenNodesInterestHelper.sol";
/**
* @dev Buffer / overhang sweep logic. The contract must hold at
* least two weeks of forward interest at the configured
* `bufferInterestRate` on the share supply PLUS the settled
* `totalCashedInterest` liability users can already claim on
* demand; anything above that combined reserve is "overhang" and
* can be swept to the registered `workerAddress` by any address
* master has granted in the `isSweeper` allowlist. The liability
* term means a sweep can never take the cash a custodian
* pre-funded for pending claims. With zero share supply the
* reserve is the liability alone — cashed interest stays claimable
* after every share has exited.
*
* Principal is `totalSupply()` — queued shares are already counted
* there (they move from the user's `balanceOf` to the queue's
* `balanceOf` on `joinQue`, never minted/burned).
*/
abstract contract WiseSovrenNodesBufferHelper is WiseSovrenNodesInterestHelper {
using SafeERC20 for IERC20;
function _calculateNeededBuffer()
internal
view
returns (uint256)
{
uint256 principal = totalSupply();
if (principal == 0) {
return totalCashedInterest;
}
uint256 yearFactor = SECONDS_IN_TWO_WEEKS
* PRECISION_FACTOR_E18
/ SECONDS_IN_YEAR;
uint256 forwardInterest = principal
* bufferInterestRate
* yearFactor
/ PRECISION_RATE
/ PRECISION_FACTOR_E18;
return forwardInterest
+ totalCashedInterest;
}
function _calculateOverhang()
internal
view
returns (uint256)
{
uint256 needed = _calculateNeededBuffer();
uint256 actual = USD_TOKEN.balanceOf(
address(this)
);
if (actual <= needed) {
return 0;
}
return actual - needed;
}
function _executeSweepOverhang()
internal
returns (uint256 amount)
{
require(
isSweeper[msg.sender],
NotSweeper()
);
amount = _calculateOverhang();
require(
amount > 0,
NoOverhang()
);
address worker = workerAddress;
USD_TOKEN.safeTransfer(
worker,
amount
);
emit OverhangSwept(
worker,
msg.sender,
amount
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesCrossChainHelper.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 {WiseSovrenNodesMoveHelper} from "./WiseSovrenNodesMoveHelper.sol";
import {CohortWeeks} from "../../shared/pending/CohortWeeks.sol";
/**
* @dev Cross-chain sibling of {WiseSovrenNodesMoveHelper}. Where
* `moveBetweenVaults` shifts a share claim to a peer vault on the
* same chain in one transaction, `bridgeToVault` does the same across
* chains over Chainlink CCIP arbitrary messaging: the source burns
* the user's shares and sends a data-only message; the destination
* peer mints the scaled equivalent when CCIP delivers it.
*
* The interest handling mirrors the same-chain move helper: the
* `assignInterest(msg.sender)` modifier on the
* facet entry banks the user's accrued-but-unclaimed interest into
* `cashedInterest` and resets `lastSyncTimeStamp` before the burn, so
* that interest stays claimable on the source chain and is never
* bridged. On delivery `_executeBridgeReceive` runs the same
* `_assignInterest` then `_mint`, so the freshly minted balance starts
* accruing from the arrival timestamp exactly as a normal deposit
* would — and if the receiver already holds shares, their prior
* accrual is banked first so forward accrual stays correct.
*
* No `USD_TOKEN` crosses chains — the share claim is burned here and
* minted there, and the underlying backing is reconciled off-chain by
* the custodian from the emitted `BridgeSent` / `BridgeReceived`
* events, mirroring the on-chain `MovedOut` / `MovedIn` model.
*
* Both directions relocate the deposit-cap budget with the shares:
* the out-path burns and then lowers `totalDepositCap` by the burned
* amount via `_reduceDepositCap`, while the receive-path raises
* `totalDepositCap` by the minted amount via `_raiseDepositCap`
* before the mint. Local room (`totalDepositCap - totalSupply()`) is
* therefore invariant under bridging on both ends, the mesh-wide cap
* sum is conserved by user flows, and the receive-path mint can never
* exceed the cap — `ccipReceive` has no economic revert path at all
* (only router, peer, replay and zero-amount guards).
*
* Registering a peer is timelocked behind `CROSS_CHAIN_PEER_CHANGE_DELAY`,
* gated on `initialized` like the selector routing: instant while the
* mesh is still being wired before `finalizeSetup`, delayed afterwards,
* so a compromised master cannot instantly point a lane at a malicious
* vault that would mint unbacked shares. Disabling is instant via
* `removeCrossChainPeer`.
*
* Referral attribution: an armed source replaces the post-burn
* sale-like clamp with the bridge-carry capture — the same clamp plus
* an aggregate relocation payload written into `referralData`
* (caller-supplied bytes are ignored while armed; while unarmed a
* caller payload that parses as a valid carry reverts
* `ReferralDataReserved`). An armed destination consumes the payload
* right after the mint through the tolerant `_cohortBridgeIn` stub —
* validation, registry merge and landing all degrade soft, and the
* legacy `BridgeReferral` surfacing fires only when the carry did NOT
* apply. Fee quoting sizes the message with a fixed-width carry dummy
* while armed, since the real payload is storage-derived at send
* time. The carry's per-component scaling shares
* `crossChainPeerDecimals` with the amount path through
* `_crossChainScaleFactors` (numerator/denominator form, floors per
* component so the destination can never be told more than the
* scaled burn).
*/
abstract contract WiseSovrenNodesCrossChainHelper is WiseSovrenNodesMoveHelper {
function _setCcipRouter(
address _router
)
internal
{
require(
_router != ZERO_ADDRESS,
InvalidValue()
);
require(
ccipRouter == ZERO_ADDRESS,
RouterAlreadySet()
);
ccipRouter = _router;
emit CcipRouterSet(
_router
);
}
function _setReferralEnabled(
bool _enabled
)
internal
{
referralEnabled = _enabled;
emit ReferralEnabledSet(
_enabled
);
}
function _setBridgeGasLimit(
uint256 _gasLimit
)
internal
{
require(
_gasLimit >= BRIDGE_GAS_LIMIT,
InvalidBridgeGasLimit()
);
require(
_gasLimit <= MAX_BRIDGE_GAS_LIMIT,
InvalidBridgeGasLimit()
);
bridgeGasLimit = uint64(_gasLimit);
emit BridgeGasLimitSet(
_gasLimit
);
}
function _proposeCrossChainPeer(
uint64 _chainSelector,
address _peer,
uint8 _peerDecimals
)
internal
{
require(
_chainSelector != 0,
InvalidValue()
);
require(
_peer != ZERO_ADDRESS,
InvalidValue()
);
proposedCrossChainPeer[_chainSelector] = _peer;
proposedCrossChainPeerDecimals[_chainSelector] = _peerDecimals;
crossChainPeerChangeQueuedAt[_chainSelector] = block.timestamp;
emit CrossChainPeerProposed(
_chainSelector,
_peer,
block.timestamp + CROSS_CHAIN_PEER_CHANGE_DELAY
);
}
function _applyCrossChainPeerChange(
uint64 _chainSelector
)
internal
{
uint256 queuedAt = crossChainPeerChangeQueuedAt[_chainSelector];
require(
queuedAt > 0,
NoCrossChainPeerChangeProposed()
);
if (initialized) {
require(
block.timestamp >= queuedAt + CROSS_CHAIN_PEER_CHANGE_DELAY,
CrossChainPeerTimelockNotElapsed()
);
}
crossChainPeer[_chainSelector] = proposedCrossChainPeer[_chainSelector];
crossChainPeerDecimals[_chainSelector] = proposedCrossChainPeerDecimals[_chainSelector];
crossChainPeerEnabled[_chainSelector] = true;
proposedCrossChainPeer[_chainSelector] = ZERO_ADDRESS;
proposedCrossChainPeerDecimals[_chainSelector] = 0;
crossChainPeerChangeQueuedAt[_chainSelector] = 0;
emit CrossChainPeerSet(
_chainSelector,
crossChainPeer[_chainSelector],
true
);
}
function _cancelCrossChainPeerChange(
uint64 _chainSelector
)
internal
{
require(
crossChainPeerChangeQueuedAt[_chainSelector] > 0,
NoCrossChainPeerChangeProposed()
);
proposedCrossChainPeer[_chainSelector] = ZERO_ADDRESS;
proposedCrossChainPeerDecimals[_chainSelector] = 0;
crossChainPeerChangeQueuedAt[_chainSelector] = 0;
emit CrossChainPeerProposalCancelled(
_chainSelector
);
}
function _removeCrossChainPeer(
uint64 _chainSelector
)
internal
{
crossChainPeerEnabled[_chainSelector] = false;
proposedCrossChainPeer[_chainSelector] = ZERO_ADDRESS;
proposedCrossChainPeerDecimals[_chainSelector] = 0;
crossChainPeerChangeQueuedAt[_chainSelector] = 0;
emit CrossChainPeerSet(
_chainSelector,
crossChainPeer[_chainSelector],
false
);
}
function _executeBridgeOut(
uint64 _destChainSelector,
uint256 _amount,
bytes memory _referralData
)
internal
returns (
uint256 dstAmount,
bytes32 messageId
)
{
require(
_amount > 0,
InvalidValue()
);
require(
_referralData.length <= MAX_REFERRAL_BYTES,
ReferralDataTooLong()
);
require(
ccipRouter != ZERO_ADDRESS,
RouterNotSet()
);
require(
crossChainPeerEnabled[_destChainSelector] == true,
CrossChainPeerNotEnabled()
);
require(
msg.sender != InterestRateProxy,
InterestRateProxyCannotMove()
);
require(
balanceOf(msg.sender) >= _amount,
InsufficientBalance()
);
uint256 dust;
(
dstAmount,
dust
) = _scaleAmountForCrossChainPeer(
crossChainPeerDecimals[_destChainSelector],
_amount
);
require(
dstAmount > 0,
MoveAmountTooSmall()
);
_cohortSync(
msg.sender
);
_burn(
msg.sender,
_amount
);
bytes memory referralPayload = _referralData;
if (cohortSyncEnabled == true) {
(
uint256 scaleNumerator,
uint256 scaleDenominator
) = _crossChainScaleFactors(
_destChainSelector
);
referralPayload = _cohortBridgeOut(
msg.sender,
_destChainSelector,
_amount,
scaleNumerator,
scaleDenominator
);
} else {
require(
CohortWeeks._bridgeCarryValid(
_referralData,
type(uint256).max
) == false,
ReferralDataReserved()
);
}
_reduceDepositCap(
_amount
);
Client.EVM2AnyMessage memory message = _buildBridgeMessage(
crossChainPeer[_destChainSelector],
msg.sender,
dstAmount,
referralPayload
);
uint256 fee = IRouterClient(ccipRouter).getFee(
_destChainSelector,
message
);
require(
msg.value >= fee,
InsufficientBridgeFee()
);
messageId = IRouterClient(ccipRouter).ccipSend{value: fee}(
_destChainSelector,
message
);
emit BridgeSent(
msg.sender,
_destChainSelector,
_amount,
dstAmount,
messageId
);
if (dust > 0) {
emit MoveDust(
msg.sender,
crossChainPeer[_destChainSelector],
dust
);
}
_refundExcessFee(
fee
);
}
function _executeBridgeReceive(
Client.Any2EVMMessage calldata _message
)
internal
{
require(
msg.sender == ccipRouter,
NotCcipRouter()
);
uint64 srcChainSelector = _message.sourceChainSelector;
address srcPeer = abi.decode(
_message.sender,
(address)
);
require(
crossChainPeerEnabled[srcChainSelector] == true,
CrossChainPeerNotEnabled()
);
require(
crossChainPeer[srcChainSelector] == srcPeer,
CrossChainPeerMismatch()
);
require(
processedMessageId[_message.messageId] == false,
MessageAlreadyProcessed()
);
processedMessageId[_message.messageId] = true;
address user;
uint256 amount;
bytes memory referralData;
if (_message.data.length == LEGACY_BRIDGE_PAYLOAD_LENGTH) {
(
user,
amount
) = abi.decode(
_message.data,
(address, uint256)
);
} else {
(
user,
amount,
referralData
) = abi.decode(
_message.data,
(address, uint256, bytes)
);
}
require(
amount > 0,
InvalidValue()
);
_assignInterest(
user
);
_raiseDepositCap(
amount
);
_cohortSync(
user
);
_mint(
user,
amount
);
emit BridgeReceived(
user,
srcChainSelector,
amount,
_message.messageId
);
bool carryApplied;
if (referralData.length > 0) {
carryApplied = _cohortBridgeIn(
user,
srcChainSelector,
amount,
referralData
);
}
if (
carryApplied == false
&& referralEnabled
&& referralData.length > 0
) {
emit BridgeReferral(
user,
srcChainSelector,
_message.messageId,
referralData
);
}
}
function _quoteBridgeFee(
uint64 _destChainSelector,
uint256 _amount,
bytes memory _referralData
)
internal
view
returns (uint256)
{
(
uint256 dstAmount,
) = _scaleAmountForCrossChainPeer(
crossChainPeerDecimals[_destChainSelector],
_amount
);
bytes memory referralPayload = cohortSyncEnabled
? new bytes(CohortWeeks.BRIDGE_CARRY_BYTES)
: _referralData;
Client.EVM2AnyMessage memory message = _buildBridgeMessage(
crossChainPeer[_destChainSelector],
msg.sender,
dstAmount,
referralPayload
);
return IRouterClient(ccipRouter).getFee(
_destChainSelector,
message
);
}
function _crossChainScaleFactors(
uint64 _destChainSelector
)
internal
view
returns (
uint256 numerator,
uint256 denominator
)
{
uint8 srcDecimals = decimalsSet;
uint8 dstDecimals = crossChainPeerDecimals[_destChainSelector];
if (dstDecimals >= srcDecimals) {
return (
10 ** (dstDecimals - srcDecimals),
1
);
}
return (
1,
10 ** (srcDecimals - dstDecimals)
);
}
function _buildBridgeMessage(
address _peer,
address _user,
uint256 _dstAmount,
bytes memory _referralData
)
internal
view
returns (Client.EVM2AnyMessage memory)
{
uint256 gasLimit = bridgeGasLimit == 0
? BRIDGE_GAS_LIMIT
: bridgeGasLimit;
return Client.EVM2AnyMessage({
receiver: abi.encode(_peer),
data: abi.encode(
_user,
_dstAmount,
_referralData
),
tokenAmounts: new Client.EVMTokenAmount[](0),
feeToken: address(0),
extraArgs: Client._argsToBytes(
Client.GenericExtraArgsV2({
gasLimit: gasLimit,
allowOutOfOrderExecution: true
})
)
});
}
function _scaleAmountForCrossChainPeer(
uint8 _dstDecimals,
uint256 _srcAmount
)
internal
view
returns (
uint256 dstAmount,
uint256 dust
)
{
uint8 srcDecimals = decimalsSet;
if (srcDecimals == _dstDecimals) {
return (
_srcAmount,
0
);
}
if (_dstDecimals > srcDecimals) {
return (
_srcAmount * (10 ** (_dstDecimals - srcDecimals)),
0
);
}
uint256 factor = 10 ** (srcDecimals - _dstDecimals);
dstAmount = _srcAmount / factor;
dust = _srcAmount % factor;
}
function _refundExcessFee(
uint256 _fee
)
internal
{
uint256 refund = msg.value - _fee;
if (refund == 0) {
return;
}
(
bool ok,
) = payable(msg.sender).call{value: refund}(
""
);
require(
ok,
BridgeRefundFailed()
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {WiseSovrenNodesCrossChainHelper} from "./WiseSovrenNodesCrossChainHelper.sol";
/**
* @dev Top of the vault helper chain. Owns deposit, the combined
* deposit-and-{claim,compound} flows, and the ERC20
* `transfer`/`transferFrom` overrides that route through interest
* assignment.
*/
abstract contract WiseSovrenNodesHelper is WiseSovrenNodesCrossChainHelper {
using SafeERC20 for IERC20;
function _checkValuesDeposit(
uint256 _amount
)
internal
view
{
if (depositsDisabled == true) {
revert DepositsDisabled();
}
if (_amount == 0) {
revert InvalidValue();
}
_checkDepositCap(
_amount
);
}
function _deposit(
uint256 _amount
)
internal
{
_checkValuesDeposit(
_amount
);
USD_TOKEN.safeTransferFrom(
msg.sender,
thirdPartyAddress,
_amount
);
_recordDeposit(
_amount
);
}
function _recordDeposit(
uint256 _amount
)
internal
{
_cohortSync(
msg.sender
);
_mint(
msg.sender,
_amount
);
emit Deposited(
msg.sender,
_amount
);
_cohortCredit(
msg.sender,
_amount
);
}
function _executeDepositAndClaim(
uint256 _amount
)
internal
returns (uint256)
{
_deposit(
_amount
);
return _handleSimpleClaim(
msg.sender
);
}
function _executeDepositAndCompound(
uint256 _amount
)
internal
returns (uint256)
{
_deposit(
_amount
);
return _handleCompoundInterest(
msg.sender
);
}
// ---- ERC20 transfer overrides ----
function transfer(
address to,
uint256 amount
)
public
virtual
override
assignInterest(msg.sender)
assignInterest(to)
nonReentrant
returns (bool)
{
require(
amount > 0,
InvalidValue()
);
_runTransferHook(
msg.sender,
to
);
return super.transfer(
to,
amount
);
}
function transferFrom(
address from,
address to,
uint256 amount
)
public
virtual
override
assignInterest(from)
assignInterest(to)
nonReentrant
returns (bool)
{
require(
amount > 0,
InvalidValue()
);
_runTransferHook(
from,
to
);
return super.transferFrom(
from,
to,
amount
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesInterestHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {WiseSovrenNodesProxyHelper} from "./WiseSovrenNodesProxyHelper.sol";
/**
* @dev Interest accrual, assignment, claim and compound logic plus
* the public view helpers. Most parity-sensitive layer — any drift
* here surfaces as cashedInterest / pending-interest mismatch.
*/
abstract contract WiseSovrenNodesInterestHelper is WiseSovrenNodesProxyHelper {
using SafeERC20 for IERC20;
modifier assignInterest(
address _user
) {
_assignInterest(
_user
);
_;
}
modifier gracePeriodCheck(
address _user
) {
_checkGracePeriod(
_user
);
_;
}
modifier registerLargeDeposit(
address _user
) {
uint256 balanceBefore = balanceOf(
_user
);
_;
_registerLargeDeposit(
_user,
balanceBefore
);
}
function _assignInterest(
address _user
)
internal
{
address userToAssign = _user;
if (_user == InterestRateProxy) {
userToAssign = currentProxyBenefactor;
}
if (userToAssign == ZERO_ADDRESS) {
return;
}
uint256 scaledPending = _pendingInterestScaledByTimeStamp(
userToAssign,
block.timestamp
);
if (scaledPending > 0) {
uint256 accrued = scaledPending
+ interestRemainder[userToAssign];
uint256 interest = accrued
/ PRECISION_FACTOR_E18;
interestRemainder[userToAssign] = accrued
- interest
* PRECISION_FACTOR_E18;
if (interest > 0) {
cashedInterest[userToAssign] += interest;
totalCashedInterest += interest;
emit TotalCashedInterestChanged(
totalCashedInterest
);
}
}
lastSyncTimeStamp[userToAssign] = block.timestamp;
}
function _checkGracePeriod(
address _user
)
internal
view
{
require(
lastLargeDepositAt[_user] == 0
|| block.timestamp >= lastLargeDepositAt[_user] + gracePeriodDuration,
GracePeriodNotElapsed()
);
}
function _registerLargeDeposit(
address _user,
uint256 _balanceBefore
)
internal
{
uint256 threshold = graceThresholdAmount;
if (threshold == 0) {
return;
}
uint256 balanceAfter = balanceOf(
_user
);
if (balanceAfter <= _balanceBefore) {
return;
}
uint256 balanceIncrease = balanceAfter
- _balanceBefore;
address facet = depositHookFacet;
if (facet == ZERO_ADDRESS) {
if (balanceIncrease < threshold) {
return;
}
_stampLargeDeposit(
_user,
balanceIncrease
);
return;
}
_runDepositHook(
facet,
_user,
balanceIncrease
);
}
function _stampLargeDeposit(
address _user,
uint256 _balanceIncrease
)
internal
{
lastLargeDepositAt[_user] = block.timestamp;
emit LargeDepositRegistered(
_user,
_balanceIncrease,
block.timestamp + gracePeriodDuration
);
}
function _executeMoveInterestTo(
address _from,
address _target,
uint256 _amount,
bool _all
)
internal
{
if (_target == _from) {
return;
}
require(
_target != ZERO_ADDRESS && _target != InterestRateProxy,
InvalidValue()
);
uint256 available = cashedInterest[_from];
uint256 moveAmount = _all
? available
: _amount;
require(
moveAmount > 0,
NoInterest()
);
require(
moveAmount <= available,
InvalidValue()
);
cashedInterest[_from] = available - moveAmount;
cashedInterest[_target] = cashedInterest[_target] + moveAmount;
emit InterestMoved(
_from,
_target,
moveAmount
);
}
function _runTransferHook(
address _from,
address _to
)
internal
{
address facet = transferHookFacet;
if (facet == ZERO_ADDRESS) {
return;
}
hookExecuting = true;
(
bool success,
bytes memory returnData
) = facet.delegatecall(
abi.encodeWithSelector(
TRANSFER_HOOK_SELECTOR,
_from,
_to
)
);
hookExecuting = false;
if (success == false) {
assembly {
revert(add(returnData, 0x20), mload(returnData))
}
}
}
function _runDepositHook(
address _facet,
address _user,
uint256 _balanceIncrease
)
internal
{
hookExecuting = true;
(
bool success,
bytes memory returnData
) = _facet.delegatecall(
abi.encodeWithSelector(
DEPOSIT_HOOK_SELECTOR,
_user,
_balanceIncrease
)
);
hookExecuting = false;
if (success == false) {
assembly {
revert(add(returnData, 0x20), mload(returnData))
}
}
}
function _calculateInterestScaledE18(
uint256 _balance,
uint256 _timeDelta
)
internal
view
returns (uint256)
{
uint256 yearFactor = _timeDelta
* PRECISION_FACTOR_E18
/ SECONDS_IN_YEAR;
return _balance
* interestRate
* yearFactor
/ PRECISION_RATE;
}
function _calculateInterest(
uint256 _balance,
uint256 _timeDelta
)
internal
view
returns (uint256)
{
return _calculateInterestScaledE18(
_balance,
_timeDelta
) / PRECISION_FACTOR_E18;
}
function _prepareClaim(
address _user
)
internal
returns (uint256 interestAmount)
{
interestAmount = cashedInterest[_user];
if (interestAmount == 0) {
revert NoInterest();
}
cashedInterest[_user] = 0;
totalCashedInterest -= interestAmount;
emit TotalCashedInterestChanged(
totalCashedInterest
);
}
function _prepareExactAmountClaim(
address _user,
uint256 _amount
)
internal
{
if (_amount == 0) {
revert InvalidValue();
}
uint256 totalInterest = cashedInterest[_user];
if (totalInterest < _amount) {
revert InsufficientInterest();
}
cashedInterest[_user] = totalInterest - _amount;
totalCashedInterest -= _amount;
emit TotalCashedInterestChanged(
totalCashedInterest
);
}
function _handleSimpleClaim(
address _user
)
internal
returns (uint256 interest)
{
interest = _prepareClaim(
_user
);
USD_TOKEN.safeTransfer(
_user,
interest
);
emit ClaimInterestSimple(
_user,
interest
);
}
function _handleClaimExactAmount(
address _user,
uint256 _amount
)
internal
returns (uint256)
{
_prepareExactAmountClaim(
_user,
_amount
);
USD_TOKEN.safeTransfer(
_user,
_amount
);
emit ClaimInterestExactAmount(
_user,
_amount
);
return _amount;
}
function _handleCompoundInterest(
address _user
)
internal
returns (uint256 interest)
{
interest = _prepareClaim(
_user
);
_checkDepositCap(
interest
);
_cohortSync(
_user
);
_mint(
_user,
interest
);
_cohortCredit(
_user,
interest
);
USD_TOKEN.safeTransfer(
thirdPartyAddress,
interest
);
emit CompoundInterest(
_user,
interest
);
}
function _executePartialClaimAndCompound(
address _user,
uint256 _amount
)
internal
returns (uint256 totalClaimed)
{
totalClaimed = _handleClaimExactAmount(
_user,
_amount
);
totalClaimed += _handleCompoundInterest(
_user
);
}
// ---- view helpers ----
function _pendingInterestScaledByTimeStamp(
address _user,
uint256 _timestamp
)
internal
view
returns (uint256)
{
if (_user == InterestRateProxy) {
return 0;
}
uint256 currentBalance = balanceOf(_user)
+ proxyBalance[_user];
if (currentBalance == 0) {
return 0;
}
uint256 lastSync = lastSyncTimeStamp[_user];
if (_timestamp <= lastSync) {
return 0;
}
uint256 timeDelta = _timestamp - lastSync;
return _calculateInterestScaledE18(
currentBalance,
timeDelta
);
}
/**
* @dev Mirrors _assignInterest exactly: the carried interestRemainder
* participates in the floor, so the view reports precisely the amount
* the next sync will bank. A zero scaled pending returns zero because
* _assignInterest skips entirely in that case and the remainder alone
* can never reach a full unit.
*/
function getPendingInterestByTimeStamp(
address _user,
uint256 _timestamp
)
public
view
returns (uint256)
{
uint256 scaledPending = _pendingInterestScaledByTimeStamp(
_user,
_timestamp
);
if (scaledPending == 0) {
return 0;
}
return (scaledPending + interestRemainder[_user])
/ PRECISION_FACTOR_E18;
}
function getPendingInterest(
address _user
)
public
view
returns (uint256)
{
return getPendingInterestByTimeStamp(
_user,
block.timestamp
);
}
function getPendingInterestBulkByTimeStamp(
address[] memory _users,
uint256 _timestamp
)
public
view
returns (uint256[] memory)
{
uint256[] memory pendingInterests = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; i++) {
pendingInterests[i] = getPendingInterestByTimeStamp(
_users[i],
_timestamp
);
}
return pendingInterests;
}
function getPendingInterestBulk(
address[] memory _users
)
external
view
returns (uint256[] memory)
{
return getPendingInterestBulkByTimeStamp(
_users,
block.timestamp
);
}
function getTotalInterestUserByTimeStamp(
address _user,
uint256 _timestamp
)
public
view
returns (uint256)
{
return cashedInterest[_user]
+ getPendingInterestByTimeStamp(
_user,
_timestamp
);
}
function getTotalInterestUser(
address _user
)
external
view
returns (uint256)
{
return getTotalInterestUserByTimeStamp(
_user,
block.timestamp
);
}
function getTotalInterestUserBulkByTimeStamp(
address[] memory _users,
uint256 _timestamp
)
public
view
returns (uint256[] memory)
{
uint256[] memory totalInterests = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; i++) {
totalInterests[i] = getTotalInterestUserByTimeStamp(
_users[i],
_timestamp
);
}
return totalInterests;
}
function getTotalInterestUserBulk(
address[] memory _users
)
public
view
returns (uint256[] memory)
{
return getTotalInterestUserBulkByTimeStamp(
_users,
block.timestamp
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesMoveHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {WiseSovrenNodesBufferHelper} from "./WiseSovrenNodesBufferHelper.sol";
import {IPeerVault} from "../interfaces/IPeerVault.sol";
/**
* @dev Same-chain vault-to-vault movement. The user calls
* `moveBetweenVaults` on the source diamond which (a) banks the
* user's accrued-but-unclaimed interest into `cashedInterest` via the
* `assignInterest` facet modifier — mirroring `bridgeToVault` — so it
* stays claimable on the source diamond and never moves, (b) burns
* `_amount` source vault tokens and relocates the matching deposit-cap
* budget via `_reduceDepositCap`, keeping source room
* (`totalDepositCap - totalSupply()`) unchanged, and (c) calls
* `mintFromPeer` on the destination diamond which raises its cap by
* the decimal-scaled equivalent and mints it to the same user. No
* `USD_TOKEN` is moved between diamonds — the share claim is shifted
* on-chain and the underlying backing is reconciled off-chain by the
* custodian based on the emitted `MovedOut` / `MovedIn` events.
* Scale-down rounding loss is surfaced via `MoveDust` so off-chain
* reconciliation can see the lost dust rather than reasoning about it
* from event amounts alone.
*
* Enabling a peer is timelocked: `proposePeerVault` queues the
* change, `executePeerVaultChange` activates it after
* `PEER_VAULT_CHANGE_DELAY`. Disabling is instant via
* `removePeerVault` so a misbehaving peer can be quarantined
* without waiting out the delay.
*
* Referral attribution: a same-chain move is a
* system relocation, so the cohort recorder CARRIES the moved slice
* of referral credit instead of destroying it. The exit path keeps
* the pre-burn `_cohortSync` (any pre-existing deficit clamps
* sale-like) and replaces the post-burn sync with `_cohortMoveOut`,
* which captures the reduction walk's exact slot pairs and stages
* them in the chain registry before `mintFromPeer` is called; the
* enter path adds `_cohortMoveIn` after the mint, which drains and
* replants them at the same slots in the same transaction. The user
* is by construction the same address on both ends — `mintFromPeer`
* is always called with `msg.sender` and carries no recipient
* parameter. Every attribution failure degrades soft (anomaly event,
* move unaffected); both stubs are inert until `cohortSyncEnabled`.
* Decimal scaling factors are computed once per move via
* `_peerScaleFactors` and shared by the amount scaling and the
* carry's per-component scaling.
*/
abstract contract WiseSovrenNodesMoveHelper is WiseSovrenNodesBufferHelper {
function _proposePeerVault(
address _peer
)
internal
{
require(
_peer != ZERO_ADDRESS,
InvalidValue()
);
require(
_peer != address(this),
SelfPeerNotAllowed()
);
peerVaultChangeQueuedAt[_peer] = block.timestamp;
emit PeerVaultProposed(
_peer,
block.timestamp + PEER_VAULT_CHANGE_DELAY
);
}
function _applyPeerVaultChange(
address _peer
)
internal
{
uint256 queuedAt = peerVaultChangeQueuedAt[_peer];
require(
queuedAt > 0,
NoPeerVaultChangeProposed()
);
require(
block.timestamp >= queuedAt + PEER_VAULT_CHANGE_DELAY,
PeerVaultTimelockNotElapsed()
);
peerVault[_peer] = true;
peerVaultChangeQueuedAt[_peer] = 0;
emit PeerVaultSet(
_peer,
true
);
}
function _cancelPeerVaultChange(
address _peer
)
internal
{
require(
peerVaultChangeQueuedAt[_peer] > 0,
NoPeerVaultChangeProposed()
);
peerVaultChangeQueuedAt[_peer] = 0;
emit PeerVaultProposalCancelled(
_peer
);
}
function _removePeerVault(
address _peer
)
internal
{
peerVault[_peer] = false;
peerVaultChangeQueuedAt[_peer] = 0;
emit PeerVaultSet(
_peer,
false
);
}
function _executeMoveOut(
address _dstVault,
uint256 _amount
)
internal
returns (uint256 dstAmount)
{
require(
_amount > 0,
InvalidValue()
);
require(
_dstVault != ZERO_ADDRESS,
InvalidValue()
);
require(
_dstVault != address(this),
SelfPeerNotAllowed()
);
require(
peerVault[_dstVault] == true,
PeerVaultNotEnabled()
);
require(
msg.sender != InterestRateProxy,
InterestRateProxyCannotMove()
);
require(
balanceOf(msg.sender) >= _amount,
InsufficientBalance()
);
(
uint256 scaleNumerator,
uint256 scaleDenominator
) = _peerScaleFactors(
_dstVault
);
dstAmount = _amount * scaleNumerator / scaleDenominator;
uint256 dust = _amount - dstAmount * scaleDenominator / scaleNumerator;
require(
dstAmount > 0,
MoveAmountTooSmall()
);
_cohortSync(
msg.sender
);
_burn(
msg.sender,
_amount
);
_cohortMoveOut(
msg.sender,
_dstVault,
_amount,
scaleNumerator,
scaleDenominator
);
_reduceDepositCap(
_amount
);
emit MovedOut(
msg.sender,
_dstVault,
_amount,
dstAmount
);
if (dust > 0) {
emit MoveDust(
msg.sender,
_dstVault,
dust
);
}
IPeerVault(_dstVault).mintFromPeer(
msg.sender,
dstAmount
);
}
/**
* @dev Same-chain move-in, mirroring `_executeBridgeReceive`. The shares
* were burned on a registered peer vault (`_executeMoveOut`, which took
* the matching deposit-cap budget out of that peer), so they are
* relocation, not new local origination: the cap is raised by the moved
* amount via `_raiseDepositCap` before the mint, keeping the move
* room-neutral on both ends and never reverting `DepositExceedCap` on a
* near-cap destination — the same cap-relocation room law the
* bridge-receive path holds. The pre-mint `_cohortSync`
* clamps the user's pre-existing deficit against OLD tracked before
* the balance grows (clamp-before-mint, dip-healing closed); the
* post-mint `_cohortMoveIn` then replants the attribution the source
* staged for this move — ordered after the mint so replanted tracked
* never exceeds the held balance.
*/
function _executeMintFromPeer(
address _user,
uint256 _amount
)
internal
{
require(
peerVault[msg.sender] == true,
NotPeerVault()
);
require(
_amount > 0,
InvalidValue()
);
_raiseDepositCap(
_amount
);
_cohortSync(
_user
);
_mint(
_user,
_amount
);
_cohortMoveIn(
_user,
msg.sender
);
emit MovedIn(
_user,
msg.sender,
_amount
);
}
function _peerScaleFactors(
address _dstVault
)
internal
view
returns (
uint256 numerator,
uint256 denominator
)
{
uint8 srcDec = decimalsSet;
uint8 dstDec = IERC20Metadata(
_dstVault
).decimals();
if (dstDec >= srcDec) {
return (
10 ** (dstDec - srcDec),
1
);
}
return (
1,
10 ** (srcDec - dstDec)
);
}
function _getMoveableBalance(
address _user
)
internal
view
returns (uint256)
{
return balanceOf(
_user
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesProxyHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {WiseSovrenNodesAdminHelper} from "./WiseSovrenNodesAdminHelper.sol";
/**
* @dev Proxy-balance accounting. Inc/dec are caller-gated to
* `InterestRateProxy` at the facet boundary.
*/
abstract contract WiseSovrenNodesProxyHelper is WiseSovrenNodesAdminHelper {
function _increaseProxyBalance(
address _proxyUser,
uint256 _amount
)
internal
{
proxyBalance[_proxyUser] += _amount;
emit ProxyBalanceIncreased(
_proxyUser,
_amount
);
}
function _decreaseProxyBalance(
address _proxyUser,
uint256 _amount
)
internal
{
proxyBalance[_proxyUser] -= _amount;
emit ProxyBalanceDecreased(
_proxyUser,
_amount
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesQueueHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {WiseSovrenNodesQueueLowLevelHelper} from "./WiseSovrenNodesQueueLowLevelHelper.sol";
/**
* @dev Order-processing layer for the queue surface. Owns the
* `setProxyBenefactor` post-action modifier, `_processOrder`, and
* the plan/solve traversal.
*/
abstract contract WiseSovrenNodesQueueHelper is WiseSovrenNodesQueueLowLevelHelper {
modifier setProxyBenefactor() {
_;
_setProxyBenefactor(
ZERO_ADDRESS
);
}
function _processOrder(
uint256 _queMemberId,
int256 _incentive,
uint256 _amount,
bool _isFullFulfill
)
internal
returns (
uint256 wiseSovrenNodesTokenAmount,
uint256 stableCoinTokenAmount
)
{
_validateOrderProcessing(
_queMemberId,
_incentive,
_amount,
_isFullFulfill
);
QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_incentive];
uint256 discountedAmount = _predictChargedAmount(
_amount,
_incentive
);
address cashedMember = member.member;
_changeProxyAccounting(
_decreaseProxyBalance,
cashedMember,
_amount
);
_setProxyBenefactor(
cashedMember
);
_executeTransfers(
cashedMember,
_amount,
discountedAmount
);
if (_isFullFulfill) {
currentOrderIdByIncentive[_incentive] = member.headPointer;
_finalizeMemberRemoval(
_queMemberId,
member,
_incentive,
false
);
} else {
member.amount -= _amount;
}
emit OrderProcessed(
msg.sender,
cashedMember,
_queMemberId,
_incentive,
_amount,
_isFullFulfill
);
return (
_amount,
discountedAmount
);
}
function _fulfillOrderBulk(
FulfillOrderBulkVars memory vars
)
internal
returns (
uint256 vaultTokensReceived,
uint256 usdSpent
)
{
require(
_hasNoOrdersToProcess(
vars.orders,
vars.partials
) == false,
NoOrdersPresent()
);
for (uint256 i; i < vars.orders.length; ++i) {
(
uint256 vt,
uint256 usd
) = _processOrder({
_queMemberId: vars.orders[i],
_incentive: vars.incentives[i],
_amount: QueMemberByIdAndIncentive[vars.orders[i]][vars.incentives[i]].amount,
_isFullFulfill: true
});
vaultTokensReceived += vt;
usdSpent += usd;
}
if (vars.partials.length > 0 && vars.partialAmount > 0) {
(
uint256 vt,
uint256 usd
) = _processOrder({
_queMemberId: vars.partials[0],
_incentive: vars.incentives[vars.incentives.length - 1],
_amount: vars.partialAmount,
_isFullFulfill: false
});
vaultTokensReceived += vt;
usdSpent += usd;
}
require(
vaultTokensReceived >= vars.minReceiveAmount,
AmountReceivedTooLow()
);
require(
usdSpent <= vars.maxUsdToSpend,
AmountSpentTooHigh()
);
}
function _processOrderFromContract(
uint256 _queMemberId,
int256 _incentive,
uint256 _amount,
bool _isFullFulfill
)
internal
returns (
uint256 wiseSovrenNodesTokenAmount,
uint256 stableCoinTokenAmount
)
{
_validateOrderProcessing(
_queMemberId,
_incentive,
_amount,
_isFullFulfill
);
QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_incentive];
uint256 discountedAmount = _predictChargedAmount(
_amount,
_incentive
);
address cashedMember = member.member;
_changeProxyAccounting(
_decreaseProxyBalance,
cashedMember,
_amount
);
_setProxyBenefactor(
cashedMember
);
_executeTransfersFromContract(
cashedMember,
_amount,
discountedAmount
);
if (_isFullFulfill) {
currentOrderIdByIncentive[_incentive] = member.headPointer;
_finalizeMemberRemoval(
_queMemberId,
member,
_incentive,
false
);
} else {
member.amount -= _amount;
}
emit OrderProcessed(
msg.sender,
cashedMember,
_queMemberId,
_incentive,
_amount,
_isFullFulfill
);
return (
_amount,
discountedAmount
);
}
function _fulfillOrderBulkFromContract(
FulfillOrderBulkVars memory vars
)
internal
returns (
uint256 vaultTokensReceived,
uint256 usdSpent
)
{
require(
_hasNoOrdersToProcess(
vars.orders,
vars.partials
) == false,
NoOrdersPresent()
);
for (uint256 i; i < vars.orders.length; ++i) {
(
uint256 vt,
uint256 usd
) = _processOrderFromContract({
_queMemberId: vars.orders[i],
_incentive: vars.incentives[i],
_amount: QueMemberByIdAndIncentive[vars.orders[i]][vars.incentives[i]].amount,
_isFullFulfill: true
});
vaultTokensReceived += vt;
usdSpent += usd;
}
if (vars.partials.length > 0 && vars.partialAmount > 0) {
(
uint256 vt,
uint256 usd
) = _processOrderFromContract({
_queMemberId: vars.partials[0],
_incentive: vars.incentives[vars.incentives.length - 1],
_amount: vars.partialAmount,
_isFullFulfill: false
});
vaultTokensReceived += vt;
usdSpent += usd;
}
require(
vaultTokensReceived >= vars.minReceiveAmount,
AmountReceivedTooLow()
);
require(
usdSpent <= vars.maxUsdToSpend,
AmountSpentTooHigh()
);
}
function _executeCompoundViaFulfillBulk(
FulfillOrderBulkVars memory vars
)
internal
gracePeriodCheck(msg.sender)
registerLargeDeposit(msg.sender)
returns (
uint256 vaultTokensReceived,
uint256 usdSpent
)
{
(
vaultTokensReceived,
usdSpent
) = _fulfillOrderBulkFromContract(
vars
);
_prepareExactAmountClaim(
msg.sender,
usdSpent
);
uint256 remainder = cashedInterest[msg.sender];
if (remainder > 0) {
_handleCompoundInterest(
msg.sender
);
}
emit CompoundViaQueue(
msg.sender,
usdSpent,
vaultTokensReceived,
remainder
);
}
function _processOrderInPlan(
PlanVars memory _v,
uint256[] memory _tempFull,
uint256 _amountLeft,
int256 _incentive
)
internal
view
returns (
uint256 newAmountLeft,
uint256 nextStartingId
)
{
QueMember storage entry = QueMemberByIdAndIncentive[_v.current][_incentive];
uint256 amt = entry.amount;
_v.ordersConsidered++;
if (_isEmptyOrder(entry)) {
(
_v.current,
nextStartingId
) = _moveToNextOrder(
entry,
_incentive
);
return (
_amountLeft,
nextStartingId
);
}
if (_amountLeft >= amt) {
_tempFull[_v.fullIndex] = _v.current;
_v.fullIndex++;
newAmountLeft = _amountLeft - amt;
(
_v.current,
nextStartingId
) = _moveToNextOrder(
entry,
_incentive
);
} else {
_v.partialId = _v.current;
_v.hasPartial = true;
newAmountLeft = 0;
nextStartingId = _v.current;
}
}
function _traverseOrdersForAmount(
uint256 _amount,
int256 _incentive
)
internal
view
returns (
uint256[] memory tempFull,
uint256 partialId,
bool hasPartial,
uint256 fullIndex
)
{
uint256 total = activeOrderCountByIncentive[_incentive];
tempFull = new uint256[](total);
uint256 current = currentOrderIdByIncentive[_incentive];
uint256 amountLeft = _amount;
while (
amountLeft > 0
&& current < earliestValidQueMemberByIncentive[_incentive]
&& fullIndex < total
) {
QueMember storage entry = QueMemberByIdAndIncentive[current][_incentive];
if (_isEmptyOrder(entry)) {
current = entry.headPointer;
continue;
}
if (amountLeft >= entry.amount) {
tempFull[fullIndex] = current;
fullIndex++;
amountLeft -= entry.amount;
current = entry.headPointer;
} else {
partialId = current;
hasPartial = true;
break;
}
}
}
function _processIncentiveForCost(
int256 _incentive,
uint256 _remainingUsd
)
internal
view
returns (
uint256 tokensReceived,
uint256 usdSpent
)
{
uint256 currentOrderId = currentOrderIdByIncentive[_incentive];
uint256 earliestId = earliestValidQueMemberByIncentive[_incentive];
uint256 remainingBudget = _remainingUsd;
while (currentOrderId < earliestId && remainingBudget > 0) {
QueMember storage entry = QueMemberByIdAndIncentive[currentOrderId][_incentive];
if (_isEmptyOrder(entry)) {
currentOrderId = entry.headPointer;
continue;
}
(
uint256 tokens,
uint256 spent
) = _processOrderForCost(
entry,
_incentive,
remainingBudget
);
tokensReceived += tokens;
remainingBudget -= spent;
if (
spent < _predictChargedAmount(
entry.amount,
_incentive
)
) {
break;
}
currentOrderId = entry.headPointer;
}
usdSpent = _remainingUsd - remainingBudget;
}
function _solveForAmountWithIncentive(
uint256 _amount,
int256 _incentive
)
public
view
returns (
uint256[] memory fullOrderIds,
uint256[] memory partialOrderIds
)
{
(
uint256[] memory tempFull,
uint256 partialId,
bool hasPartial,
uint256 fullIndex
) = _traverseOrdersForAmount(
_amount,
_incentive
);
fullOrderIds = new uint256[](fullIndex);
for (uint256 i; i < fullIndex; i++) {
fullOrderIds[i] = tempFull[i];
}
if (hasPartial) {
partialOrderIds = new uint256[](1);
partialOrderIds[0] = partialId;
} else {
partialOrderIds = new uint256[](0);
}
}
function _solveForAmount(
uint256 _amount,
bool _allowNegativeIncentives
)
internal
view
returns (
int256[] memory incentives,
uint256[] memory orders,
uint256[] memory partials
)
{
SolveForAmountVars memory v = _initializeSolveVars();
uint256 remainingAmount = _amount;
int256[] memory pos = _initializePositiveIncentivesArray();
for (uint256 i; i < pos.length && remainingAmount > 0; ++i) {
(
uint256[] memory fullIds,
uint256[] memory partialIds
) = _solveForAmountWithIncentive(
remainingAmount,
pos[i]
);
remainingAmount = _processFullOrdersForIncentive(
v,
fullIds,
pos[i],
remainingAmount
);
if (remainingAmount > 0 && partialIds.length != 0) {
_processPartialOrderForIncentive(
v,
partialIds,
pos[i]
);
remainingAmount = 0;
break;
}
}
if (_allowNegativeIncentives && remainingAmount > 0) {
int256[] memory neg = _initializeNegativeIncentivesArray();
for (uint256 j; j < neg.length && remainingAmount > 0; ++j) {
(
uint256[] memory fullIds,
uint256[] memory partialIds
) = _solveForAmountWithIncentive(
remainingAmount,
neg[j]
);
remainingAmount = _processFullOrdersForIncentive(
v,
fullIds,
neg[j],
remainingAmount
);
if (remainingAmount > 0 && partialIds.length != 0) {
_processPartialOrderForIncentive(
v,
partialIds,
neg[j]
);
remainingAmount = 0;
break;
}
}
}
return _buildSolveResults(
v
);
}
}
src/diamond/vault/helpers/WiseSovrenNodesQueueLowLevelHelper.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {WiseSovrenNodesHelper} from "./WiseSovrenNodesHelper.sol";
import {WiseSovrenNodesIncentiveLadder} from "../WiseSovrenNodesIncentiveLadder.sol";
/**
* @dev Low-level queue helper: validators, linked-list manipulation,
* token movement, proxy-benefactor and proxy-balance bridges, order
* traversal primitives, and discount math. In the merged diamond the
* vault is its own custodian, so the former external bridges into the
* vault are direct internal calls.
*
* The lane arrays are read from {WiseSovrenNodesIncentiveLadder} so
* the tiers the solver walks are the same tiers the constructor
* marks allowed.
*/
abstract contract WiseSovrenNodesQueueLowLevelHelper is WiseSovrenNodesHelper {
using SafeERC20 for IERC20;
function _setProxyBenefactor(
address _user
)
internal
{
_updateProxyBenefactor(
_user
);
}
function _validateJoinQue(
uint256 _amount,
int256 _incentive
)
internal
view
{
require(
_amount > 0,
ZeroAmount()
);
_requireIncentiveAllowed(
_incentive
);
_requireMinDeposit(
_amount
);
}
function _transferTokensIn(
uint256 _amount
)
internal
{
_moveVaultTokens(
msg.sender,
address(this),
_amount
);
_cohortSync(
msg.sender
);
}
function _moveVaultTokens(
address _from,
address _to,
uint256 _amount
)
internal
{
_assignInterest(
_from
);
_assignInterest(
_to
);
_runTransferHook(
_from,
_to
);
_transfer(
_from,
_to,
_amount
);
}
function _createQueMember(
uint256 _amount,
int256 _incentive
)
internal
returns (
QueMember memory member,
uint256 newId
)
{
newId = earliestValidQueMemberByIncentive[_incentive];
QueMember storage hole = QueMemberByIdAndIncentive[newId][_incentive];
uint256 prevId = hole.tailPointer;
uint256 nextId = newId + 1;
member = QueMember({
member: msg.sender,
amount: _amount,
tailPointer: prevId,
headPointer: nextId
});
QueMemberByIdAndIncentive[newId][_incentive] = member;
if (prevId < earliestValidQueMemberByIncentive[_incentive]) {
QueMemberByIdAndIncentive[prevId][_incentive].headPointer = newId;
}
QueMemberByIdAndIncentive[nextId][_incentive].tailPointer = newId;
unchecked {
++earliestValidQueMemberByIncentive[_incentive];
}
}
function _updateJoinQueState(
uint256 _amount,
int256 _incentive
)
internal
{
_changeProxyAccounting(
_increaseProxyBalance,
msg.sender,
_amount
);
totalActiveOrders++;
activeOrderCountByIncentive[_incentive]++;
}
function _validateLeaveQue(
uint256 _queMemberId,
int256 _incentive
)
internal
view
{
_requireValidMemberId(
_queMemberId,
_incentive
);
}
function _hasNoOrdersToProcess(
uint256[] memory _orders,
uint256[] memory _partials
)
internal
pure
returns (bool)
{
return _orders.length == 0 && _partials.length == 0;
}
function _validateReduceAmount(
uint256 _queMemberId,
int256 _incentive,
uint256 _reduceBy
)
internal
view
{
require(
_reduceBy > 0,
ZeroAmount()
);
_requireValidMemberId(
_queMemberId,
_incentive
);
}
function _executeReduction(
QueMember storage _member,
uint256 _reduceBy
)
internal
{
_changeProxyAccounting(
_decreaseProxyBalance,
msg.sender,
_reduceBy
);
_member.amount -= _reduceBy;
_requireMinDeposit(
_member.amount
);
}
function _changeProxyAccounting(
function(address, uint256) internal _changeProxyBalance,
address _user,
uint256 _amount
)
internal
{
_updateProxyBenefactor(
_user
);
_assignInterest(
_user
);
_changeProxyBalance(
_user,
_amount
);
}
function _validateMemberCanReduce(
QueMember storage _member,
uint256 _reduceBy
)
internal
view
{
require(
_member.member == msg.sender,
NotMember()
);
require(
_reduceBy < _member.amount,
AmountTooHigh()
);
}
function _validateMemberCanLeave(
QueMember storage _member
)
internal
view
{
require(
_member.member == msg.sender,
NotMember()
);
}
function _updateCurrentOrderIfNeeded(
uint256 _queMemberId,
int256 _incentive,
QueMember storage _member
)
internal
{
if (_queMemberId == currentOrderIdByIncentive[_incentive]) {
currentOrderIdByIncentive[_incentive] = _member.headPointer;
}
}
function _updateLinkedListPointers(
uint256 _queMemberId,
QueMember storage _member,
int256 _incentive
)
internal
{
if (_queMemberId == currentOrderIdByIncentive[_incentive]) {
QueMemberByIdAndIncentive[_member.headPointer][_incentive].tailPointer = _member.headPointer;
return;
}
QueMemberByIdAndIncentive[_member.tailPointer][_incentive].headPointer = _member.headPointer;
QueMemberByIdAndIncentive[_member.headPointer][_incentive].tailPointer = _member.tailPointer;
}
function _transferTokensOut(
address _to,
uint256 _amount
)
internal
{
_moveVaultTokens(
address(this),
_to,
_amount
);
}
function _requireIncentiveAllowed(
int256 _incentive
)
internal
view
{
require(
incentiveAllowed[_incentive],
IncentiveNotAllowed()
);
}
function _requireMinDeposit(
uint256 _amount
)
internal
view
{
require(
_amount >= minDepositAmount,
AmountTooLow()
);
}
function _requireValidMemberId(
uint256 _id,
int256 _incentive
)
internal
view
{
require(
_id < earliestValidQueMemberByIncentive[_incentive],
QueMemberIdTooHigh()
);
}
function _validateOrderProcessing(
uint256 _queMemberId,
int256 _incentive,
uint256 _amount,
bool _isFullFulfill
)
internal
view
{
_requireValidMemberId(
_queMemberId,
_incentive
);
if (_isFullFulfill) {
require(
QueMemberByIdAndIncentive[_queMemberId][_incentive].amount > 0,
ZeroAmount()
);
} else {
require(
_amount > 0,
ZeroAmount()
);
require(
_amount < QueMemberByIdAndIncentive[_queMemberId][_incentive].amount,
AmountTooHigh()
);
}
_requireIncentiveAllowed(
_incentive
);
require(
currentOrderIdByIncentive[_incentive] == _queMemberId,
OrderNotReady()
);
}
function _executeTransfers(
address _cashedMember,
uint256 _amount,
uint256 _discountedAmount
)
internal
{
USD_TOKEN.safeTransferFrom(
msg.sender,
_cashedMember,
_discountedAmount
);
_transferTokensOut(
msg.sender,
_amount
);
}
function _executeTransfersFromContract(
address _cashedMember,
uint256 _amount,
uint256 _discountedAmount
)
internal
{
USD_TOKEN.safeTransfer(
_cashedMember,
_discountedAmount
);
_transferTokensOut(
msg.sender,
_amount
);
}
function _initializeNegativeIncentivesArray()
internal
pure
returns (int256[] memory)
{
return WiseSovrenNodesIncentiveLadder.negativeIncentives();
}
function _initializeAllIncentivesArray()
internal
pure
returns (int256[] memory)
{
return WiseSovrenNodesIncentiveLadder.allIncentives();
}
function _initializePositiveIncentivesArray()
internal
pure
returns (int256[] memory)
{
return WiseSovrenNodesIncentiveLadder.positiveIncentives();
}
function _calculateDiscountFactor(
int256 _incentive
)
internal
pure
returns (uint256)
{
return _incentive >= 0
? PRECISION_RATE - uint256(_incentive)
: PRECISION_RATE + uint256(-_incentive);
}
function _isEmptyOrder(
QueMember storage _entry
)
internal
view
returns (bool)
{
return _entry.amount == 0;
}
function _moveToNextOrder(
QueMember storage _entry,
int256 _incentive
)
internal
view
returns (
uint256 newCurrent,
uint256 newNextId
)
{
newCurrent = _entry.headPointer;
if (newCurrent == 0 || newCurrent >= earliestValidQueMemberByIncentive[_incentive]) {
newNextId = earliestValidQueMemberByIncentive[_incentive];
newCurrent = earliestValidQueMemberByIncentive[_incentive];
} else {
newNextId = newCurrent;
}
}
function _shouldContinuePlanTraversal(
uint256 _amountLeft,
PlanVars memory _v,
int256 _incentive,
uint256 _maxOrdersToConsider,
uint256 _considerationLimit
)
internal
view
returns (bool)
{
return _amountLeft > 0
&& _v.current < earliestValidQueMemberByIncentive[_incentive]
&& _v.fullIndex < _v.arraySize
&& (_maxOrdersToConsider == 0 || _v.ordersConsidered < _considerationLimit);
}
function _buildFinalOrderArrays(
PlanVars memory _v,
uint256[] memory _tempFull
)
internal
pure
returns (
uint256[] memory fullOrderIds,
uint256[] memory partialOrderIds
)
{
fullOrderIds = new uint256[](_v.fullIndex);
for (uint256 i; i < _v.fullIndex; i++) {
fullOrderIds[i] = _tempFull[i];
}
if (_v.hasPartial) {
partialOrderIds = new uint256[](1);
partialOrderIds[0] = _v.partialId;
} else {
partialOrderIds = new uint256[](0);
}
}
function _initializePlanVars(
uint256 _activeCount,
uint256 _maxOrdersToConsider
)
internal
pure
returns (PlanVars memory v)
{
if (_maxOrdersToConsider == 0) {
v.arraySize = _activeCount;
} else {
v.arraySize = _activeCount < _maxOrdersToConsider
? _activeCount
: _maxOrdersToConsider;
}
}
function _initializeSolveVars()
internal
view
returns (SolveForAmountVars memory v)
{
v.incs = _initializePositiveIncentivesArray();
v.tempIncentives = new int256[](totalActiveOrders);
v.tempOrders = new uint256[](totalActiveOrders);
v.tempPartials = new uint256[](totalActiveOrders);
}
function _processFullOrdersForIncentive(
SolveForAmountVars memory _v,
uint256[] memory _fullIds,
int256 _incentive,
uint256 _remainingAmount
)
internal
view
returns (uint256 newRemainingAmount)
{
newRemainingAmount = _remainingAmount;
for (uint256 j; j < _fullIds.length; j++) {
if (newRemainingAmount == 0) {
break;
}
uint256 id = _fullIds[j];
uint256 amt = QueMemberByIdAndIncentive[id][_incentive].amount;
if (amt == 0 || amt > newRemainingAmount) {
continue;
}
_v.tempIncentives[_v.orderIndex] = _incentive;
_v.tempOrders[_v.orderIndex] = id;
_v.orderIndex++;
newRemainingAmount -= amt;
}
}
function _processPartialOrderForIncentive(
SolveForAmountVars memory _v,
uint256[] memory _partialIds,
int256 _incentive
)
internal
pure
{
if (_partialIds.length != 0) {
_v.tempPartials[_v.partialIndex] = _partialIds[0];
_v.tempIncentives[_v.orderIndex + _v.partialIndex] = _incentive;
_v.partialIndex++;
}
}
function _buildSolveResults(
SolveForAmountVars memory _v
)
internal
pure
returns (
int256[] memory incentives,
uint256[] memory orders,
uint256[] memory partials
)
{
incentives = new int256[](_v.orderIndex + _v.partialIndex);
orders = new uint256[](_v.orderIndex);
partials = new uint256[](_v.partialIndex);
for (uint256 k; k < _v.orderIndex; k++) {
incentives[k] = _v.tempIncentives[k];
orders[k] = _v.tempOrders[k];
}
for (uint256 l; l < _v.partialIndex; l++) {
incentives[_v.orderIndex + l] = _v.tempIncentives[_v.orderIndex + l];
partials[l] = _v.tempPartials[l];
}
}
function _collectOrdersForIncentive(
int256 _currentIncentive,
address _user,
bool _checkUser,
QueMember[] memory _tempOrders,
int256[] memory _tempIncentives,
uint256 _currentIndex
)
internal
view
returns (uint256 newIndex)
{
newIndex = _currentIndex;
uint256 maxIdForIncentive = earliestValidQueMemberByIncentive[_currentIncentive];
for (uint256 id = 0; id < maxIdForIncentive; id++) {
QueMember storage member = QueMemberByIdAndIncentive[id][_currentIncentive];
if (_shouldIncludeOrder(member, _user, _checkUser)) {
_tempOrders[newIndex] = member;
_tempIncentives[newIndex] = _currentIncentive;
newIndex++;
}
}
}
function _shouldIncludeOrder(
QueMember storage _member,
address _user,
bool _checkUser
)
internal
view
returns (bool)
{
return _checkUser
? (_member.member == _user && _member.amount > 0)
: (_member.member != ZERO_ADDRESS && _member.amount > 0);
}
function _copyToFinalArrays(
QueMember[] memory _tempOrders,
int256[] memory _tempIncentives,
uint256 _actualLength
)
internal
pure
returns (
QueMember[] memory actualOrders,
int256[] memory actualIncentives
)
{
actualOrders = new QueMember[](_actualLength);
actualIncentives = new int256[](_actualLength);
for (uint256 j = 0; j < _actualLength; j++) {
actualOrders[j] = _tempOrders[j];
actualIncentives[j] = _tempIncentives[j];
}
}
function _collectAllOrders(
address _user,
bool _checkUser
)
internal
view
returns (
QueMember[] memory,
int256[] memory
)
{
int256[] memory allIncentives = _initializeAllIncentivesArray();
QueMember[] memory tempOrders = new QueMember[](totalActiveOrders);
int256[] memory tempIncentives = new int256[](totalActiveOrders);
uint256 index = 0;
for (uint256 i = 0; i < allIncentives.length; i++) {
index = _collectOrdersForIncentive(
allIncentives[i],
_user,
_checkUser,
tempOrders,
tempIncentives,
index
);
}
return _copyToFinalArrays(
tempOrders,
tempIncentives,
index
);
}
function _collectOrdersForIncentiveWithId(
int256 _currentIncentive,
address _user,
bool _checkUser,
QueMemberWithId[] memory _tempOrders,
uint256 _currentIndex
)
internal
view
returns (uint256 newIndex)
{
newIndex = _currentIndex;
uint256 maxIdForIncentive = earliestValidQueMemberByIncentive[_currentIncentive];
for (uint256 id = 0; id < maxIdForIncentive; id++) {
QueMember storage member = QueMemberByIdAndIncentive[id][_currentIncentive];
if (_shouldIncludeOrder(member, _user, _checkUser)) {
_tempOrders[newIndex] = QueMemberWithId({
memberId: id,
incentive: _currentIncentive,
member: member.member,
amount: member.amount,
tailPointer: member.tailPointer,
headPointer: member.headPointer
});
newIndex++;
}
}
}
function _copyToFinalArrayWithId(
QueMemberWithId[] memory _tempOrders,
uint256 _actualLength
)
internal
pure
returns (QueMemberWithId[] memory actualOrders)
{
actualOrders = new QueMemberWithId[](_actualLength);
for (uint256 j = 0; j < _actualLength; j++) {
actualOrders[j] = _tempOrders[j];
}
}
function _collectAllOrdersWithId(
address _user,
bool _checkUser
)
internal
view
returns (QueMemberWithId[] memory)
{
int256[] memory allIncentives = _initializeAllIncentivesArray();
QueMemberWithId[] memory tempOrders = new QueMemberWithId[](totalActiveOrders);
uint256 index = 0;
for (uint256 i = 0; i < allIncentives.length; i++) {
index = _collectOrdersForIncentiveWithId(
allIncentives[i],
_user,
_checkUser,
tempOrders,
index
);
}
return _copyToFinalArrayWithId(
tempOrders,
index
);
}
function _calculateFullOrdersCost(
uint256[] memory _orders,
int256[] memory _incentives
)
internal
view
returns (
uint256 costInUsd,
uint256 totalTokensPlanned
)
{
for (uint256 i = 0; i < _orders.length; i++) {
uint256 orderId = _orders[i];
int256 incentive = _incentives[i];
uint256 orderAmount = QueMemberByIdAndIncentive[orderId][incentive].amount;
costInUsd += _predictChargedAmount(
orderAmount,
incentive
);
totalTokensPlanned += orderAmount;
}
}
function _predictDiscountedAmount(
uint256 _amount,
int256 _incentive
)
internal
pure
returns (uint256)
{
uint256 factor = _calculateDiscountFactor(
_incentive
);
return Math.mulDiv(
_amount,
factor,
PRECISION_RATE
);
}
function _predictChargedAmount(
uint256 _amount,
int256 _incentive
)
internal
pure
returns (uint256)
{
uint256 discounted = _predictDiscountedAmount(
_amount,
_incentive
);
return discounted == 0
? _amount
: discounted;
}
function _calculatePartialOrderCost(
uint256[] memory _partials,
int256[] memory _incentives,
uint256 _ordersLength,
uint256 _tokensToReceive,
uint256 _totalTokensPlanned
)
internal
pure
returns (
uint256 partialCost,
uint256 partialTokens
)
{
if (_partials.length > 0) {
int256 partialIncentive = _incentives[_ordersLength];
partialTokens = _tokensToReceive - _totalTokensPlanned;
partialCost = _predictChargedAmount(
partialTokens,
partialIncentive
);
}
}
function _processOrderForCost(
QueMember storage _entry,
int256 _incentive,
uint256 _remainingUsd
)
internal
view
returns (
uint256 tokensAcquired,
uint256 usdSpent
)
{
uint256 orderCost = _predictChargedAmount(
_entry.amount,
_incentive
);
if (_remainingUsd >= orderCost) {
tokensAcquired = _entry.amount;
usdSpent = orderCost;
} else {
uint256 factor = _calculateDiscountFactor(
_incentive
);
tokensAcquired = Math.mulDiv(
_remainingUsd,
PRECISION_RATE,
factor
);
usdSpent = _remainingUsd;
}
}
function _finalizeMemberRemoval(
uint256 _queMemberId,
QueMember storage _member,
int256 _incentive,
bool _handleAccounting
)
internal
{
if (_handleAccounting) {
_changeProxyAccounting(
_decreaseProxyBalance,
_member.member,
_member.amount
);
}
_updateLinkedListPointers(
_queMemberId,
_member,
_incentive
);
delete QueMemberByIdAndIncentive[_queMemberId][_incentive];
totalActiveOrders--;
activeOrderCountByIncentive[_incentive]--;
}
}
src/diamond/vault/interfaces/IPeerVault.sol
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.36;
/**
* @dev Minimal interface a source vault uses to call its
* destination peer's `mintFromPeer` entry inside the
* `moveBetweenVaults` flow. `decimals()` is sourced separately via
* `IERC20Metadata`.
*/
interface IPeerVault {
function mintFromPeer(
address _user,
uint256 _amount
)
external;
}
src/diamond/vault/interfaces/pending/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
},
"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.