Проверенный контрактТочноеMIT
MagnaForkV3Ethereum
Адрес0xffebb77fd84af0fcdfa25b390b326b3bd9564e63
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.24
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.24+commit.e11b9ed9
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- paris
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 440 554
- Транзакция создания
- 0xd094e89770…a929e923d4
13 файлов
- contracts/MagnaForkV3Ethereum.solглавный62,17 КБ
- @openzeppelin/contracts/access/Ownable.sol3,1 КБ
- @openzeppelin/contracts/interfaces/IERC1363.sol4,45 КБ
- @openzeppelin/contracts/interfaces/IERC165.sol193 Б
- @openzeppelin/contracts/interfaces/IERC20.sol182 Б
- @openzeppelin/contracts/token/ERC20/IERC20.sol2,78 КБ
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13,31 КБ
- @openzeppelin/contracts/utils/Context.sol963 Б
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4,77 КБ
- @openzeppelin/contracts/utils/StorageSlot.sol4,18 КБ
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol12,15 КБ
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 Б
contracts/MagnaForkV3Ethereum.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
interface IMagnaForkClosingFeeAdapter {
function closingFeeTerms() external view returns (uint256 amount, address recipient);
}
// Standalone Ethereum V3 staging contract. Existing deployments and state are separate.
// Invitations address one live fork. Closed links offer a separate global entry in the UI.
contract MagnaForkV3Ethereum is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
bytes32 public constant ROOT_FORK_AUTH_TYPEHASH =
keccak256(
"RootForkAuthorization(uint8 tierId,bytes32 linkId,uint64 deadline,uint256 chainId,address verifyingContract,address creator)"
);
bytes32 public constant ENTRY_INTENT_TYPEHASH =
keccak256(
"MagnaForkEntryIntent(address payer,uint8 tierId,uint8 mode,uint256 anchorForkId,address inviter,uint256 expectedTargetForkId,uint8 expectedLevel,uint8 expectedSlotIndex,uint256 chainId,address verifyingContract,uint256 nonce,uint256 deadline,bytes32 salt)"
);
bytes32 public constant ENTRY_INTENT_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 public constant ENTRY_INTENT_DOMAIN_NAME_HASH = keccak256("MagnaFork");
bytes32 public constant ENTRY_INTENT_DOMAIN_VERSION_HASH = keccak256("3");
enum ForkStatus {
ACTIVE,
SLEEP,
CLOSED
}
enum GiftMode {
INVITE,
GLOBAL,
ROOT
}
struct TierConfig {
uint256 giftAmount;
uint256 feeAmount;
uint256 netAmount;
uint256 payoutAmount;
}
struct InviteEntry {
uint8 tierId;
uint256 anchorForkId;
address inviter;
uint256 expectedTargetForkId;
uint8 expectedLevel;
uint8 expectedSlotIndex;
}
struct GlobalEntry {
uint8 tierId;
uint256 expectedForkId;
uint8 expectedLevel;
uint8 expectedSlotIndex;
}
struct EntryAuthorization {
uint256 nonce;
uint256 deadline;
bytes32 salt;
bytes signature;
}
struct Fork {
uint256 id;
uint8 tierId;
ForkStatus status;
address elder;
address[2] lvl2;
address[4] lvl4;
address[8] outer;
uint8 outerFilled;
uint64 lastInviteAt;
uint64 createdAt;
uint256 parentForkId;
uint256 rootForkId;
uint256 leftChildForkId;
uint256 rightChildForkId;
uint256 inviteCursor;
}
struct ForkPositionIds {
uint64[15] ids;
}
// Position identifiers remain sequential. Ownership already lives in the fork seat.
struct Position {
uint248 forkId;
uint8 location;
}
error InvalidTier();
error InvalidFork();
error InvalidPosition();
error ForkNotActive();
error ForkClosed();
error NoEmptySeat();
error InvalidFeeWallet();
error InvalidRootForkAuthorizer();
error InvalidRootLink();
error RootForkLinkExpired();
error RootForkLinkUsed();
error UnauthorizedRootForkLink();
error EntryTargetChanged(
uint256 expectedForkId,
uint256 actualForkId,
uint8 expectedLevel,
uint8 actualLevel,
uint8 expectedSlotIndex,
uint8 actualSlotIndex
);
error AdapterPaymentAlreadyUsed();
error EntryIntentExpired();
error InvalidAdapterPaymentId();
error InvalidEntryAdapter();
error InvalidEntryIntentSignature();
error InvalidEntryNonce(uint256 expectedNonce, uint256 actualNonce);
error InvalidParticipant();
error UnauthorizedEntryAdapter();
error GlobalQueueScanIncomplete();
error InvalidQueueKind();
error InvalidClosingFee();
event GiftRecorded(
uint256 indexed forkId,
uint8 indexed tierId,
address indexed user,
uint256 amount,
GiftMode mode,
address inviter,
uint8 slotIndex
);
event FeePaid(uint256 indexed forkId, uint8 indexed tierId, address indexed to, uint256 amount);
event GlobalAssigned(address indexed user, uint8 indexed tierId, uint256 indexed forkId, uint8 slotIndex);
event ForkSleep(uint256 indexed forkId, uint8 indexed tierId, uint64 at);
event ForkWake(uint256 indexed forkId, uint8 indexed tierId, address indexed byInviteUser, uint64 at);
event PayoutDone(uint256 indexed forkId, uint8 indexed tierId, address indexed elder, uint256 amount);
event ClosingFeePaid(uint256 indexed forkId, uint8 indexed tierId, address indexed elder, address recipient, uint256 amount);
event ForkSplit(uint256 indexed parentForkId, uint8 indexed tierId, uint256 forkA, uint256 forkB);
event FeeWalletUpdated(address indexed oldWallet, address indexed newWallet);
event RootForkAuthorizerUpdated(address indexed oldAuthorizer, address indexed newAuthorizer);
event RootForkCreated(uint256 indexed forkId, uint8 indexed tierId, address indexed creator, bytes32 linkId);
event PositionOpened(
uint256 indexed positionId,
uint256 indexed forkId,
uint8 indexed tierId,
address owner,
uint8 level,
uint8 slotIndex,
uint256 retainedAmount,
bool retainedInContract
);
event ReservePaid(
uint256 indexed forkId,
uint8 indexed tierId,
address indexed to,
uint8 level,
uint8 slotIndex,
uint256 amount
);
event AdapterPaymentConsumed(
bytes32 indexed paymentId,
address indexed payer,
address indexed participant,
uint256 amount
);
event EntryAdapterUpdated(address indexed oldAdapter, address indexed newAdapter);
event GlobalQueueMaintained(uint8 indexed tierId, uint8 indexed queueKind, uint256 processed, uint256 remaining);
event EntryIntentConsumed(
address indexed payer,
uint256 indexed nonce,
bytes32 indexed intentDigest
);
IERC20 public immutable usdt;
address public feeWallet;
address public rootForkAuthorizer;
address public entryAdapter;
uint256 public constant HOT_WINDOW = 24 hours;
uint256 public constant SLEEP_WINDOW = 72 hours;
uint256 private constant GLOBAL_QUEUE_SCAN_LIMIT = 32;
uint8 private constant GLOBAL_HEAT_NONE = 0;
uint8 private constant GLOBAL_HEAT_HOT = 1;
uint8 private constant GLOBAL_HEAT_WARM = 2;
mapping(uint8 => TierConfig) public tierConfigs;
mapping(bytes32 => bool) public usedRootLinkIds;
mapping(bytes32 => bool) public usedAdapterPaymentIds;
mapping(address => uint256) public entryNonces;
uint256 private _nextForkId = 1;
uint256 private _nextPositionId = 1;
mapping(uint256 => Fork) private _forks;
mapping(uint256 => ForkPositionIds) private _forkPositionIds;
mapping(uint256 => Position) private _positions;
mapping(uint256 => bool) private _positionsClosed;
mapping(uint8 => uint256[]) private _tierForkIds;
uint256[4] public globalCounter;
uint256[4] private _rootCompletionCursor;
uint256[4] private _hotCursor;
uint256[4] private _warmCursor;
mapping(uint8 => uint256[]) private _rootCompletionQueue;
mapping(uint8 => uint256[]) private _hotQueue;
mapping(uint8 => uint256[]) private _warmQueue;
mapping(uint256 => uint256) private _rootCompletionQueueIndex;
mapping(uint256 => uint256) private _hotQueueIndex;
mapping(uint256 => uint256) private _warmQueueIndex;
error InvalidToken();
error UnsupportedChain();
error UnexpectedTokenAmount();
error InvalidPageSize();
address public constant ETHEREUM_USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
constructor(
address usdt_,
address feeWallet_,
address rootForkAuthorizer_,
address entryAdapter_,
address owner_
) Ownable(owner_) {
if (block.chainid != 1 && block.chainid != 11155111 && block.chainid != 31337) revert UnsupportedChain();
if (usdt_.code.length == 0 || IERC20Metadata(usdt_).decimals() != 6) revert InvalidToken();
if (block.chainid == 1 && usdt_ != ETHEREUM_USDT) revert InvalidToken();
if (feeWallet_ == address(0) || feeWallet_ == address(this)) revert InvalidFeeWallet();
if (rootForkAuthorizer_ == address(0)) revert InvalidRootForkAuthorizer();
if (entryAdapter_ == address(0)) revert InvalidEntryAdapter();
usdt = IERC20(usdt_);
feeWallet = feeWallet_;
rootForkAuthorizer = rootForkAuthorizer_;
entryAdapter = entryAdapter_;
_setTierConfigs();
}
function updateFeeWallet(address newWallet) external onlyOwner {
if (newWallet == address(0) || newWallet == address(this)) revert InvalidFeeWallet();
address oldWallet = feeWallet;
feeWallet = newWallet;
emit FeeWalletUpdated(oldWallet, newWallet);
}
function updateRootForkAuthorizer(address newAuthorizer) external onlyOwner {
if (newAuthorizer == address(0)) revert InvalidRootForkAuthorizer();
address oldAuthorizer = rootForkAuthorizer;
rootForkAuthorizer = newAuthorizer;
emit RootForkAuthorizerUpdated(oldAuthorizer, newAuthorizer);
}
function updateEntryAdapter(address newAdapter) external onlyOwner {
if (newAdapter == address(0)) revert InvalidEntryAdapter();
address oldAdapter = entryAdapter;
entryAdapter = newAdapter;
emit EntryAdapterUpdated(oldAdapter, newAdapter);
}
function createRootFork(
uint8 tierId,
bytes32 linkId,
uint64 deadline,
bytes calldata signature
) external nonReentrant returns (uint256 forkId) {
_validateTier(tierId);
_consumeRootForkAuthorization(tierId, linkId, deadline, msg.sender, signature);
forkId = _createRootFork(tierId, msg.sender, linkId, false);
}
function createRootForkWithAuthorization(
uint8 tierId,
bytes32 linkId,
uint64 deadline,
bytes calldata signature,
address payer,
EntryAuthorization calldata entryAuthorization
) external nonReentrant returns (uint256 forkId) {
_validateTier(tierId);
bytes32 intentDigest = _getRootEntryIntentDigest(
tierId,
linkId,
payer,
entryAuthorization
);
_validateEntryIntent(payer, intentDigest, entryAuthorization);
_consumeRootForkAuthorization(tierId, linkId, deadline, payer, signature);
_consumeEntryAuthorization(
tierId,
payer,
intentDigest,
entryAuthorization
);
forkId = _createRootFork(tierId, payer, linkId, false);
}
function donateInvite(uint8 tierId, uint256 forkId, address inviter) external nonReentrant {
_validateTier(tierId);
Fork storage anchorFork = _forks[forkId];
if (anchorFork.id == 0 || anchorFork.tierId != tierId) revert InvalidFork();
uint256 targetForkId = _resolveInviteTargetForWrite(forkId);
Fork storage targetFork = _forks[targetForkId];
if (targetFork.tierId != tierId) revert InvalidFork();
_refreshForkStatus(targetForkId);
if (targetFork.status == ForkStatus.CLOSED) revert ForkClosed();
if (targetFork.status == ForkStatus.SLEEP) {
targetFork.status = ForkStatus.ACTIVE;
emit ForkWake(targetForkId, tierId, msg.sender, uint64(block.timestamp));
}
if (targetFork.status != ForkStatus.ACTIVE) revert ForkNotActive();
_processGift(targetForkId, msg.sender, GiftMode.INVITE, inviter);
targetFork.lastInviteAt = uint64(block.timestamp);
_syncGlobalCandidateQueues(targetForkId);
}
function donateInviteGuarded(
uint8 tierId,
uint256 forkId,
address inviter,
uint256 expectedTargetForkId,
uint8 expectedLevel,
uint8 expectedSlotIndex
) external nonReentrant {
_validateTier(tierId);
Fork storage anchorFork = _forks[forkId];
if (anchorFork.id == 0 || anchorFork.tierId != tierId) revert InvalidFork();
uint256 targetForkId = _resolveInviteTargetForWrite(forkId);
Fork storage targetFork = _forks[targetForkId];
if (targetFork.tierId != tierId) revert InvalidFork();
_refreshForkStatus(targetForkId);
if (targetFork.status == ForkStatus.CLOSED) revert ForkClosed();
if (targetFork.status == ForkStatus.SLEEP) {
targetFork.status = ForkStatus.ACTIVE;
emit ForkWake(targetForkId, tierId, msg.sender, uint64(block.timestamp));
}
if (targetFork.status != ForkStatus.ACTIVE) revert ForkNotActive();
_assertExpectedEntryTarget(
targetForkId,
targetFork,
expectedTargetForkId,
expectedLevel,
expectedSlotIndex
);
_processGift(targetForkId, msg.sender, GiftMode.INVITE, inviter);
targetFork.lastInviteAt = uint64(block.timestamp);
_syncGlobalCandidateQueues(targetForkId);
}
function donateGlobal(uint8 tierId) external nonReentrant {
_validateTier(tierId);
uint256 forkId = _selectGlobalFork(tierId);
if (forkId == 0) {
_createRootFork(tierId, msg.sender, bytes32(0), true);
return;
}
_processGift(forkId, msg.sender, GiftMode.GLOBAL, address(0));
_syncGlobalCandidateQueues(forkId);
}
function donateGlobalGuarded(
uint8 tierId,
uint256 expectedForkId,
uint8 expectedLevel,
uint8 expectedSlotIndex
) external nonReentrant {
_validateTier(tierId);
uint256 forkId = _selectGlobalFork(tierId);
if (forkId == 0) {
_assertExpectedRootEntry(expectedForkId, expectedLevel, expectedSlotIndex);
_createRootFork(tierId, msg.sender, bytes32(0), true);
return;
}
Fork storage fork = _forks[forkId];
_assertExpectedEntryTarget(forkId, fork, expectedForkId, expectedLevel, expectedSlotIndex);
_processGift(forkId, msg.sender, GiftMode.GLOBAL, address(0));
_syncGlobalCandidateQueues(forkId);
}
function donateInviteWithAuthorization(
InviteEntry calldata entry,
address payer,
EntryAuthorization calldata entryAuthorization
) external nonReentrant {
bytes32 intentDigest = _getInviteEntryIntentDigest(entry, payer, entryAuthorization);
_validateEntryIntent(payer, intentDigest, entryAuthorization);
uint256 targetForkId = _prepareGuardedInviteEntry(entry, payer);
_receiveAuthorizedEntryPayment(
entry.tierId,
payer,
intentDigest,
entryAuthorization
);
_completeFundedInviteEntry(targetForkId, payer, entry.inviter);
}
function donateGlobalWithAuthorization(
GlobalEntry calldata entry,
address payer,
EntryAuthorization calldata entryAuthorization
) external nonReentrant {
bytes32 intentDigest = _getGlobalEntryIntentDigest(entry, payer, entryAuthorization);
_validateEntryIntent(payer, intentDigest, entryAuthorization);
uint256 targetForkId = _prepareGuardedGlobalEntry(entry);
_receiveAuthorizedEntryPayment(
entry.tierId,
payer,
intentDigest,
entryAuthorization
);
_completeFundedGlobalEntry(entry.tierId, targetForkId, payer);
}
function donateInviteFromAdapter(
bytes32 paymentId,
address participant,
InviteEntry calldata entry
) external nonReentrant {
_validateAdapterPayment(paymentId, participant);
uint256 targetForkId = _prepareGuardedInviteEntry(entry, participant);
_receiveAdapterEntryPayment(paymentId, participant, entry.tierId);
_completeFundedInviteEntry(targetForkId, participant, entry.inviter);
}
function donateGlobalFromAdapter(
bytes32 paymentId,
address participant,
GlobalEntry calldata entry
) external nonReentrant {
_validateAdapterPayment(paymentId, participant);
uint256 targetForkId = _prepareGuardedGlobalEntry(entry);
_receiveAdapterEntryPayment(paymentId, participant, entry.tierId);
_completeFundedGlobalEntry(entry.tierId, targetForkId, participant);
}
/// @notice Honors an exact off-chain paid seat certified separately by the trusted adapter.
/// @dev No queue reselection or invitation heat refresh. Public GLOBAL entry stays queue-bound.
function donateReservedGlobalFromAdapter(
bytes32 paymentId,
address participant,
GlobalEntry calldata entry
) external nonReentrant {
_validateAdapterPayment(paymentId, participant);
_validateTier(entry.tierId);
Fork storage targetFork = _forks[entry.expectedForkId];
if (entry.expectedForkId == 0 || targetFork.id == 0 || targetFork.tierId != entry.tierId) revert InvalidFork();
if (targetFork.status == ForkStatus.CLOSED) revert ForkClosed();
_assertExpectedEntryTarget(entry.expectedForkId, targetFork, entry.expectedForkId, entry.expectedLevel, entry.expectedSlotIndex);
_recordGlobalSelection(entry.tierId, entry.expectedForkId);
_receiveAdapterEntryPayment(paymentId, participant, entry.tierId);
_completeFundedGlobalEntry(entry.tierId, entry.expectedForkId, participant);
}
/// @notice Uses the service's separately certified available GLOBAL seat without scanning other forks.
/// @dev The adapter certifies DB availability and queue preference; this contract checks current eligibility.
function donateSelectedGlobalFromAdapter(
bytes32 paymentId,
address participant,
GlobalEntry calldata entry
) external nonReentrant {
_validateAdapterPayment(paymentId, participant);
_validateTier(entry.tierId);
Fork storage targetFork = _forks[entry.expectedForkId];
if (entry.expectedForkId == 0 || targetFork.id == 0 || targetFork.tierId != entry.tierId) revert InvalidFork();
if (targetFork.status == ForkStatus.CLOSED) revert ForkClosed();
if (!_isRootCompletionCandidate(targetFork) && _globalCandidateHeat(targetFork) == GLOBAL_HEAT_NONE) revert ForkNotActive();
_assertExpectedEntryTarget(entry.expectedForkId, targetFork, entry.expectedForkId, entry.expectedLevel, entry.expectedSlotIndex);
_recordGlobalSelection(entry.tierId, entry.expectedForkId);
_receiveAdapterEntryPayment(paymentId, participant, entry.tierId);
_completeFundedGlobalEntry(entry.tierId, entry.expectedForkId, participant);
}
function getInviteEntryIntentDigest(
InviteEntry calldata entry,
address payer,
EntryAuthorization calldata entryAuthorization
) external view returns (bytes32) {
return _getInviteEntryIntentDigest(entry, payer, entryAuthorization);
}
function getGlobalEntryIntentDigest(
GlobalEntry calldata entry,
address payer,
EntryAuthorization calldata entryAuthorization
) external view returns (bytes32) {
return _getGlobalEntryIntentDigest(entry, payer, entryAuthorization);
}
function getRootForkEntryIntentDigest(
uint8 tierId,
bytes32 linkId,
address payer,
EntryAuthorization calldata entryAuthorization
) external view returns (bytes32) {
return _getRootEntryIntentDigest(tierId, linkId, payer, entryAuthorization);
}
function entryIntentDomainSeparator() public view returns (bytes32) {
return
keccak256(
abi.encode(
ENTRY_INTENT_DOMAIN_TYPEHASH,
ENTRY_INTENT_DOMAIN_NAME_HASH,
ENTRY_INTENT_DOMAIN_VERSION_HASH,
block.chainid,
address(this)
)
);
}
function supportsGlobalRootBootstrap() external pure returns (bool) {
return true;
}
function supportsClosedInviteRouting() external pure returns (bool) { return false; }
function supportsReservedGlobalEntry() external pure returns (bool) { return true; }
function supportsSelectedGlobalEntry() external pure returns (bool) { return true; }
function supportsBoundedGlobalEntry() external pure returns (bool) { return true; }
function supportsCappedClosingFee() external pure returns (bool) { return true; }
function supportsInviteTreeRouting() external pure returns (bool) {
return true;
}
function supportsReserveAutoSweep() external pure returns (bool) {
return true;
}
function supportsRootCompletionPriority() external pure returns (bool) {
return true;
}
function supportsDomainBoundRootAuthorization() external pure returns (bool) {
return true;
}
function supportsGuardedEntry() external pure returns (bool) {
return true;
}
function supportsPermitEntry() external pure returns (bool) {
return false;
}
function supportsPermitRootFork() external pure returns (bool) {
return false;
}
function protocolVersion() external pure returns (uint256) { return 3; }
function supportsAuthorizedEntry() external pure returns (bool) { return true; }
function supportsDepthIndependentInviteRouting() external pure returns (bool) { return true; }
function supportsAdapterEntry() external pure returns (bool) {
return true;
}
function supportsEntryIntentBinding() external pure returns (bool) {
return true;
}
function supportsCreatorBoundRootAuthorization() external pure returns (bool) {
return true;
}
function supportsIndexedGlobalRouting() external pure returns (bool) {
return true;
}
function supportsIndexedInviteRouting() external pure returns (bool) {
return true;
}
function resolveInviteTarget(uint256 forkId) external view returns (uint256 targetForkId) {
(bool found, uint256 resolvedForkId) = _tryResolveInviteTargetView(forkId);
if (!found) revert NoEmptySeat();
return resolvedForkId;
}
function getGlobalRoutingQueueLengths(
uint8 tierId
) external view returns (uint256 rootCompletion, uint256 hot, uint256 warm) {
_validateTier(tierId);
return (_rootCompletionQueue[tierId].length, _hotQueue[tierId].length, _warmQueue[tierId].length);
}
/// @notice Raw candidates in round-robin order. Read all pages at one block and evaluate current fork heat.
/// @dev Queue 0 is root completion, 1 HOT, 2 WARM. Aged HOT entries can currently be WARM or SLEEP.
function getGlobalRoutingQueuePage(uint8 tierId, uint8 queueKind, uint256 offset, uint256 limit)
external view returns (uint256[] memory ids, uint256 total, uint256 cursor, uint256 counter)
{
_validateTier(tierId);
if (limit == 0 || limit > 256) revert InvalidPageSize();
uint256[] storage queue = _globalQueue(tierId, queueKind);
total = queue.length;
cursor = queueKind == 0 ? _rootCompletionCursor[tierId] : queueKind == 1 ? _hotCursor[tierId] : _warmCursor[tierId];
counter = globalCounter[tierId];
if (offset >= total) return (new uint256[](0), total, cursor, counter);
uint256 count = total - offset;
if (count > limit) count = limit;
ids = new uint256[](count);
uint256 start = cursor % total;
for (uint256 i; i < count; ++i) ids[i] = queue[addmod(start, offset + i, total)];
}
/// @notice Optional bounded maintenance paid by its caller, never by a participant's entry.
/// @dev Offset is physical (not round-robin); removed slots are replaced by the last queue element.
function maintainGlobalQueue(uint8 tierId, uint8 queueKind, uint256 offset, uint256 limit)
external nonReentrant returns (uint256 processed, uint256 remaining)
{
_validateTier(tierId);
if (limit == 0 || limit > GLOBAL_QUEUE_SCAN_LIMIT) revert InvalidPageSize();
uint256[] storage queue = _globalQueue(tierId, queueKind);
while (processed < limit && offset < queue.length) {
uint256 forkId = queue[offset];
_syncGlobalCandidateQueues(forkId);
processed += 1;
if (offset < queue.length && queue[offset] == forkId) offset += 1;
}
remaining = queue.length;
emit GlobalQueueMaintained(tierId, queueKind, processed, remaining);
}
function _globalQueue(uint8 tierId, uint8 queueKind) internal view returns (uint256[] storage queue) {
if (queueKind > 2) revert InvalidQueueKind();
return queueKind == 0 ? _rootCompletionQueue[tierId] : queueKind == 1 ? _hotQueue[tierId] : _warmQueue[tierId];
}
/// @notice Bounded alternative to the legacy full-array getter.
function getTierForkIdsPage(uint8 tierId, uint256 offset, uint256 limit) external view returns (uint256[] memory ids, uint256 total) {
_validateTier(tierId);
if (limit == 0 || limit > 256) revert InvalidPageSize();
uint256[] storage all = _tierForkIds[tierId];
total = all.length;
if (offset >= total) return (new uint256[](0), total);
uint256 count = total - offset;
if (count > limit) count = limit;
ids = new uint256[](count);
for (uint256 i; i < count; ++i) ids[i] = all[offset + i];
}
function previewGlobalEntry(
uint8 tierId
)
external
view
returns (uint256 forkId, uint8 level, uint8 slotIndex, bool createsRootFork)
{
_validateTier(tierId);
forkId = _selectGlobalForkView(tierId);
if (forkId == 0) {
return (0, 0, 0, true);
}
Fork storage fork = _forks[forkId];
(level, slotIndex) = _nextOpenSlot(fork);
return (forkId, level, slotIndex, false);
}
function previewSelectedGlobalEntry(uint8 tierId, uint256 forkId)
external view returns (uint8 level, uint8 slotIndex)
{
_validateTier(tierId);
Fork storage fork = _forks[forkId];
if (forkId == 0 || fork.id == 0 || fork.tierId != tierId) revert InvalidFork();
if (fork.status == ForkStatus.CLOSED) revert ForkClosed();
if (!_isRootCompletionCandidate(fork) && _globalCandidateHeat(fork) == GLOBAL_HEAT_NONE) revert ForkNotActive();
return _nextOpenSlot(fork);
}
function previewInviteEntry(
uint8 tierId,
uint256 forkId
) external view returns (uint256 targetForkId, uint8 level, uint8 slotIndex) {
_validateTier(tierId);
Fork storage anchorFork = _forks[forkId];
if (anchorFork.id == 0 || anchorFork.tierId != tierId) revert InvalidFork();
(bool found, uint256 resolvedForkId) = _tryResolveInviteTargetView(forkId);
if (!found) revert NoEmptySeat();
Fork storage targetFork = _forks[resolvedForkId];
if (targetFork.tierId != tierId) revert InvalidFork();
(level, slotIndex) = _nextOpenSlot(targetFork);
return (resolvedForkId, level, slotIndex);
}
function getTierForkIds(uint8 tierId) external view returns (uint256[] memory) {
_validateTier(tierId);
return _tierForkIds[tierId];
}
function getFork(
uint256 forkId
)
external
view
returns (
uint8 tierId,
ForkStatus status,
address elder,
address[2] memory lvl2,
address[4] memory lvl4,
uint8 outerFilled,
uint64 lastInviteAt
)
{
Fork storage fork = _forks[forkId];
if (fork.id == 0) revert InvalidFork();
return (fork.tierId, fork.status, fork.elder, fork.lvl2, fork.lvl4, fork.outerFilled, fork.lastInviteAt);
}
function getForkOuter(uint256 forkId) external view returns (address[8] memory) {
Fork storage fork = _forks[forkId];
if (fork.id == 0) revert InvalidFork();
return fork.outer;
}
function getForkTree(
uint256 forkId
)
external
view
returns (
uint256 parentForkId,
uint256 rootForkId,
uint256 leftChildForkId,
uint256 rightChildForkId,
uint256 inviteCursor
)
{
Fork storage fork = _forks[forkId];
if (fork.id == 0) revert InvalidFork();
return (fork.parentForkId, fork.rootForkId, fork.leftChildForkId, fork.rightChildForkId, fork.inviteCursor);
}
function getForkPositionIds(
uint256 forkId
)
external
view
returns (
uint256 elder,
uint256[2] memory lvl2,
uint256[4] memory lvl4,
uint256[8] memory outer
)
{
Fork storage fork = _forks[forkId];
if (fork.id == 0) revert InvalidFork();
ForkPositionIds storage positions = _forkPositionIds[forkId];
elder = positions.ids[0];
for (uint8 i = 0; i < 2; i++) lvl2[i] = positions.ids[1 + i];
for (uint8 i = 0; i < 4; i++) lvl4[i] = positions.ids[3 + i];
for (uint8 i = 0; i < 8; i++) outer[i] = positions.ids[7 + i];
}
function getPosition(
uint256 positionId
)
external
view
returns (
uint256 forkId,
address owner,
uint8 level,
uint8 slotIndex,
uint256 retainedAmount,
bool retainedInContract,
bool active
)
{
Position storage position = _positions[positionId];
forkId = position.forkId;
if (forkId == 0) revert InvalidPosition();
Fork storage fork = _forks[forkId];
uint8 location = position.location;
if (location == 0) {
owner = fork.elder;
} else if (location < 3) {
level = 1;
slotIndex = location - 1;
owner = fork.lvl2[slotIndex];
} else if (location < 7) {
level = 2;
slotIndex = location - 3;
owner = fork.lvl4[slotIndex];
} else {
level = 3;
slotIndex = location - 7;
owner = fork.outer[slotIndex];
}
active = !_positionsClosed[forkId];
retainedInContract = active && level == 3;
retainedAmount = retainedInContract ? tierConfigs[fork.tierId].netAmount : 0;
}
function _getInviteEntryIntentDigest(
InviteEntry calldata entry,
address payer,
EntryAuthorization calldata entryAuthorization
) internal view returns (bytes32) {
return
_hashEntryIntent(
keccak256(
abi.encode(
ENTRY_INTENT_TYPEHASH,
payer,
entry.tierId,
uint8(GiftMode.INVITE),
entry.anchorForkId,
entry.inviter,
entry.expectedTargetForkId,
entry.expectedLevel,
entry.expectedSlotIndex,
block.chainid,
address(this),
entryAuthorization.nonce,
entryAuthorization.deadline,
entryAuthorization.salt
)
)
);
}
function _getGlobalEntryIntentDigest(
GlobalEntry calldata entry,
address payer,
EntryAuthorization calldata entryAuthorization
) internal view returns (bytes32) {
return
_hashEntryIntent(
keccak256(
abi.encode(
ENTRY_INTENT_TYPEHASH,
payer,
entry.tierId,
uint8(GiftMode.GLOBAL),
uint256(0),
address(0),
entry.expectedForkId,
entry.expectedLevel,
entry.expectedSlotIndex,
block.chainid,
address(this),
entryAuthorization.nonce,
entryAuthorization.deadline,
entryAuthorization.salt
)
)
);
}
function _getRootEntryIntentDigest(
uint8 tierId,
bytes32 linkId,
address payer,
EntryAuthorization calldata entryAuthorization
) internal view returns (bytes32) {
return
_hashEntryIntent(
keccak256(
abi.encode(
ENTRY_INTENT_TYPEHASH,
payer,
tierId,
uint8(GiftMode.ROOT),
uint256(linkId),
address(0),
uint256(0),
uint8(0),
uint8(0),
block.chainid,
address(this),
entryAuthorization.nonce,
entryAuthorization.deadline,
entryAuthorization.salt
)
)
);
}
function _validateEntryIntent(
address payer,
bytes32 intentDigest,
EntryAuthorization calldata entryAuthorization
) internal view {
if (payer == address(0)) revert InvalidParticipant();
if (block.timestamp > entryAuthorization.deadline) revert EntryIntentExpired();
uint256 expectedNonce = entryNonces[payer];
if (entryAuthorization.nonce != expectedNonce) {
revert InvalidEntryNonce(expectedNonce, entryAuthorization.nonce);
}
(address recovered, , ) = ECDSA.tryRecoverCalldata(
intentDigest,
entryAuthorization.signature
);
if (recovered != payer) {
revert InvalidEntryIntentSignature();
}
}
function _hashEntryIntent(bytes32 structHash) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", entryIntentDomainSeparator(), structHash));
}
function _prepareGuardedInviteEntry(
InviteEntry calldata entry,
address participant
) internal returns (uint256 targetForkId) {
_validateTier(entry.tierId);
Fork storage anchorFork = _forks[entry.anchorForkId];
if (anchorFork.id == 0 || anchorFork.tierId != entry.tierId) revert InvalidFork();
targetForkId = _resolveInviteTargetForWrite(entry.anchorForkId);
Fork storage targetFork = _forks[targetForkId];
if (targetFork.tierId != entry.tierId) revert InvalidFork();
_refreshForkStatus(targetForkId);
if (targetFork.status == ForkStatus.CLOSED) revert ForkClosed();
if (targetFork.status == ForkStatus.SLEEP) {
targetFork.status = ForkStatus.ACTIVE;
emit ForkWake(targetForkId, entry.tierId, participant, uint64(block.timestamp));
}
if (targetFork.status != ForkStatus.ACTIVE) revert ForkNotActive();
_assertExpectedEntryTarget(
targetForkId,
targetFork,
entry.expectedTargetForkId,
entry.expectedLevel,
entry.expectedSlotIndex
);
}
function _prepareGuardedGlobalEntry(
GlobalEntry calldata entry
) internal returns (uint256 targetForkId) {
_validateTier(entry.tierId);
targetForkId = _selectGlobalFork(entry.tierId);
if (targetForkId == 0) {
_assertExpectedRootEntry(
entry.expectedForkId,
entry.expectedLevel,
entry.expectedSlotIndex
);
return 0;
}
Fork storage targetFork = _forks[targetForkId];
_assertExpectedEntryTarget(
targetForkId,
targetFork,
entry.expectedForkId,
entry.expectedLevel,
entry.expectedSlotIndex
);
}
function _receiveAuthorizedEntryPayment(
uint8 tierId,
address payer,
bytes32 intentDigest,
EntryAuthorization calldata entryAuthorization
) internal {
uint256 giftAmount = _consumeEntryAuthorization(
tierId,
payer,
intentDigest,
entryAuthorization
);
_receiveExactPayment(payer, giftAmount);
}
function _consumeEntryAuthorization(
uint8 tierId,
address payer,
bytes32 intentDigest,
EntryAuthorization calldata entryAuthorization
) internal returns (uint256 giftAmount) {
entryNonces[payer] = entryAuthorization.nonce + 1;
giftAmount = tierConfigs[tierId].giftAmount;
emit EntryIntentConsumed(payer, entryAuthorization.nonce, intentDigest);
}
function _validateAdapterPayment(bytes32 paymentId, address participant) internal view {
if (msg.sender != entryAdapter) revert UnauthorizedEntryAdapter();
if (paymentId == bytes32(0)) revert InvalidAdapterPaymentId();
if (participant == address(0) || participant == address(this)) revert InvalidParticipant();
if (usedAdapterPaymentIds[paymentId]) revert AdapterPaymentAlreadyUsed();
}
function _receiveAdapterEntryPayment(
bytes32 paymentId,
address participant,
uint8 tierId
) internal {
TierConfig memory cfg = tierConfigs[tierId];
usedAdapterPaymentIds[paymentId] = true;
_receiveExactPayment(msg.sender, cfg.giftAmount);
emit AdapterPaymentConsumed(paymentId, msg.sender, participant, cfg.giftAmount);
}
function _completeFundedInviteEntry(
uint256 targetForkId,
address participant,
address inviter
) internal {
Fork storage targetFork = _forks[targetForkId];
_processFundedGift(targetForkId, participant, GiftMode.INVITE, inviter);
targetFork.lastInviteAt = uint64(block.timestamp);
_syncGlobalCandidateQueues(targetForkId);
}
function _completeFundedGlobalEntry(
uint8 tierId,
uint256 targetForkId,
address participant
) internal {
if (targetForkId == 0) {
_createFundedRootFork(tierId, participant, bytes32(0), true);
return;
}
_processFundedGift(targetForkId, participant, GiftMode.GLOBAL, address(0));
_syncGlobalCandidateQueues(targetForkId);
}
function _receiveExactPayment(address payer, uint256 amount) internal {
uint256 beforeBalance = usdt.balanceOf(address(this));
usdt.safeTransferFrom(payer, address(this), amount);
if (usdt.balanceOf(address(this)) != beforeBalance + amount) revert UnexpectedTokenAmount();
}
function _transferExact(address to, uint256 amount) internal {
uint256 beforeRecipient = usdt.balanceOf(to);
uint256 beforeBalance = usdt.balanceOf(address(this));
usdt.safeTransfer(to, amount);
if (usdt.balanceOf(to) != beforeRecipient + amount || usdt.balanceOf(address(this)) + amount != beforeBalance) {
revert UnexpectedTokenAmount();
}
}
function _setTierConfigs() internal {
tierConfigs[0] = TierConfig({
giftAmount: 15_000_000,
feeAmount: 1_050_000,
netAmount: 13_950_000,
payoutAmount: 111_600_000
});
tierConfigs[1] = TierConfig({
giftAmount: 50_000_000,
feeAmount: 3_500_000,
netAmount: 46_500_000,
payoutAmount: 372_000_000
});
tierConfigs[2] = TierConfig({
giftAmount: 500_000_000,
feeAmount: 35_000_000,
netAmount: 465_000_000,
payoutAmount: 3_720_000_000
});
}
function _validateTier(uint8 tierId) internal pure {
if (tierId > 2) revert InvalidTier();
}
function _refreshForkStatus(uint256 forkId) internal {
Fork storage fork = _forks[forkId];
if (fork.status != ForkStatus.ACTIVE) return;
if (_isRootCompletionCandidate(fork)) return;
if (block.timestamp > uint256(fork.lastInviteAt) + SLEEP_WINDOW) {
fork.status = ForkStatus.SLEEP;
_removeGlobalActiveCandidate(forkId);
emit ForkSleep(forkId, fork.tierId, uint64(block.timestamp));
}
}
function _selectGlobalFork(uint8 tierId) internal returns (uint256) {
uint256 selected = _selectGlobalForkView(tierId);
_recordGlobalSelection(tierId, selected);
return selected;
}
function _recordGlobalSelection(uint8 tierId, uint256 selected) internal {
if (selected != 0 && _isRootCompletionCandidate(_forks[selected])) {
_rootCompletionCursor[tierId] = _rootCompletionQueueIndex[selected];
} else {
globalCounter[tierId] += 1;
if (selected != 0) {
uint8 heat = _syncGlobalCandidateQueues(selected);
if (heat == GLOBAL_HEAT_HOT) _hotCursor[tierId] = _hotQueueIndex[selected];
else if (heat == GLOBAL_HEAT_WARM) _warmCursor[tierId] = _warmQueueIndex[selected];
}
}
}
function _selectGlobalForkView(uint8 tierId) internal view returns (uint256) {
uint256 selected = _selectGlobalForkBoundedView(tierId);
// A bounded scan is not evidence that the entire pool is empty. Never
// create a root merely because live candidates lie beyond its first page.
if (selected == 0 && (_rootCompletionQueue[tierId].length > GLOBAL_QUEUE_SCAN_LIMIT
|| _hotQueue[tierId].length > GLOBAL_QUEUE_SCAN_LIMIT || _warmQueue[tierId].length > GLOBAL_QUEUE_SCAN_LIMIT)) {
revert GlobalQueueScanIncomplete();
}
return selected;
}
function _selectGlobalForkBoundedView(uint8 tierId) internal view returns (uint256) {
uint256 rootCompletionForkId = _pickRootCompletionByRoundRobinView(tierId);
if (rootCompletionForkId != 0) {
return rootCompletionForkId;
}
uint256 bucket = globalCounter[tierId] % 4;
bool preferHot = bucket < 3;
if (preferHot) {
uint256 hotForkId = _pickGlobalHeatByRoundRobinView(tierId, GLOBAL_HEAT_HOT);
if (hotForkId != 0) return hotForkId;
return _pickGlobalHeatByRoundRobinView(tierId, GLOBAL_HEAT_WARM);
}
uint256 warmForkId = _pickGlobalHeatByRoundRobinView(tierId, GLOBAL_HEAT_WARM);
if (warmForkId != 0) return warmForkId;
uint256 fallbackHotForkId = _pickGlobalHeatByRoundRobinView(tierId, GLOBAL_HEAT_HOT);
if (fallbackHotForkId != 0) return fallbackHotForkId;
return _pickGlobalHeatByRoundRobinView(tierId, GLOBAL_HEAT_WARM);
}
function _createRootFork(
uint8 tierId,
address creator,
bytes32 linkId,
bool fromGlobal
) internal returns (uint256 forkId) {
TierConfig memory cfg = tierConfigs[tierId];
_receiveExactPayment(creator, cfg.giftAmount);
_transferExact(feeWallet, cfg.giftAmount);
return _recordRootFork(tierId, creator, linkId, fromGlobal);
}
function _createFundedRootFork(
uint8 tierId,
address creator,
bytes32 linkId,
bool fromGlobal
) internal returns (uint256 forkId) {
TierConfig memory cfg = tierConfigs[tierId];
_transferExact(feeWallet, cfg.giftAmount);
return _recordRootFork(tierId, creator, linkId, fromGlobal);
}
function _recordRootFork(
uint8 tierId,
address creator,
bytes32 linkId,
bool fromGlobal
) internal returns (uint256 forkId) {
TierConfig memory cfg = tierConfigs[tierId];
forkId = _nextForkId++;
Fork storage fork = _forks[forkId];
fork.id = forkId;
fork.tierId = tierId;
fork.status = ForkStatus.ACTIVE;
fork.lastInviteAt = uint64(block.timestamp);
fork.createdAt = uint64(block.timestamp);
fork.rootForkId = forkId;
_openPosition(fork, creator, 0, 0, 0, false);
_tierForkIds[tierId].push(forkId);
_syncGlobalCandidateQueues(forkId);
emit RootForkCreated(forkId, tierId, creator, linkId);
emit FeePaid(forkId, tierId, feeWallet, cfg.feeAmount);
emit ReservePaid(forkId, tierId, feeWallet, 0, 0, cfg.netAmount);
emit GiftRecorded(forkId, tierId, creator, cfg.giftAmount, GiftMode.ROOT, address(0), 0);
if (fromGlobal) {
emit GlobalAssigned(creator, tierId, forkId, 0);
}
}
function _pickRootCompletionByRoundRobinView(uint8 tierId) internal view returns (uint256) {
uint256 length = _rootCompletionQueue[tierId].length;
if (length == 0) {
return 0;
}
uint256 cursor = _rootCompletionCursor[tierId];
uint256 limit = length < GLOBAL_QUEUE_SCAN_LIMIT ? length : GLOBAL_QUEUE_SCAN_LIMIT;
for (uint256 probes = 0; probes < limit; probes++) {
uint256 forkId = _rootCompletionQueue[tierId][(cursor + probes) % length];
if (_isRootCompletionCandidate(_forks[forkId])) {
return forkId;
}
}
return 0;
}
function _pickGlobalHeatByRoundRobinView(uint8 tierId, uint8 expectedHeat) internal view returns (uint256) {
uint256 cursor = expectedHeat == GLOBAL_HEAT_HOT ? _hotCursor[tierId] : _warmCursor[tierId];
uint256 forkId = _pickGlobalHeatFromQueueView(
expectedHeat == GLOBAL_HEAT_HOT ? _hotQueue[tierId] : _warmQueue[tierId],
cursor,
expectedHeat
);
if (forkId != 0 || expectedHeat == GLOBAL_HEAT_HOT) {
return forkId;
}
return _pickGlobalHeatFromQueueView(_hotQueue[tierId], _hotCursor[tierId], GLOBAL_HEAT_WARM);
}
function _pickGlobalHeatFromQueueView(
uint256[] storage queue,
uint256 cursor,
uint8 expectedHeat
) internal view returns (uint256) {
uint256 length = queue.length;
uint256 limit = length < GLOBAL_QUEUE_SCAN_LIMIT ? length : GLOBAL_QUEUE_SCAN_LIMIT;
for (uint256 probes = 0; probes < limit; probes++) {
uint256 forkId = queue[(cursor + probes) % length];
if (_globalCandidateHeat(_forks[forkId]) == expectedHeat) {
return forkId;
}
}
return 0;
}
function _syncGlobalCandidateQueues(uint256 forkId) internal returns (uint8 heat) {
Fork storage fork = _forks[forkId];
if (fork.id == 0) {
_removeGlobalCandidate(forkId);
return GLOBAL_HEAT_NONE;
}
if (_isRootCompletionCandidate(fork)) {
_removeGlobalActiveCandidate(forkId);
_addToQueue(_rootCompletionQueue[fork.tierId], _rootCompletionQueueIndex, forkId);
return GLOBAL_HEAT_NONE;
}
_removeFromQueue(_rootCompletionQueue[fork.tierId], _rootCompletionQueueIndex, forkId);
_refreshForkStatus(forkId);
heat = _globalCandidateHeat(fork);
if (heat == GLOBAL_HEAT_HOT) {
_removeFromQueue(_warmQueue[fork.tierId], _warmQueueIndex, forkId);
_addToQueue(_hotQueue[fork.tierId], _hotQueueIndex, forkId);
} else if (heat == GLOBAL_HEAT_WARM) {
_removeFromQueue(_hotQueue[fork.tierId], _hotQueueIndex, forkId);
_addToQueue(_warmQueue[fork.tierId], _warmQueueIndex, forkId);
} else {
_removeGlobalActiveCandidate(forkId);
}
}
function _globalCandidateHeat(Fork storage fork) internal view returns (uint8) {
if (fork.id == 0 || fork.status != ForkStatus.ACTIVE || !_hasOpenSeat(fork)) {
return GLOBAL_HEAT_NONE;
}
if (_isRootCompletionCandidate(fork)) {
return GLOBAL_HEAT_NONE;
}
uint256 age = block.timestamp - uint256(fork.lastInviteAt);
if (age <= HOT_WINDOW) {
return GLOBAL_HEAT_HOT;
}
if (age <= SLEEP_WINDOW) {
return GLOBAL_HEAT_WARM;
}
return GLOBAL_HEAT_NONE;
}
function _removeGlobalCandidate(uint256 forkId) internal {
Fork storage fork = _forks[forkId];
uint8 tierId = fork.tierId;
_removeFromQueue(_rootCompletionQueue[tierId], _rootCompletionQueueIndex, forkId);
_removeFromQueue(_hotQueue[tierId], _hotQueueIndex, forkId);
_removeFromQueue(_warmQueue[tierId], _warmQueueIndex, forkId);
}
function _removeGlobalActiveCandidate(uint256 forkId) internal {
Fork storage fork = _forks[forkId];
uint8 tierId = fork.tierId;
_removeFromQueue(_hotQueue[tierId], _hotQueueIndex, forkId);
_removeFromQueue(_warmQueue[tierId], _warmQueueIndex, forkId);
}
function _addToQueue(
uint256[] storage queue,
mapping(uint256 => uint256) storage queueIndex,
uint256 forkId
) internal {
if (queueIndex[forkId] != 0) {
return;
}
queue.push(forkId);
queueIndex[forkId] = queue.length;
}
function _removeFromQueue(
uint256[] storage queue,
mapping(uint256 => uint256) storage queueIndex,
uint256 forkId
) internal {
uint256 storedIndex = queueIndex[forkId];
if (storedIndex == 0) {
return;
}
uint256 index = storedIndex - 1;
uint256 lastIndex = queue.length - 1;
if (index != lastIndex) {
uint256 movedForkId = queue[lastIndex];
queue[index] = movedForkId;
queueIndex[movedForkId] = storedIndex;
}
queue.pop();
delete queueIndex[forkId];
}
function _resolveInviteTargetForWrite(uint256 forkId) internal view returns (uint256) {
(bool found, uint256 targetForkId) = _tryResolveInviteTargetForWrite(forkId);
if (!found) revert NoEmptySeat();
return targetForkId;
}
function _tryResolveInviteTargetView(uint256 forkId) internal view returns (bool found, uint256 targetForkId) {
Fork storage fork = _forks[forkId];
if (fork.id == 0) revert InvalidFork();
if (fork.status != ForkStatus.CLOSED) return (_hasOpenSeat(fork), forkId);
return (false, 0);
}
function _tryResolveInviteTargetForWrite(uint256 forkId) internal view returns (bool found, uint256 targetForkId) {
return _tryResolveInviteTargetView(forkId);
}
function _assertExpectedRootEntry(
uint256 expectedForkId,
uint8 expectedLevel,
uint8 expectedSlotIndex
) internal pure {
if (expectedForkId != 0 || expectedLevel != 0 || expectedSlotIndex != 0) {
revert EntryTargetChanged(expectedForkId, 0, expectedLevel, 0, expectedSlotIndex, 0);
}
}
function _assertExpectedEntryTarget(
uint256 actualForkId,
Fork storage fork,
uint256 expectedForkId,
uint8 expectedLevel,
uint8 expectedSlotIndex
) internal view {
(uint8 actualLevel, uint8 actualSlotIndex) = _nextOpenSlot(fork);
if (
expectedForkId != actualForkId ||
expectedLevel != actualLevel ||
expectedSlotIndex != actualSlotIndex
) {
revert EntryTargetChanged(
expectedForkId,
actualForkId,
expectedLevel,
actualLevel,
expectedSlotIndex,
actualSlotIndex
);
}
}
function _processGift(uint256 forkId, address donor, GiftMode mode, address inviter) internal {
_receiveExactPayment(donor, tierConfigs[_forks[forkId].tierId].giftAmount);
_processFundedGift(forkId, donor, mode, inviter);
}
function _processFundedGift(
uint256 forkId,
address donor,
GiftMode mode,
address inviter
) internal {
Fork storage fork = _forks[forkId];
if (fork.status == ForkStatus.CLOSED) revert ForkClosed();
if (!_hasOpenSeat(fork)) revert NoEmptySeat();
TierConfig memory cfg = tierConfigs[fork.tierId];
(uint8 level, uint8 slotIndex) = _nextOpenSlot(fork);
bool retainedInContract = level == 3;
if (retainedInContract) {
_transferExact(feeWallet, cfg.feeAmount);
} else {
_transferExact(feeWallet, cfg.giftAmount);
}
_recordFundedGift(forkId, donor, mode, inviter, level, slotIndex, retainedInContract);
}
function _recordFundedGift(
uint256 forkId,
address donor,
GiftMode mode,
address inviter,
uint8 level,
uint8 slotIndex,
bool retainedInContract
) internal {
Fork storage fork = _forks[forkId];
TierConfig memory cfg = tierConfigs[fork.tierId];
_openPosition(fork, donor, level, slotIndex, retainedInContract ? cfg.netAmount : 0, retainedInContract);
if (level == 3) {
fork.outerFilled += 1;
}
emit FeePaid(forkId, fork.tierId, feeWallet, cfg.feeAmount);
if (!retainedInContract) {
emit ReservePaid(forkId, fork.tierId, feeWallet, level, slotIndex, cfg.netAmount);
}
emit GiftRecorded(forkId, fork.tierId, donor, cfg.giftAmount, mode, inviter, slotIndex);
if (mode == GiftMode.GLOBAL) {
emit GlobalAssigned(donor, fork.tierId, forkId, slotIndex);
}
if (_isSettledForkReadyForSplit(fork)) {
_settleAndSplit(forkId);
}
}
function _nextOpenSlot(Fork storage fork) internal view returns (uint8 level, uint8 slotIndex) {
if (fork.elder == address(0)) {
return (0, 0);
}
for (uint8 i = 0; i < 2; i++) {
if (fork.lvl2[i] == address(0)) {
return (1, i);
}
}
for (uint8 i = 0; i < 4; i++) {
if (fork.lvl4[i] == address(0)) {
return (2, i);
}
}
if (fork.outerFilled >= 8) revert NoEmptySeat();
for (uint8 i = 0; i < 8; i++) {
if (fork.outer[i] == address(0)) {
return (3, i);
}
}
revert NoEmptySeat();
}
function _hasOpenSeat(Fork storage fork) internal view returns (bool) {
if (fork.elder == address(0)) {
return true;
}
for (uint8 i = 0; i < 2; i++) {
if (fork.lvl2[i] == address(0)) {
return true;
}
}
for (uint8 i = 0; i < 4; i++) {
if (fork.lvl4[i] == address(0)) {
return true;
}
}
return fork.outerFilled < 8;
}
function _isRootCompletionCandidate(Fork storage fork) internal view returns (bool) {
return
fork.status != ForkStatus.CLOSED &&
fork.parentForkId == 0 &&
fork.rootForkId == fork.id &&
_hasOpenSeat(fork);
}
function _isSettledForkReadyForSplit(Fork storage fork) internal view returns (bool) {
if (fork.elder == address(0) || fork.outerFilled != 8) {
return false;
}
for (uint8 i = 0; i < 2; i++) {
if (fork.lvl2[i] == address(0)) {
return false;
}
}
for (uint8 i = 0; i < 4; i++) {
if (fork.lvl4[i] == address(0)) {
return false;
}
}
return true;
}
function _settleAndSplit(uint256 forkId) internal {
Fork storage parent = _forks[forkId];
// A previously paid GLOBAL reservation may settle after its fork has slept.
if (parent.status == ForkStatus.CLOSED) revert ForkClosed();
TierConfig memory cfg = tierConfigs[parent.tierId];
_closePositionsForSplit(forkId);
uint256 closingFee;
address recipient;
if (msg.sender == entryAdapter && msg.sender.code.length != 0) {
(closingFee, recipient) = IMagnaForkClosingFeeAdapter(msg.sender).closingFeeTerms();
if (closingFee > cfg.payoutAmount - 7 * cfg.giftAmount) revert InvalidClosingFee();
}
_transferExact(parent.elder, cfg.payoutAmount - closingFee);
emit PayoutDone(forkId, parent.tierId, parent.elder, cfg.payoutAmount - closingFee);
if (closingFee != 0) {
if (recipient == address(0) || recipient == address(this) || recipient == address(usdt)) revert InvalidClosingFee();
_transferExact(recipient, closingFee);
emit ClosingFeePaid(forkId, parent.tierId, parent.elder, recipient, closingFee);
}
uint256 forkA = _createChildFork(parent, true);
uint256 forkB = _createChildFork(parent, false);
parent.leftChildForkId = forkA;
parent.rightChildForkId = forkB;
parent.status = ForkStatus.CLOSED;
_removeGlobalCandidate(forkId);
emit ForkSplit(forkId, parent.tierId, forkA, forkB);
}
function _createChildFork(Fork storage parent, bool isLeft) internal returns (uint256 newForkId) {
newForkId = _nextForkId++;
Fork storage child = _forks[newForkId];
child.id = newForkId;
child.tierId = parent.tierId;
child.status = ForkStatus.ACTIVE;
child.createdAt = uint64(block.timestamp);
child.lastInviteAt = uint64(block.timestamp);
child.parentForkId = parent.id;
child.rootForkId = parent.rootForkId == 0 ? parent.id : parent.rootForkId;
if (isLeft) {
_openPosition(child, parent.lvl2[0], 0, 0, 0, false);
_openPosition(child, parent.lvl4[0], 1, 0, 0, false);
_openPosition(child, parent.lvl4[1], 1, 1, 0, false);
_openPosition(child, parent.outer[0], 2, 0, 0, false);
_openPosition(child, parent.outer[1], 2, 1, 0, false);
_openPosition(child, parent.outer[2], 2, 2, 0, false);
_openPosition(child, parent.outer[3], 2, 3, 0, false);
} else {
_openPosition(child, parent.lvl2[1], 0, 0, 0, false);
_openPosition(child, parent.lvl4[2], 1, 0, 0, false);
_openPosition(child, parent.lvl4[3], 1, 1, 0, false);
_openPosition(child, parent.outer[4], 2, 0, 0, false);
_openPosition(child, parent.outer[5], 2, 1, 0, false);
_openPosition(child, parent.outer[6], 2, 2, 0, false);
_openPosition(child, parent.outer[7], 2, 3, 0, false);
}
_tierForkIds[parent.tierId].push(newForkId);
_syncGlobalCandidateQueues(newForkId);
}
function _openPosition(
Fork storage fork,
address owner,
uint8 level,
uint8 slotIndex,
uint256 retainedAmount,
bool retainedInContract
) internal returns (uint256 positionId) {
if (owner == address(0)) revert NoEmptySeat();
positionId = _nextPositionId++;
// Explicit capacity bounds protect packed identifiers from truncation.
if (positionId > type(uint64).max || fork.id > type(uint248).max) revert InvalidPosition();
uint8 location = level == 0 ? 0 : level == 1 ? 1 + slotIndex : level == 2 ? 3 + slotIndex : 7 + slotIndex;
_positions[positionId] = Position({forkId: uint248(fork.id), location: location});
ForkPositionIds storage forkPositions = _forkPositionIds[fork.id];
forkPositions.ids[location] = uint64(positionId);
if (level == 0) {
fork.elder = owner;
} else if (level == 1) {
fork.lvl2[slotIndex] = owner;
} else if (level == 2) {
fork.lvl4[slotIndex] = owner;
} else {
fork.outer[slotIndex] = owner;
}
emit PositionOpened(
positionId,
fork.id,
fork.tierId,
owner,
level,
slotIndex,
retainedAmount,
retainedInContract
);
}
// One flag closes every position before the external payout transfer, as before.
function _closePositionsForSplit(uint256 forkId) internal {
_positionsClosed[forkId] = true;
}
function _consumeRootForkAuthorization(
uint8 tierId,
bytes32 linkId,
uint64 deadline,
address creator,
bytes calldata signature
) internal {
if (linkId == bytes32(0)) revert InvalidRootLink();
if (block.timestamp > uint256(deadline)) revert RootForkLinkExpired();
if (usedRootLinkIds[linkId]) revert RootForkLinkUsed();
bytes32 structHash =
keccak256(
abi.encode(
ROOT_FORK_AUTH_TYPEHASH,
tierId,
linkId,
deadline,
block.chainid,
address(this),
creator
)
);
bytes32 digest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", structHash));
address signer = ECDSA.recover(digest, signature);
if (signer != rootForkAuthorizer) revert UnauthorizedRootForkLink();
usedRootLinkIds[linkId] = true;
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* 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].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature is invalid.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
*
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
* formats. Returns (0,0,0) for invalid signatures.
*
* For 64-byte signatures, `v` is automatically normalized to 27 or 28.
* For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
*
* Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
*/
function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch mload(signature)
// - case 65: r,s,v signature (standard)
case 65 {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Variant of {parse} that takes a signature in calldata
*/
function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch signature.length
// - case 65: r,s,v signature (standard)
case 65 {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
r := calldataload(signature.offset)
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Настройки компилятораПоказать
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": []
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.