Verified contractExactMIT
EarthmetaStaking
Address0x16e802cd295047f91aa913ef33e89d3ae8fd6dc5
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,444,243
- Creation transaction
- 0x269171f785…a0f655fafb
30 files
- project/contracts/staking/EarthmetaStaking.solmain65.11 KB
- npm/@openzeppelin/[email protected]/access/AccessControlUpgradeable.sol8.28 KB
- npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol144 B
- npm/@openzeppelin/[email protected]/proxy/utils/UUPSUpgradeable.sol148 B
- npm/@openzeppelin/[email protected]/utils/ContextUpgradeable.sol1.22 KB
- npm/@openzeppelin/[email protected]/utils/PausableUpgradeable.sol3.68 KB
- npm/@openzeppelin/[email protected]/utils/introspection/ERC165Upgradeable.sol1.17 KB
- npm/@openzeppelin/[email protected]/access/IAccessControl.sol3.34 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol4.45 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC165.sol193 B
- npm/@openzeppelin/[email protected]/interfaces/IERC1967.sol637 B
- npm/@openzeppelin/[email protected]/interfaces/IERC20.sol182 B
- npm/@openzeppelin/[email protected]/interfaces/draft-IERC1822.sol882 B
- npm/@openzeppelin/[email protected]/proxy/ERC1967/ERC1967Utils.sol6.26 KB
- npm/@openzeppelin/[email protected]/proxy/beacon/IBeacon.sol473 B
- npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol9.28 KB
- npm/@openzeppelin/[email protected]/proxy/utils/UUPSUpgradeable.sol6.32 KB
- npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol2.78 KB
- npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol13.31 KB
- npm/@openzeppelin/[email protected]/utils/Address.sol6.8 KB
- npm/@openzeppelin/[email protected]/utils/Errors.sol896 B
- npm/@openzeppelin/[email protected]/utils/LowLevelCall.sol5.55 KB
- npm/@openzeppelin/[email protected]/utils/ReentrancyGuardTransient.sol2.85 KB
- npm/@openzeppelin/[email protected]/utils/StorageSlot.sol4.18 KB
- npm/@openzeppelin/[email protected]/utils/TransientSlot.sol5.08 KB
- npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol871 B
- project/contracts/interfaces/IErrors.sol5.23 KB
- project/contracts/interfaces/IStaking.sol1.76 KB
- project/contracts/interfaces/IStakingPools.sol8.72 KB
- project/contracts/lib/Roles.sol6.5 KB
project/contracts/staking/EarthmetaStaking.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IStaking} from "../interfaces/IStaking.sol";
import {IStakingPools} from "../interfaces/IStakingPools.sol";
import {IErrors, ISolvencyErrors, IPositionErrors} from "../interfaces/IErrors.sol";
import {Roles} from "../lib/Roles.sol";
/// @title EarthmetaStaking
/// @author EarthMeta 2026.
/// @notice Unified successor to the legacy V1 (presale, signer-pushed) and V2
/// (normal, self-service) staking contracts. Every position — presale or
/// normal — is stored identically and is **permissionlessly self-claimed**
/// once matured, eliminating the custodial signer. Rewards use the legacy
/// flat-rate model (bps per stage × lock period). The contract tracks
/// solvency (`requiredReserve`: principal + reward liability + unspent
/// pool reward budget) and only lets an admin recover provably-unowed
/// funds — the exploited unlimited `emergencyWithdraw` and the
/// stake-rewriting `updateStaking` are gone.
/// @dev UUPS upgradeable; DEFAULT_ADMIN_ROLE = Timelock. Migration seeds historical
/// positions under MIGRATOR_ROLE (revoked afterwards). Reserves are funded
/// (`fundReserve`) before claims are unpaused; `stake()` enforces solvency so
/// no new promise is ever unbacked.
///
/// RESTAKE POOLS (2026-11). A pool is a governance-created campaign that
/// lets the holders of chosen existing positions roll principal + reward
/// into a new fixed-term position at the pool's own rates (`createPool`,
/// `reStakeToPool`). A pool id IS the `stage` of the positions it creates
/// and is priced by the pool's own term table instead of `_rewardRates`,
/// so those positions are ordinary `Stake`s — `claim`, the views and every
/// total treat them like any other. Pool terms are immutable; new rates
/// are a new pool. See the "Restake pools" sections below.
///
/// FRESH EMT (2026-11). A pool may also take NEW EMT. Its reward is paid
/// from a per-pool budget funded up front (`fundPoolRewards`), and the
/// budget plus every unclaimed fresh position is ring-fenced
/// (`fencedReserve`) from the legacy book: a legacy `claim` is paid only
/// from the balance the fence leaves free, and a fresh position is never
/// restaked or rewritten. Unspent budget counts in `requiredReserve`, so
/// it is never swept. See the "Fresh EMT" sections.
contract EarthmetaStaking is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardTransient,
UUPSUpgradeable,
IStaking,
IStakingPools,
IErrors,
ISolvencyErrors,
IPositionErrors
{
using SafeERC20 for IERC20;
/// @notice Basis-point denominator for reward rates.
uint256 public constant BPS = 10_000;
/// @notice Most lock terms one pool may define.
uint256 public constant MAX_POOL_TERMS = 8;
/// @notice Most source stages one pool may list.
uint256 public constant MAX_POOL_SOURCES = 32;
/// @notice Longest pool lock term, in days (5 years).
uint32 public constant MAX_POOL_PERIOD_DAYS = 1825;
/// @notice Highest reward a pool term may pay, in bps of principal (100%).
/// A typo guard: 17000 for 1700 does not get through.
uint32 public constant MAX_POOL_RATE_BPS = 10_000;
/// @notice Smallest non-zero bonus threshold (1 EMT). A typo guard: a
/// threshold entered in whole tokens instead of wei is refused.
uint256 public constant MIN_BONUS_UNIT = 1e18;
/// @notice Most positions one `reStakeToPool` call may merge.
uint256 public constant MAX_RESTAKE_BATCH = 50;
/// @notice The EMT token staked and paid out.
IERC20 public emt;
/// @notice Recipient of recovered excess reserves.
address public treasury;
/// @notice Per-user positions. Stake ids are stable array indices.
mapping(address => Stake[]) private _userStakes;
/// @notice rewardRates[stage] = [90d, 120d, 180d, 365d] in bps. A stage is
/// "set" iff index 0 is non-zero. Write-once per stage.
mapping(uint32 => uint256[4]) private _rewardRates;
/// @notice Sum of unclaimed principal.
uint256 public totalPrincipal;
/// @notice Sum of unclaimed reward obligations.
uint256 public totalRewardLiability;
/// @notice Whether restaking is currently open.
bool public reStakeOpen;
/// @notice The only stage a restake may target.
uint32 public reStakeStage;
/// @notice Restaking closes at this timestamp.
uint256 public reStakeDeadline;
/// @notice Stages that accept NEW self-service stakes. Default: none.
/// @dev A configured rate table prices a stage; it does NOT open it. The two
/// are deliberately separate: the six legacy stages exist only to value
/// MIGRATED positions at their original terms (V1 presale stage 1 pays
/// 18600 bps over 365 days). If a rate table alone admitted new stakes,
/// anyone could open a fresh position at the presale rate and convert
/// every EMT of reserve headroom into a 186% payout — and, because the
/// new obligation consumes the surplus, permanently brick `recoverExcess`.
/// A campaign is opened explicitly, per stage, by governance.
mapping(uint32 => bool) public stakeOpenStage;
/// @dev Specific errors.
error InvalidPeriod();
error InvalidStage();
error ReStakeClosed();
error AlreadyRestaked();
/// @dev A seed row disagrees with the position already stored at that index.
error SeedMismatch(address user, uint256 index);
/// @dev `stake()` was called for a stage that is not open to new stakes.
error StageClosed(uint32 stage);
/// @notice A stage was opened or closed for new self-service stakes.
event StakeOpenStageSet(uint32 indexed stage, bool open);
/// @notice A historical position to seed during migration.
/// @dev `index` is the expected slot in the user's array; it makes seeding
/// idempotent/resumable — a batch that overlaps an already-seeded range
/// is skipped rather than duplicated.
struct SeedReq {
address user;
uint256 index;
uint256 amount;
uint64 startTime;
uint32 stakingPeriod;
uint32 stage;
bool claimed;
bool restaked;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initialize the staking contract.
/// @param emt_ The EMT token.
/// @param admin DEFAULT_ADMIN (Timelock).
/// @param treasury_ Recipient of recovered excess.
function initialize(address emt_, address admin, address treasury_) external initializer {
if (emt_ == address(0) || admin == address(0) || treasury_ == address(0)) revert ZeroAddress();
__AccessControl_init();
__Pausable_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
emt = IERC20(emt_);
treasury = treasury_;
}
// ─────────────────────────────────────────────────────────────────────────
// Configuration (admin)
// ─────────────────────────────────────────────────────────────────────────
/// @notice Set the reward rate table for a stage (write-once, all four > 0).
function setRewardRates(uint32 stage, uint256[4] calldata rates) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (stage == 0) revert InvalidStage();
if (_rewardRates[stage][0] != 0) revert AlreadySet();
// A pool prices its own stage; a legacy table over it would silently
// reprice every position the pool created.
if (isPool(stage)) revert AlreadySet();
for (uint256 i = 0; i < 4; i++) {
if (rates[i] == 0) revert InvalidParam();
}
_rewardRates[stage] = rates;
emit RewardRatesSet(stage, rates);
}
/// @notice Open or close a stage for NEW self-service stakes.
/// @dev Migrated stages stay closed forever; open only a stage created for a
/// deliberate campaign, whose rate table was set for that purpose.
function setStakeOpenStage(uint32 stage, bool open) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (stage == 0) revert InvalidStage();
// A pool admits positions through `reStakeToPool` only (its window, its
// cap, its source list) — never as a fresh self-service stake.
if (open && isPool(stage)) revert InvalidStage();
stakeOpenStage[stage] = open;
emit StakeOpenStageSet(stage, open);
}
/// @notice Fund the reward reserve by transferring EMT into the contract.
function fundReserve(uint256 amount) external {
if (amount == 0) revert ZeroAmount();
emt.safeTransferFrom(msg.sender, address(this), amount);
emit ReserveFunded(msg.sender, amount);
}
/// @notice Open or close the restaking window.
function setReStakeOpen(bool open) external onlyRole(DEFAULT_ADMIN_ROLE) {
reStakeOpen = open;
emit ReStakeOpenSet(open);
}
/// @notice Set the restake target stage and deadline.
function setReStakeParams(uint32 stage, uint256 deadline) external onlyRole(DEFAULT_ADMIN_ROLE) {
reStakeStage = stage;
reStakeDeadline = deadline;
emit ReStakeParamsSet(stage, deadline);
}
/// @notice Update the excess-recovery recipient.
function setTreasury(address treasury_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (treasury_ == address(0)) revert ZeroAddress();
treasury = treasury_;
}
function pause() external {
_requirePauser();
_pause();
}
function unpause() external {
_requirePauser();
_unpause();
}
function _requirePauser() internal view {
if (!hasRole(Roles.PAUSER_ROLE, msg.sender) && !hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) {
revert NotAuthorized();
}
}
// ─────────────────────────────────────────────────────────────────────────
// Staking
// ─────────────────────────────────────────────────────────────────────────
/// @notice Stake `amount` EMT for `stakingPeriod` days at `stage`. Pulls EMT
/// from the caller and enforces reward-reserve solvency.
function stake(uint256 amount, uint32 stakingPeriod, uint32 stage) external whenNotPaused nonReentrant {
if (amount == 0) revert ZeroAmount();
// A priced stage is not an open stage — see `stakeOpenStage`.
if (!stakeOpenStage[stage]) revert StageClosed(stage);
uint256 reward = _reward(amount, stakingPeriod, stage);
emt.safeTransferFrom(msg.sender, address(this), amount);
_push(msg.sender, amount, uint64(block.timestamp), stakingPeriod, stage, false, false);
totalPrincipal += amount;
totalRewardLiability += reward;
// Every promise must be backed by present balance.
_requireSolvent();
}
/// @notice Claim principal + reward for a matured position.
/// @dev `whenNotPaused`: the migration model funds the reward reserve BEFORE
/// claims are unpaused (see contract NatSpec + runbook-migration), so
/// claims must be gated by the same emergency pause as stake/reStake.
///
/// The ring-fence: a fresh position is paid out of `fencedReserve`,
/// which the balance always covers; any other position only out of
/// the balance the fence leaves free (`InsufficientReserve` when
/// short). With the fence empty nothing changes, so an underfunded
/// claim still fails in the token's own transfer.
function claim(uint256 stakeId) external whenNotPaused nonReentrant {
Stake[] storage stakes = _userStakes[msg.sender];
if (stakeId >= stakes.length) revert InvalidPosition();
Stake storage s = stakes[stakeId];
if (s.claimed) revert AlreadyClaimed();
if (block.timestamp < uint256(s.startTime) + uint256(s.stakingPeriod) * 1 days) revert StillLocked();
uint256 principal = s.amount;
uint256 reward = _reward(principal, s.stakingPeriod, s.stage);
s.claimed = true;
totalPrincipal -= principal;
totalRewardLiability -= reward;
// `fencedReserve` is `totalRewardBudget` + Σ `freshOwed`, so a fresh
// position implies a non-empty fence: reading the fence first leaves
// an empty fence one storage read and no new branch.
uint256 fenced = fencedReserve;
if (fenced != 0) {
uint256 owed = freshOwed[msg.sender][stakeId];
if (owed != 0) {
// Fresh: its payout (`owed` = principal + reward) leaves the fence.
fencedReserve = fenced - owed;
freshOwed[msg.sender][stakeId] = 0;
} else {
uint256 need = principal + reward + fenced;
uint256 bal = emt.balanceOf(address(this));
if (bal < need) revert InsufficientReserve(need, bal);
}
}
emt.safeTransfer(msg.sender, principal + reward);
emit Claimed(msg.sender, stakeId, principal, reward);
}
/// @notice Compound a matured-or-open position into a new one (restake-once).
/// Only while the restaking window is open and before its deadline.
function reStake(uint256 stakeId, uint32 newPeriod, uint32 newStage) external whenNotPaused nonReentrant {
if (!reStakeOpen || block.timestamp >= reStakeDeadline) revert ReStakeClosed();
if (newStage != reStakeStage) revert InvalidStage();
// A pool is entered through `reStakeToPool`, which applies its rules.
if (isPool(newStage)) revert InvalidStage();
Stake[] storage stakes = _userStakes[msg.sender];
if (stakeId >= stakes.length) revert InvalidPosition();
Stake storage s = stakes[stakeId];
if (s.claimed) revert AlreadyClaimed();
if (s.restaked) revert AlreadyRestaked(); // a restake-created position can't be restaked again
_requireNotFresh(msg.sender, stakeId);
uint256 oldPrincipal = s.amount;
uint256 oldReward = _reward(oldPrincipal, s.stakingPeriod, s.stage);
uint256 newPrincipal = oldPrincipal + oldReward;
uint256 newReward = _reward(newPrincipal, newPeriod, newStage);
// Consume the old position; its principal+reward roll into the new one.
s.claimed = true;
// The new lock runs from the LATER of now and the old position's maturity:
// - still locked → start at the old maturity, so rolling early can never
// shorten the total time served;
// - already matured → start now, never in the past. Back-dating a matured
// position would pay a full period of yield for time nothing was locked,
// and 1,393 of the 1,625 migrated positions are already matured — a
// back-dated roll would be claimable in the block it was created.
uint256 oldMaturity = uint256(s.startTime) + uint256(s.stakingPeriod) * 1 days;
uint64 newStart = uint64(block.timestamp > oldMaturity ? block.timestamp : oldMaturity);
// Accounting: remove old, add new.
totalPrincipal = totalPrincipal - oldPrincipal + newPrincipal;
totalRewardLiability = totalRewardLiability - oldReward + newReward;
uint256 newId = stakes.length;
_push(msg.sender, newPrincipal, newStart, newPeriod, newStage, false, true);
_requireSolvent();
emit ReStaked(msg.sender, stakeId, newId, newPrincipal);
}
// ─────────────────────────────────────────────────────────────────────────
// Migration (MIGRATOR_ROLE)
// ─────────────────────────────────────────────────────────────────────────
/// @notice Seed historical positions with their exact original startTime and
/// flags. Preserves per-user index order (append in the given order).
/// Does NOT enforce solvency — reserves are funded before claims are
/// unpaused (see runbook). Only unclaimed positions add to liability.
function seedStakes(SeedReq[] calldata reqs) external onlyRole(Roles.MIGRATOR_ROLE) {
uint256 seeded;
for (uint256 i = 0; i < reqs.length; i++) {
SeedReq calldata r = reqs[i];
if (r.user == address(0)) revert ZeroAddress();
if (!r.claimed && r.amount == 0) revert ZeroAmount();
uint256 len = _userStakes[r.user].length;
if (r.index < len) {
// Idempotent for a genuine replay, loud on a divergent one. The
// comparison covers the IDENTITY of the position (amount, term,
// stage) but deliberately not `claimed`/`restaked`, which change
// legitimately once users are live — so a re-run stays a no-op
// after a claim, while a regenerated plan that shifts a user's
// rows (dropping one position and duplicating another, with no
// on-chain signal) reverts.
Stake storage p = _userStakes[r.user][r.index];
if (
p.amount != r.amount ||
p.startTime != r.startTime ||
p.stakingPeriod != r.stakingPeriod ||
p.stage != r.stage
) revert SeedMismatch(r.user, r.index);
continue;
}
if (r.index != len) revert InvalidPosition(); // seeds must be contiguous per user
_push(r.user, r.amount, r.startTime, r.stakingPeriod, r.stage, r.claimed, r.restaked);
if (!r.claimed) {
totalPrincipal += r.amount;
totalRewardLiability += _reward(r.amount, r.stakingPeriod, r.stage);
}
unchecked {
++seeded;
}
}
emit StakesSeeded(seeded);
}
/// @notice Governance correction of a stored position. Repairs bad or
/// mistakenly-migrated stake data (wrong amount / term / stage / flags).
/// Recomputes the reserve accounting from the before/after delta and
/// re-asserts solvency whenever the resulting position is live, so a fix
/// can never leave a promise unbacked. Emits the full before/after.
/// @dev Gated by DEFAULT_ADMIN_ROLE (the Timelock) — a standing but heavily
/// governed capability that replaces the legacy single-EOA `updateStaking`
/// (which was exploited). Callable while paused, so positions can be fixed
/// during an incident. A live result validates stage+period via `_reward`;
/// an invalid stage/period therefore reverts rather than corrupting state.
function adminFixStake(
address user,
uint256 stakeId,
Stake calldata newData
) external onlyRole(DEFAULT_ADMIN_ROLE) {
Stake[] storage stakes = _userStakes[user];
if (stakeId >= stakes.length) revert InvalidPosition();
// A fresh position's payout is fixed in `freshOwed` and the fence; a
// rewrite would desync them.
if (freshOwed[user][stakeId] != 0) revert FreshPosition(stakeId);
Stake storage s = stakes[stakeId];
Stake memory oldData = s;
// Unwind the OLD obligation — only a live position contributed to the reserve.
if (!oldData.claimed) {
totalPrincipal -= oldData.amount;
totalRewardLiability -= _reward(oldData.amount, oldData.stakingPeriod, oldData.stage);
}
// Apply the correction.
s.amount = newData.amount;
s.startTime = newData.startTime;
s.stakingPeriod = newData.stakingPeriod;
s.stage = newData.stage;
s.claimed = newData.claimed;
s.restaked = newData.restaked;
// Book the NEW obligation and re-assert solvency if the result is live.
// `_reward` validates stage+period, so a live fix cannot store bad params.
if (!newData.claimed) {
totalRewardLiability += _reward(newData.amount, newData.stakingPeriod, newData.stage);
totalPrincipal += newData.amount;
_requireSolvent();
}
emit StakeAdminFixed(user, stakeId, oldData, newData);
}
/// @notice Withdraw only funds that can never be owed to stakers.
/// @dev `whenNotPaused`: a pause is declared precisely when the accounting may
/// be untrustworthy, so the treasury sweep must be frozen alongside it.
/// Unspent pool reward budget is reserved (see `requiredReserve`), so
/// it is never swept.
function recoverExcess() external whenNotPaused nonReentrant {
_requireTreasurer();
uint256 reserved = _reserved();
uint256 bal = emt.balanceOf(address(this));
if (bal <= reserved) revert InsufficientReserve(reserved, bal);
uint256 excess = bal - reserved;
emt.safeTransfer(treasury, excess);
emit ExcessRecovered(treasury, excess);
}
// ─────────────────────────────────────────────────────────────────────────
// Restake pools — configuration (admin)
// ─────────────────────────────────────────────────────────────────────────
/// @notice Create a restake pool. It is created DISABLED: read it back, then
/// open it with `setPoolEnabled(poolId, true)`.
/// @dev `poolId` becomes the `stage` of every position the pool creates, so
/// it must be a stage nothing prices yet and that is closed to fresh
/// stakes. Rates are written once here and can never change — a
/// position's reward is recomputed from them at claim, so a mutable
/// rate would silently reprice positions and break the reserve totals.
///
/// Sources sit strictly BELOW the pool id. That makes the pool graph
/// acyclic by construction: a position can pass through each pool at
/// most once, so nobody can loop a locked position through pools to
/// farm bonus units or burn a pool's cap.
///
/// `enforceSolvency`: when true every `reStakeToPool` and `stakeToPool`
/// call into the pool must leave the contract holding at least
/// `requiredReserve()` (principal + reward liability + unspent pool
/// reward budget), exactly like `stake`. The check covers the whole
/// book, so while the legacy book is underfunded even a fresh-only
/// stake into such a pool reverts, although the fresh leg brings its
/// own principal and takes its reward from the budget. When false a
/// restake is admitted regardless — it moves no token and REPLACES an
/// obligation that is due (or about to be) with a later, larger one,
/// so it relieves the reserve today and adds `principal × rate` to it
/// at the new maturity. That promise is not backed by present balance:
/// `maxPrincipal` is the explicit bound governance accepts on it.
/// `stake()` always enforces solvency.
/// @param poolId The pool id (= stage). Non-zero, unused, above every source.
/// @param init The pool definition — see `IStakingPools.PoolInit`.
function createPool(uint32 poolId, PoolInit calldata init) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (poolId == 0) revert InvalidStage();
Pool storage pool = _pools[poolId];
if (pool.periods.length != 0) revert PoolExists(poolId);
if (_rewardRates[poolId][0] != 0 || stakeOpenStage[poolId]) revert InvalidStage();
if (init.closesAt <= init.opensAt || init.closesAt <= block.timestamp) revert InvalidParam();
if (init.maxPrincipal == 0) revert InvalidParam();
uint256 nTerms = init.terms.length;
if (nTerms == 0 || nTerms > MAX_POOL_TERMS) revert InvalidParam();
uint32 prev;
for (uint256 i = 0; i < nTerms; i++) {
PoolTerm calldata t = init.terms[i];
// Strictly ascending: no zero term, no duplicate.
if (t.periodDays <= prev || t.periodDays > MAX_POOL_PERIOD_DAYS) revert InvalidPeriod();
if (t.rateBps == 0 || t.rateBps > MAX_POOL_RATE_BPS) revert InvalidParam();
_checkBonusUnit(t.bonusUnit);
prev = t.periodDays;
pool.periods.push(t.periodDays);
pool.terms[t.periodDays] = TermData({rateBps: t.rateBps, bonusUnit: uint224(t.bonusUnit)});
emit PoolTermSet(poolId, t.periodDays, t.rateBps, t.bonusUnit);
}
pool.opensAt = init.opensAt;
pool.closesAt = init.closesAt;
pool.maxPrincipal = init.maxPrincipal;
pool.maxBonusUnits = init.maxBonusUnits;
pool.enforceSolvency = init.enforceSolvency;
_poolIds.push(poolId);
emit PoolCreated(
poolId,
init.opensAt,
init.closesAt,
init.maxPrincipal,
init.maxBonusUnits,
init.enforceSolvency
);
uint256 nSources = init.sourceStages.length;
if (nSources == 0) revert InvalidParam();
for (uint256 i = 0; i < nSources; i++) {
uint32 stage = init.sourceStages[i];
if (pool.sourceStage[stage]) revert InvalidParam(); // listed twice
_setSourceStage(pool, poolId, stage, true);
}
}
/// @notice Enable or disable a pool. Disabling is a brake — the pauser or
/// the admin; enabling is governance — the admin only.
function setPoolEnabled(uint32 poolId, bool enabled) external {
if (enabled) _checkRole(DEFAULT_ADMIN_ROLE);
else _requirePauser();
Pool storage pool = _existingPool(poolId);
pool.enabled = enabled;
emit PoolEnabledSet(poolId, enabled);
}
/// @notice Move a pool's window (extend it, or close it by passing a past
/// `closesAt`). Positions already in the pool are unaffected.
function setPoolWindow(uint32 poolId, uint64 opensAt, uint64 closesAt) external onlyRole(DEFAULT_ADMIN_ROLE) {
Pool storage pool = _existingPool(poolId);
if (closesAt <= opensAt) revert InvalidParam();
pool.opensAt = opensAt;
pool.closesAt = closesAt;
emit PoolWindowSet(poolId, opensAt, closesAt);
}
/// @notice Set a pool's caps: the principal it may admit in total and the
/// bonus units it may grant in total. Lowering either below what is
/// already used simply stops further admissions / grants.
function setPoolCaps(
uint32 poolId,
uint256 maxPrincipal,
uint256 maxBonusUnits
) external onlyRole(DEFAULT_ADMIN_ROLE) {
Pool storage pool = _existingPool(poolId);
pool.maxPrincipal = maxPrincipal;
pool.maxBonusUnits = maxBonusUnits;
emit PoolCapsSet(poolId, maxPrincipal, maxBonusUnits);
}
/// @notice Change the EMT-per-bonus-unit threshold of one term (0 = no
/// bonus). Applies to FUTURE restakes only: units already granted
/// are stored per position. A restaker is protected from a change
/// landing ahead of their transaction by `minBonusUnits`.
/// @dev The threshold is a fixed EMT amount on purpose. Reading a price
/// oracle here would let a holder move the TWAP for one window and be
/// granted units for a dollar value the position never had.
function setPoolBonusUnit(
uint32 poolId,
uint32 periodDays,
uint256 bonusUnit
) external onlyRole(DEFAULT_ADMIN_ROLE) {
Pool storage pool = _existingPool(poolId);
TermData storage term = pool.terms[periodDays];
if (term.rateBps == 0) revert InvalidPeriod();
_checkBonusUnit(bonusUnit);
term.bonusUnit = uint224(bonusUnit);
emit PoolBonusUnitSet(poolId, periodDays, bonusUnit);
}
/// @notice Allow or remove a source stage. Affects future restakes only.
function setPoolSourceStage(uint32 poolId, uint32 stage, bool allowed) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setSourceStage(_existingPool(poolId), poolId, stage, allowed);
}
/// @notice Switch a pool's solvency requirement (see `createPool`).
function setPoolSolvency(uint32 poolId, bool enforceSolvency) external onlyRole(DEFAULT_ADMIN_ROLE) {
Pool storage pool = _existingPool(poolId);
pool.enforceSolvency = enforceSolvency;
emit PoolSolvencySet(poolId, enforceSolvency);
}
// ─────────────────────────────────────────────────────────────────────────
// Fresh EMT — reward budget and fresh cap (admin / treasurer)
// ─────────────────────────────────────────────────────────────────────────
/// @notice Add `amount` EMT, pulled from the caller, to `poolId`'s reward
/// budget: the reserve the reward of every fresh stake into the
/// pool is taken from. A pool may be funded before it opens.
/// @dev The budget is ring-fenced from the moment it arrives: it counts in
/// `requiredReserve` (so `recoverExcess` cannot sweep it and no other
/// promise is admitted against it) and in `fencedReserve`. Pulled
/// BEFORE it is booked, so the fence never exceeds the balance.
function fundPoolRewards(uint32 poolId, uint256 amount) external {
_requireTreasurer();
_existingPool(poolId);
if (amount == 0) revert ZeroAmount();
emt.safeTransferFrom(msg.sender, address(this), amount);
uint256 budget;
// Each sum only ever grows by EMT actually received, so it stays below
// the token's supply (2.1e27) — nowhere near overflow.
unchecked {
budget = poolRewardBudget[poolId] + amount;
totalRewardBudget += amount;
fencedReserve += amount;
}
poolRewardBudget[poolId] = budget;
emit PoolRewardsFunded(poolId, msg.sender, amount, budget);
}
/// @notice Send `amount` of `poolId`'s UNSPENT reward budget to `to`. A
/// reward already promised to a fresh position has left the budget
/// and can never be withdrawn.
function withdrawPoolRewards(
uint32 poolId,
uint256 amount,
address to
) external onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused {
if (to == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
uint256 budget = poolRewardBudget[poolId];
if (amount > budget) revert RewardBudgetExceeded(poolId, amount, budget);
unchecked {
budget -= amount; // checked just above
}
poolRewardBudget[poolId] = budget;
totalRewardBudget -= amount;
fencedReserve -= amount;
emt.safeTransfer(to, amount);
emit PoolRewardsWithdrawn(poolId, to, amount, budget);
}
/// @notice Set the most fresh principal `poolId` may take in total. A cap
/// below what it has already taken simply stops new fresh stakes.
function setPoolFreshCap(uint32 poolId, uint256 cap) external onlyRole(DEFAULT_ADMIN_ROLE) {
_existingPool(poolId);
poolFreshCap[poolId] = cap;
emit PoolFreshCapSet(poolId, cap);
}
// ─────────────────────────────────────────────────────────────────────────
// Restake pools — restaking
// ─────────────────────────────────────────────────────────────────────────
/// @notice Roll one or more of the caller's positions into ONE new position
/// in `poolId`, locked for `periodDays`. The new principal is the sum
/// of every source's principal + reward; no token moves.
/// @dev Each source must be unclaimed, not a fresh position
/// (`FreshNotRestakable`) and of a stage the pool lists as a source;
/// whether it was itself created by a restake does not matter here
/// (the restake-once rule belongs to the legacy `reStake`).
/// The new lock runs from the LATER of now and the latest source
/// maturity, so rolling a still-locked position can never shorten the
/// time served and a matured one is never back-dated.
/// Bonus units are computed on the merged principal against the term's
/// fixed threshold, capped by what the pool has left, stored against
/// the new position and never changed afterwards.
/// @param stakeIds The positions to roll — strictly ascending, at most
/// `MAX_RESTAKE_BATCH`.
/// @param poolId The pool.
/// @param periodDays One of the pool's terms.
/// @param minBonusUnits Revert unless at least this many bonus units are
/// granted (pass the quoted figure; 0 to accept any).
/// @return newStakeId The id of the position created.
function reStakeToPool(
uint256[] calldata stakeIds,
uint32 poolId,
uint32 periodDays,
uint256 minBonusUnits
) external whenNotPaused nonReentrant returns (uint256 newStakeId) {
Pool storage pool = _pools[poolId];
newStakeId = _restakeLeg(pool, poolId, stakeIds, periodDays, 0, minBonusUnits);
if (pool.enforceSolvency) _requireSolvent();
}
// ─────────────────────────────────────────────────────────────────────────
// Fresh EMT — staking (new EMT, restakes, or both in one call)
// ─────────────────────────────────────────────────────────────────────────
/// @notice Stake `amount` NEW EMT and/or roll the positions `stakeIds` into
/// `poolId`, locked for `periodDays`, in one call. Each leg that
/// runs opens its own position.
/// @dev The restake leg runs FIRST and is `reStakeToPool` exactly (same
/// checks, cap, start rule, totals and events) except for its bonus
/// units. The fresh leg runs second: it pulls `amount`, starts now,
/// books `amount × rate` taken out of the pool's reward budget
/// (`RewardBudgetExceeded` when short), is bounded by `poolFreshCap`
/// — never by the restake book's `maxPrincipal` — and is announced by
/// `PoolStaked` alone, never `Staked`.
/// Bonus units are ONE figure for the whole call, computed on both
/// principals together, and stored on one position: the restake's when
/// that leg runs, else the fresh one's. The other leg's event carries
/// 0. A grant is fixed at creation and never changes a payout, so
/// where it sits is bookkeeping.
/// @param poolId The pool.
/// @param amount New EMT to stake, approved beforehand (0 = none).
/// @param stakeIds Positions to roll (empty = none) — strictly
/// ascending, at most `MAX_RESTAKE_BATCH`.
/// @param periodDays One of the pool's terms, for both legs.
/// @param minBonusUnits Revert unless the call grants at least this many
/// bonus units in total (0 to accept any).
/// @return freshStakeId The fresh position's id; `type(uint256).max` if
/// that leg did not run.
/// @return restakeStakeId The restake position's id; `type(uint256).max` if
/// that leg did not run.
function stakeToPool(
uint32 poolId,
uint256 amount,
uint256[] calldata stakeIds,
uint32 periodDays,
uint256 minBonusUnits
) external whenNotPaused nonReentrant returns (uint256 freshStakeId, uint256 restakeStakeId) {
Pool storage pool = _pools[poolId];
TermData memory term = _openTerm(pool, poolId, periodDays);
if (amount == 0 && stakeIds.length == 0) revert ZeroAmount();
freshStakeId = type(uint256).max;
restakeStakeId = type(uint256).max;
uint256 units; // the fresh position's: none when the restake leg runs
if (stakeIds.length != 0) {
restakeStakeId = _restakeLeg(pool, poolId, stakeIds, periodDays, amount, minBonusUnits);
} else {
units = _bonusUnitsFor(pool, term, amount);
if (units < minBonusUnits) revert BonusBelowMin(units, minBonusUnits);
}
if (amount != 0) freshStakeId = _stakeFresh(pool, poolId, periodDays, term.rateBps, amount, units);
if (pool.enforceSolvency) _requireSolvent();
}
// ─────────────────────────────────────────────────────────────────────────
// Internal
// ─────────────────────────────────────────────────────────────────────────
function _push(
address user,
uint256 amount,
uint64 startTime,
uint32 period,
uint32 stage,
bool claimed,
bool restaked
) internal {
uint256 id = _append(user, amount, startTime, period, stage, claimed, restaked);
emit Staked(user, id, amount, period, stage, startTime);
}
/// @dev Append a position to `user`'s array and return its id, announcing
/// nothing: `_push` adds `Staked`, a pool position its pool event.
function _append(
address user,
uint256 amount,
uint64 startTime,
uint32 period,
uint32 stage,
bool claimed,
bool restaked
) internal returns (uint256 id) {
Stake[] storage stakes = _userStakes[user];
id = stakes.length;
stakes.push(
Stake({
amount: amount,
startTime: startTime,
stakingPeriod: period,
stage: stage,
claimed: claimed,
restaked: restaked
})
);
}
function _reward(uint256 amount, uint32 period, uint32 stage) internal view returns (uint256) {
return (amount * _rateBps(stage, period)) / BPS;
}
/// @dev The flat reward rate of (stage, period). A stage is priced by the
/// legacy four-period table OR by a pool's term table, never both:
/// `createPool` refuses a stage the table prices and `setRewardRates`
/// refuses a pool. Reverts `InvalidStage` for an unpriced stage and
/// `InvalidPeriod` for a period the stage does not offer.
function _rateBps(uint32 stage, uint32 period) internal view returns (uint256) {
uint256[4] storage rates = _rewardRates[stage];
if (rates[0] != 0) return rates[_periodIndex(period)];
Pool storage pool = _pools[stage];
if (pool.periods.length == 0) revert InvalidStage();
uint256 bps = pool.terms[period].rateBps;
if (bps == 0) revert InvalidPeriod();
return bps;
}
function _periodIndex(uint32 period) internal pure returns (uint256) {
if (period == 90) return 0;
if (period == 120) return 1;
if (period == 180) return 2;
if (period == 365) return 3;
revert InvalidPeriod();
}
function _requireSolvent() internal view {
uint256 reserved = _reserved();
uint256 bal = emt.balanceOf(address(this));
if (bal < reserved) revert InsufficientReserve(reserved, bal);
}
/// @dev What the contract must hold: every unclaimed principal and reward,
/// plus every pool's unspent reward budget.
function _reserved() internal view returns (uint256) {
return totalPrincipal + totalRewardLiability + totalRewardBudget;
}
/// @dev The treasurer or the admin, else `NotAuthorized`.
function _requireTreasurer() internal view {
if (!hasRole(Roles.TREASURER_ROLE, msg.sender) && !hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) {
revert NotAuthorized();
}
}
/// @dev The pool at `poolId`, or revert. A pool always has at least one term.
function _existingPool(uint32 poolId) internal view returns (Pool storage pool) {
pool = _pools[poolId];
if (pool.periods.length == 0) revert PoolNotFound(poolId);
}
/// @dev A bonus threshold is 0 (no bonus) or a sane EMT amount.
function _checkBonusUnit(uint256 bonusUnit) internal pure {
if (bonusUnit != 0 && (bonusUnit < MIN_BONUS_UNIT || bonusUnit > type(uint224).max)) revert InvalidParam();
}
/// @dev Allow or remove a source stage. An allowed source is a priced stage
/// strictly below the pool id (see `createPool`).
function _setSourceStage(Pool storage pool, uint32 poolId, uint32 stage, bool allowed) internal {
if (allowed) {
if (stage == 0 || stage >= poolId) revert InvalidStage();
if (_rewardRates[stage][0] == 0 && !isPool(stage)) revert InvalidStage();
uint256 n = pool.sourceList.length;
bool listed;
for (uint256 i = 0; i < n; i++) {
if (pool.sourceList[i] == stage) {
listed = true;
break;
}
}
if (!listed) {
if (n >= MAX_POOL_SOURCES) revert InvalidParam();
pool.sourceList.push(stage);
}
}
pool.sourceStage[stage] = allowed;
emit PoolSourceStageSet(poolId, stage, allowed);
}
/// @dev Sum the sources of a restake: their principal, their reward, and the
/// latest of now and every source's maturity. Validates each source.
function _sumSources(
address user,
uint256[] calldata stakeIds,
Pool storage pool
) internal view returns (uint256 oldPrincipal, uint256 oldReward, uint256 start) {
uint256 n = stakeIds.length;
if (n == 0 || n > MAX_RESTAKE_BATCH) revert InvalidBatch();
Stake[] storage stakes = _userStakes[user];
uint256 len = stakes.length;
start = block.timestamp;
for (uint256 i = 0; i < n; i++) {
uint256 id = stakeIds[i];
// Strictly ascending — which also rules out naming a position twice.
if (i != 0 && id <= stakeIds[i - 1]) revert InvalidBatch();
if (id >= len) revert InvalidPosition();
Stake storage s = stakes[id];
if (s.claimed) revert AlreadyClaimed();
_requireNotFresh(user, id);
if (!pool.sourceStage[s.stage]) revert NotEligible(id, s.stage);
oldPrincipal += s.amount;
oldReward += _reward(s.amount, s.stakingPeriod, s.stage);
uint256 maturity = uint256(s.startTime) + uint256(s.stakingPeriod) * 1 days;
if (maturity > start) start = maturity;
}
}
/// @dev A fresh position is never a restake source, by either door: rolling
/// it would move its payout out of the fence into the legacy book.
function _requireNotFresh(address user, uint256 stakeId) internal view {
if (freshOwed[user][stakeId] != 0) revert FreshNotRestakable(stakeId);
}
/// @dev Mark every source claimed and announce it. Returns the id the new
/// position will take (the user's next array index). `_quoteRestake`
/// has already validated every id.
function _consumeSources(address user, uint256[] calldata stakeIds) internal returns (uint256 newStakeId) {
Stake[] storage stakes = _userStakes[user];
newStakeId = stakes.length;
for (uint256 i = 0; i < stakeIds.length; i++) {
Stake storage s = stakes[stakeIds[i]];
// Each source's principal + reward rolls into the new position.
uint256 rolled = s.amount + _reward(s.amount, s.stakingPeriod, s.stage);
s.claimed = true;
emit ReStaked(user, stakeIds[i], newStakeId, rolled);
}
}
/// @dev Append the pool position `q` describes, book it against the pool and
/// record its bonus units.
function _openPoolPosition(
address user,
Pool storage pool,
uint32 poolId,
uint32 periodDays,
RestakeQuote memory q
) internal {
pool.principalIn += q.principal;
pool.rewardBooked += q.reward;
// Deliberately NOT `_push`: a pool position is announced by `PoolReStaked`
// alone, never by `Staked`. `Staked` is what the platform's free-city job
// pays on (one city per USD threshold of ANY new stake, whatever its term),
// so emitting it here would hand a city to every restaker — including the
// terms that carry no bonus. The pool's own `bonusUnits` is the only grant.
uint256 stakeId = _append(user, q.principal, q.startTime, periodDays, poolId, false, true);
_grantBonusUnits(user, pool, stakeId, q.bonusUnits);
emit PoolReStaked(user, poolId, stakeId, periodDays, q.principal, q.reward, q.startTime, q.bonusUnits);
}
/// @dev Roll `stakeIds` into one new position in `poolId`: the whole of
/// `reStakeToPool`, and the restake leg of `stakeToPool`. The bonus
/// units are computed on the rolled principal plus `fresh`, the
/// principal of a fresh leg in the same call (0 from `reStakeToPool`,
/// which leaves the quote's own figure), and all granted here.
function _restakeLeg(
Pool storage pool,
uint32 poolId,
uint256[] calldata stakeIds,
uint32 periodDays,
uint256 fresh,
uint256 minBonusUnits
) internal returns (uint256 newStakeId) {
(RestakeQuote memory q, uint256 oldPrincipal, uint256 oldReward) = _quoteRestake(
msg.sender,
stakeIds,
pool,
poolId,
periodDays
);
// The quote validated the term.
q.bonusUnits = _bonusUnitsFor(pool, pool.terms[periodDays], fresh + q.principal);
if (q.bonusUnits < minBonusUnits) revert BonusBelowMin(q.bonusUnits, minBonusUnits);
newStakeId = _consumeSources(msg.sender, stakeIds);
// Accounting: remove the old obligations, add the new one.
totalPrincipal = totalPrincipal - oldPrincipal + q.principal;
totalRewardLiability = totalRewardLiability - oldReward + q.reward;
_openPoolPosition(msg.sender, pool, poolId, periodDays, q);
}
/// @dev The fresh leg of `stakeToPool`: pull `amount` from the caller and
/// open a position for it starting now, its reward moved from the
/// pool's budget to the book. `units` were computed by the caller.
function _stakeFresh(
Pool storage pool,
uint32 poolId,
uint32 periodDays,
uint256 rateBps,
uint256 amount,
uint256 units
) internal returns (uint256 stakeId) {
// `_reward`'s arithmetic on the same rate, so the claim pays exactly this.
uint256 reward = (amount * rateBps) / BPS;
uint256 budget = poolRewardBudget[poolId];
if (budget < reward) revert RewardBudgetExceeded(poolId, reward, budget);
uint256 freshIn = poolFreshIn[poolId] + amount;
uint256 cap = poolFreshCap[poolId];
if (freshIn > cap) revert PoolCapExceeded(poolId, freshIn, cap);
emt.safeTransferFrom(msg.sender, address(this), amount);
// Not `_push`, for the reason in `_openPoolPosition`: `Staked` would
// hand out a free city outside the pool's own `bonusUnits`.
stakeId = _append(msg.sender, amount, uint64(block.timestamp), periodDays, poolId, false, false);
totalPrincipal += amount;
totalRewardLiability += reward;
poolFreshIn[poolId] = freshIn;
// The reward leaves the budget for the book. It was fenced already, so
// the fence grows by the principal alone.
unchecked {
poolRewardBudget[poolId] = budget - reward; // checked above
}
totalRewardBudget -= reward;
fencedReserve += amount;
freshOwed[msg.sender][stakeId] = amount + reward;
_grantBonusUnits(msg.sender, pool, stakeId, units);
emit PoolStaked(msg.sender, poolId, stakeId, periodDays, amount, reward, uint64(block.timestamp), units);
}
/// @dev Record `units` bonus units against one position and every total.
function _grantBonusUnits(address user, Pool storage pool, uint256 stakeId, uint256 units) internal {
if (units != 0) {
_stakeBonusUnits[user][stakeId] = units;
bonusUnitsOf[user] += units;
pool.bonusUnitsGranted += units;
totalBonusUnits += units;
}
}
/// @dev The term `periodDays` of `poolId`, which must exist (`PoolNotFound`),
/// be enabled and inside its window (`PoolClosed`) and offer that term
/// (`InvalidPeriod`).
function _openTerm(
Pool storage pool,
uint32 poolId,
uint32 periodDays
) internal view returns (TermData memory term) {
if (pool.periods.length == 0) revert PoolNotFound(poolId);
if (!pool.enabled || block.timestamp < pool.opensAt || block.timestamp >= pool.closesAt) {
revert PoolClosed(poolId);
}
term = pool.terms[periodDays];
if (term.rateBps == 0) revert InvalidPeriod();
}
/// @dev The bonus units `principal` earns on `term`: one per `bonusUnit`,
/// capped by what the pool has left to grant; 0 when the term carries
/// no bonus. The only place the city maths lives.
function _bonusUnitsFor(
Pool storage pool,
TermData memory term,
uint256 principal
) internal view returns (uint256 units) {
if (term.bonusUnit != 0) {
units = principal / term.bonusUnit;
uint256 granted = pool.bonusUnitsGranted;
uint256 room = pool.maxBonusUnits > granted ? pool.maxBonusUnits - granted : 0;
if (units > room) units = room;
}
}
/// @dev Everything `reStakeToPool` checks and computes, without writing —
/// shared with `quoteReStakeToPool` so the quote can never drift from
/// the transaction.
function _quoteRestake(
address user,
uint256[] calldata stakeIds,
Pool storage pool,
uint32 poolId,
uint32 periodDays
) internal view returns (RestakeQuote memory q, uint256 oldPrincipal, uint256 oldReward) {
TermData memory term = _openTerm(pool, poolId, periodDays);
uint256 start;
(oldPrincipal, oldReward, start) = _sumSources(user, stakeIds, pool);
uint256 principal = oldPrincipal + oldReward;
if (principal == 0) revert ZeroAmount();
uint256 admitted = pool.principalIn + principal;
if (admitted > pool.maxPrincipal) revert PoolCapExceeded(poolId, admitted, pool.maxPrincipal);
uint256 maturity = start + uint256(periodDays) * 1 days;
if (maturity > type(uint64).max) revert InvalidParam();
q.principal = principal;
q.reward = (principal * term.rateBps) / BPS;
q.startTime = uint64(start);
q.maturity = uint64(maturity);
q.bonusUnits = _bonusUnitsFor(pool, term, principal);
}
// ─────────────────────────────────────────────────────────────────────────
// Views
// ─────────────────────────────────────────────────────────────────────────
/// @notice The reward table for a stage: bps for [90d, 120d, 180d, 365d].
/// @dev For a pool it reports the pool's rate at each of those four periods
/// (0 where the pool has no such term), so every reader that prices a
/// position as `amount × rewardRates(stage)[periodIndex] / BPS` — the
/// app and the API both do — prices a pool position correctly without
/// knowing pools exist. A pool term outside those four periods is only
/// visible through `getPool` / `rewardRateBps`.
function rewardRates(uint32 stage) external view returns (uint256[4] memory) {
uint256[4] memory rates = _rewardRates[stage];
if (rates[0] == 0) {
Pool storage pool = _pools[stage];
if (pool.periods.length != 0) {
rates[0] = pool.terms[90].rateBps;
rates[1] = pool.terms[120].rateBps;
rates[2] = pool.terms[180].rateBps;
rates[3] = pool.terms[365].rateBps;
}
}
return rates;
}
/// @notice Reward owed for a specific position.
function positionReward(address user, uint256 stakeId) external view returns (uint256) {
Stake storage s = _userStakes[user][stakeId];
return _reward(s.amount, s.stakingPeriod, s.stage);
}
/// @notice Number of positions a user holds.
function stakeCount(address user) external view returns (uint256) {
return _userStakes[user].length;
}
/// @notice A single position.
function getStake(address user, uint256 stakeId) external view returns (Stake memory) {
return _userStakes[user][stakeId];
}
/// @notice Paginated positions for a user.
function getUserStakes(address user, uint256 start, uint256 limit) external view returns (Stake[] memory) {
Stake[] storage all = _userStakes[user];
if (start >= all.length) return new Stake[](0);
uint256 end = start + limit;
if (end > all.length) end = all.length;
Stake[] memory page = new Stake[](end - start);
for (uint256 i = start; i < end; i++) {
page[i - start] = all[i];
}
return page;
}
/// @notice Total EMT the contract must hold to cover all obligations:
/// unclaimed principal + reward liability + unspent pool reward budget.
function requiredReserve() external view returns (uint256) {
return _reserved();
}
// ─────────────────────────────────────────────────────────────────────────
// Restake pools — views
// ─────────────────────────────────────────────────────────────────────────
/// @notice Whether `stage` is a restake pool.
function isPool(uint32 stage) public view returns (bool) {
return _pools[stage].periods.length != 0;
}
/// @notice Every pool id, in creation order.
function poolIds() external view returns (uint32[] memory) {
return _poolIds;
}
/// @notice A pool's configuration and running totals.
function getPool(uint32 poolId) external view returns (PoolView memory v) {
Pool storage pool = _existingPool(poolId);
v.enabled = pool.enabled;
v.enforceSolvency = pool.enforceSolvency;
v.opensAt = pool.opensAt;
v.closesAt = pool.closesAt;
v.maxPrincipal = pool.maxPrincipal;
v.principalIn = pool.principalIn;
v.rewardBooked = pool.rewardBooked;
v.maxBonusUnits = pool.maxBonusUnits;
v.bonusUnitsGranted = pool.bonusUnitsGranted;
uint256 nTerms = pool.periods.length;
v.terms = new PoolTerm[](nTerms);
for (uint256 i = 0; i < nTerms; i++) {
uint32 period = pool.periods[i];
TermData storage term = pool.terms[period];
v.terms[i] = PoolTerm({periodDays: period, rateBps: term.rateBps, bonusUnit: term.bonusUnit});
}
// `sourceList` keeps every stage ever allowed; report the ones still allowed.
uint256 nListed = pool.sourceList.length;
uint256 nAllowed;
for (uint256 i = 0; i < nListed; i++) {
if (pool.sourceStage[pool.sourceList[i]]) ++nAllowed;
}
v.sourceStages = new uint32[](nAllowed);
uint256 k;
for (uint256 i = 0; i < nListed; i++) {
uint32 stage = pool.sourceList[i];
if (pool.sourceStage[stage]) v.sourceStages[k++] = stage;
}
}
/// @notice Whether positions of `stage` may enter `poolId`.
function poolSourceStage(uint32 poolId, uint32 stage) external view returns (bool) {
return _pools[poolId].sourceStage[stage];
}
/// @notice The flat reward rate (bps of principal, for the whole term) of a
/// (stage, period) — a migrated stage or a pool alike. Reverts
/// `InvalidStage` / `InvalidPeriod` when the pair is not offered.
function rewardRateBps(uint32 stage, uint32 periodDays) external view returns (uint256) {
return _rateBps(stage, periodDays);
}
/// @notice Bonus units granted to one position (0 for any position that was
/// not created by a bonus-bearing pool term).
function stakeBonusUnits(address user, uint256 stakeId) external view returns (uint256) {
return _stakeBonusUnits[user][stakeId];
}
/// @notice Exactly what `reStakeToPool(stakeIds, poolId, periodDays, …)` would
/// create for `user` right now. Reverts with the same error the
/// transaction would (closed pool, ineligible or claimed position,
/// cap, paused, unmet solvency) — so a quote that returns is a
/// restake that goes through, bar a state change in between.
function quoteReStakeToPool(
address user,
uint256[] calldata stakeIds,
uint32 poolId,
uint32 periodDays
) external view returns (RestakeQuote memory q) {
_requireNotPaused();
Pool storage pool = _pools[poolId];
uint256 oldPrincipal;
uint256 oldReward;
(q, oldPrincipal, oldReward) = _quoteRestake(user, stakeIds, pool, poolId, periodDays);
if (pool.enforceSolvency) {
uint256 reserved =
totalPrincipal - oldPrincipal + q.principal + totalRewardLiability - oldReward + q.reward;
// The unspent budget too: the same sum `_requireSolvent` checks.
reserved += totalRewardBudget;
uint256 bal = emt.balanceOf(address(this));
if (bal < reserved) revert InsufficientReserve(reserved, bal);
}
}
/// @inheritdoc UUPSUpgradeable
function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {}
// ─────────────────────────────────────────────────────────────────────────
// Restake pools — storage (appended 2026-11; five slots, `__gap` 43 → 38)
// ─────────────────────────────────────────────────────────────────────────
/// @dev One term as stored: a single slot.
struct TermData {
uint32 rateBps;
uint224 bonusUnit;
}
/// @dev A pool. Lives only inside `_pools`, so its mappings and arrays hang
/// off the mapping slot and never shift the contract's own layout.
struct Pool {
bool enabled;
bool enforceSolvency;
uint64 opensAt;
uint64 closesAt;
uint256 maxPrincipal;
uint256 principalIn;
uint256 rewardBooked;
uint256 maxBonusUnits;
uint256 bonusUnitsGranted;
uint32[] periods;
mapping(uint32 => TermData) terms;
uint32[] sourceList;
mapping(uint32 => bool) sourceStage;
}
/// @dev poolId (= stage) → pool.
mapping(uint32 => Pool) private _pools;
/// @dev Every pool id, in creation order.
uint32[] private _poolIds;
/// @dev (user, stakeId) → bonus units granted to that position.
mapping(address => mapping(uint256 => uint256)) private _stakeBonusUnits;
/// @notice Bonus units granted to a user across all their positions.
mapping(address => uint256) public bonusUnitsOf;
/// @notice Bonus units granted across all pools.
uint256 public totalBonusUnits;
// ─────────────────────────────────────────────────────────────────────────
// Fresh EMT — storage (appended 2026-11; six slots, `__gap` 38 → 32)
// ─────────────────────────────────────────────────────────────────────────
/// @notice poolId → EMT set aside to pay the reward of future fresh stakes
/// into that pool, not yet promised to any position.
mapping(uint32 => uint256) public poolRewardBudget;
/// @notice Σ `poolRewardBudget` over every pool. Part of `requiredReserve`,
/// so unspent budget is never swept and never backs another promise.
uint256 public totalRewardBudget;
/// @notice The ring-fence: `totalRewardBudget` + Σ (principal + reward) of
/// every unclaimed fresh position. Invariant: balance ≥ this.
uint256 public fencedReserve;
/// @notice (user, stakeId) → what a fresh position pays at claim (principal
/// + reward). 0 = not a fresh position (legacy, restake or claimed).
mapping(address => mapping(uint256 => uint256)) public freshOwed;
/// @notice poolId → the most fresh principal the pool may take in total.
/// 0 (the default) admits none. Separate from the pool's
/// `maxPrincipal`, which stays the restake book's.
mapping(uint32 => uint256) public poolFreshCap;
/// @notice poolId → fresh principal the pool has taken in total.
mapping(uint32 => uint256) public poolFreshIn;
uint256[32] private __gap;
}
npm/@openzeppelin/[email protected]/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/// @inheritdoc ERC165Upgradeable
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
npm/@openzeppelin/[email protected]/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
npm/@openzeppelin/[email protected]/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
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;
}
}
npm/@openzeppelin/[email protected]/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
function __Pausable_init() internal onlyInitializing {
}
function __Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
npm/@openzeppelin/[email protected]/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
npm/@openzeppelin/[email protected]/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
npm/@openzeppelin/[email protected]/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);
}
npm/@openzeppelin/[email protected]/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";
npm/@openzeppelin/[email protected]/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
npm/@openzeppelin/[email protected]/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";
npm/@openzeppelin/[email protected]/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
npm/@openzeppelin/[email protected]/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
npm/@openzeppelin/[email protected]/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
npm/@openzeppelin/[email protected]/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* @custom:stateless
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
npm/@openzeppelin/[email protected]/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);
}
npm/@openzeppelin/[email protected]/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)
}
}
}
npm/@openzeppelin/[email protected]/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bool success = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
bool success = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
bool success = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
npm/@openzeppelin/[email protected]/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
npm/@openzeppelin/[email protected]/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
npm/@openzeppelin/[email protected]/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*
* @custom:stateless
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
_reentrancyGuardStorageSlot().asBoolean().tstore(false);
}
/**
* @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().asBoolean().tload();
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
npm/@openzeppelin/[email protected]/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
}
}
}
npm/@openzeppelin/[email protected]/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
npm/@openzeppelin/[email protected]/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);
}
project/contracts/interfaces/IErrors.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/// @title Shared custom errors for the EarthMeta v2 suite.
/// @author EarthMeta 2026.
/// @notice Grouped so every contract reverts with a typed, gas-cheap error
/// instead of a string. Import the interface(s) you need.
interface IErrors {
/// @notice A zero address was supplied where a real one is required.
error ZeroAddress();
/// @notice A zero amount was supplied where a positive one is required.
error ZeroAmount();
/// @notice The caller is not permitted to perform this action.
error NotAuthorized();
/// @notice A parameter failed validation (out of range, malformed, etc.).
error InvalidParam();
/// @notice A one-time-settable value has already been set.
error AlreadySet();
/// @notice A time-bounded authorization is past its deadline.
error Expired();
/// @notice A replay-protection nonce has already been consumed.
error NonceUsed();
/// @notice Array arguments have mismatched lengths.
error LengthMismatch();
}
/// @notice Errors specific to reserve-backed payout contracts (marketplace/staking/vesting).
interface ISolvencyErrors {
/// @notice The EMT reserve cannot cover a required payout.
/// @param need The amount required.
/// @param have The amount available.
error InsufficientReserve(uint256 need, uint256 have);
/// @notice An operation would leave the contract unable to meet its obligations.
error SolvencyBreached();
}
/// @notice Errors specific to the price oracle.
interface IOracleErrors {
/// @notice The derived price fell outside the admin-configured safety band.
/// @param price The rejected price (EMT per USD, 1e18-scaled).
/// @param lo The band floor.
/// @param hi The band ceiling.
error PriceOutOfBand(uint256 price, uint256 lo, uint256 hi);
/// @notice A Chainlink feed returned a stale or non-positive answer.
error StaleOracle();
/// @notice USDT has strayed too far from its peg to price against safely.
/// @dev Only meaningful when the pool quotes EMT in USDT: price and payment
/// are then in the same asset, so the USDT/USD factor cancels out of
/// settlement and cannot itself protect the reserve. This is the
/// explicit guard that replaces it.
/// @param usdtUsdX18 The reported USDT/USD price (1e18-scaled).
/// @param loX18 Lowest accepted USDT/USD price.
/// @param hiX18 Highest accepted USDT/USD price.
error UsdtDepegged(uint256 usdtUsdX18, uint256 loX18, uint256 hiX18);
/// @notice The pool has not provisioned enough observation slots to back the
/// TWAP window (a fresh Uniswap V3 pool starts at cardinality 1).
/// @param have The pool's current observation cardinality.
/// @param need The configured minimum.
error InsufficientObservations(uint16 have, uint16 need);
/// @notice The pool's retained history is shorter than the TWAP window, so
/// the "average" would be dominated by the most recent swap.
/// @param have Age in seconds of the oldest retained observation.
/// @param need The configured TWAP window.
error InsufficientHistory(uint32 have, uint32 need);
}
/// @notice Errors specific to marketplace order settlement.
interface IMarketErrors {
/// @notice The referenced order is not currently listed/valid.
error NotListed();
/// @notice The order signature does not recover to the expected maker.
error BadSignature();
/// @notice The order has been cancelled or already filled.
error OrderInactive();
/// @notice An EMT-paid fill costs more EMT than the buyer agreed to.
/// @dev The amount is computed from the TWAP oracle AT FILL TIME, so the
/// buyer's `maxEmtIn` is what bounds an oracle that moved between the
/// quote and the transaction. Named rather than left to a bare revert:
/// it means "re-quote and try again", not "this listing is dead".
/// @param need The EMT the fill costs now.
/// @param have The ceiling the buyer set.
error PriceMoved(uint256 need, uint256 have);
/// @notice A token delivered less than it was asked for.
/// @dev Only reachable on a fee-on-transfer or rebasing pay-in. Refused
/// rather than supported, because crediting more than arrived would
/// break `balanceOf(this) == reserveEmt + Σcredits` permanently and
/// strand the last withdrawer.
error InvalidPayment();
/// @notice A `cancelOrdersFor` batch is empty or longer than
/// `MAX_JANITOR_BATCH`. Bounded so one call can never run into the
/// block gas limit, and so a leaked janitor key cancels in bounded
/// steps that the API's unknown-cancel alarm sees between.
error BatchTooLarge(uint256 size, uint256 max);
}
/// @notice Errors specific to staking/vesting positions.
interface IPositionErrors {
/// @notice The referenced position id does not exist.
error InvalidPosition();
/// @notice The position has already been claimed.
error AlreadyClaimed();
/// @notice The position is still within its lock period.
error StillLocked();
}
project/contracts/interfaces/IStaking.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/// @title IStaking
/// @author EarthMeta 2026.
/// @notice Unified EMT staking: fixed-term flat-rate positions covering both the
/// legacy presale (signer-seeded) and normal (self-service) stakes, with
/// permissionless self-claim, admin-gated restaking, and solvency
/// accounting.
interface IStaking {
/// @notice A stake position. `restaked` marks a position CREATED by a restake
/// (which therefore cannot itself be restaked again — restake-once).
struct Stake {
uint256 amount;
uint64 startTime;
uint32 stakingPeriod; // days: 90 | 120 | 180 | 365
uint32 stage;
bool claimed;
bool restaked;
}
event Staked(
address indexed user,
uint256 indexed stakeId,
uint256 amount,
uint32 stakingPeriod,
uint32 stage,
uint64 startTime
);
event Claimed(address indexed user, uint256 indexed stakeId, uint256 principal, uint256 reward);
event ReStaked(address indexed user, uint256 indexed oldStakeId, uint256 indexed newStakeId, uint256 amount);
event RewardRatesSet(uint32 indexed stage, uint256[4] rates);
event ReserveFunded(address indexed from, uint256 amount);
event ExcessRecovered(address indexed to, uint256 amount);
event ReStakeOpenSet(bool open);
event ReStakeParamsSet(uint32 stage, uint256 deadline);
event StakesSeeded(uint256 count);
/// @notice A stored position was corrected by governance (adminFixStake).
/// Emits the full before/after so every edit is auditable on-chain.
event StakeAdminFixed(address indexed user, uint256 indexed stakeId, Stake oldStake, Stake newStake);
}
project/contracts/interfaces/IStakingPools.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/// @title IStakingPools
/// @author EarthMeta 2026.
/// @notice Restake pools on EarthmetaStaking: governance-created campaigns that
/// let the holders of chosen existing positions roll principal + reward
/// into a new fixed-term position at the pool's own rates. A pool id IS
/// the `stage` its positions are stored under, so every position a pool
/// creates is an ordinary `IStaking.Stake` — claimed, paged and indexed
/// exactly like the rest.
interface IStakingPools {
/// @notice One lock term of a pool.
/// @param periodDays Lock length in days (the position's `stakingPeriod`).
/// @param rateBps Reward for the WHOLE term in basis points of principal
/// (flat, not annualised — 1700 = 17% paid at maturity).
/// Immutable once the pool exists.
/// @param bonusUnit EMT (18 decimals) of new principal that earns ONE bonus
/// unit (e.g. one free City); 0 = this term has no bonus.
struct PoolTerm {
uint32 periodDays;
uint32 rateBps;
uint256 bonusUnit;
}
/// @notice Everything a pool is created with.
/// @param opensAt First second restakes are accepted.
/// @param closesAt First second they are refused again.
/// @param maxPrincipal Most principal the pool will ever admit (cumulative).
/// @param maxBonusUnits Most bonus units the pool will ever grant.
/// @param enforceSolvency Whether a stake or restake into the pool must
/// leave the contract holding at least its whole
/// liability (see `createPool`).
/// @param terms The lock terms, strictly ascending by `periodDays`.
/// @param sourceStages Stages whose positions may enter; each `< poolId`.
struct PoolInit {
uint64 opensAt;
uint64 closesAt;
uint256 maxPrincipal;
uint256 maxBonusUnits;
bool enforceSolvency;
PoolTerm[] terms;
uint32[] sourceStages;
}
/// @notice A pool's full configuration and running totals.
struct PoolView {
bool enabled;
bool enforceSolvency;
uint64 opensAt;
uint64 closesAt;
uint256 maxPrincipal;
uint256 principalIn;
uint256 rewardBooked;
uint256 maxBonusUnits;
uint256 bonusUnitsGranted;
PoolTerm[] terms;
uint32[] sourceStages;
}
/// @notice What `reStakeToPool` would create for the same arguments.
/// @param principal The new position's principal (Σ old principal + reward).
/// @param reward The reward it pays at maturity.
/// @param startTime When its lock starts (now, or the latest source maturity).
/// @param maturity When it becomes claimable.
/// @param bonusUnits The bonus units it is granted.
struct RestakeQuote {
uint256 principal;
uint256 reward;
uint64 startTime;
uint64 maturity;
uint256 bonusUnits;
}
/// @notice A pool was created (disabled — see `setPoolEnabled`). Its terms
/// and source stages follow as `PoolTermSet` / `PoolSourceStageSet`.
event PoolCreated(
uint32 indexed poolId,
uint64 opensAt,
uint64 closesAt,
uint256 maxPrincipal,
uint256 maxBonusUnits,
bool enforceSolvency
);
/// @notice A term was written at pool creation (rates never change after).
event PoolTermSet(uint32 indexed poolId, uint32 indexed periodDays, uint32 rateBps, uint256 bonusUnit);
/// @notice A term's bonus threshold was changed (future restakes only).
event PoolBonusUnitSet(uint32 indexed poolId, uint32 indexed periodDays, uint256 bonusUnit);
/// @notice A stage was allowed into / removed from a pool's sources.
event PoolSourceStageSet(uint32 indexed poolId, uint32 indexed stage, bool allowed);
/// @notice A pool was enabled or disabled.
event PoolEnabledSet(uint32 indexed poolId, bool enabled);
/// @notice A pool's window was changed.
event PoolWindowSet(uint32 indexed poolId, uint64 opensAt, uint64 closesAt);
/// @notice A pool's caps were changed.
event PoolCapsSet(uint32 indexed poolId, uint256 maxPrincipal, uint256 maxBonusUnits);
/// @notice A pool's solvency requirement was changed.
event PoolSolvencySet(uint32 indexed poolId, bool enforceSolvency);
/// @notice One or more positions were rolled into a new pool position. This
/// is the ONLY creation event of a pool position: `IStaking.Staked`
/// is deliberately not emitted for it (see `reStakeToPool`). The same
/// transaction emits one `IStaking.ReStaked` per position consumed.
/// @param user The staker.
/// @param poolId The pool (= the new position's `stage`).
/// @param stakeId The new position's id.
/// @param periodDays The chosen term.
/// @param principal The new principal (Σ old principal + old reward).
/// @param reward The reward booked for the new position.
/// @param startTime When the new lock starts.
/// @param bonusUnits Bonus units granted to this position (0 = none).
event PoolReStaked(
address indexed user,
uint32 indexed poolId,
uint256 indexed stakeId,
uint32 periodDays,
uint256 principal,
uint256 reward,
uint64 startTime,
uint256 bonusUnits
);
/// @notice EMT was added to a pool's reward budget — the reserve its fresh
/// stakes are paid their reward from.
/// @param poolId The pool.
/// @param from Who paid it in.
/// @param amount The EMT added.
/// @param budget The pool's budget after the funding.
event PoolRewardsFunded(uint32 indexed poolId, address indexed from, uint256 amount, uint256 budget);
/// @notice Unpromised EMT was taken out of a pool's reward budget.
/// @param poolId The pool.
/// @param to Who received it.
/// @param amount The EMT taken out.
/// @param budget The pool's budget after the withdrawal.
event PoolRewardsWithdrawn(uint32 indexed poolId, address indexed to, uint256 amount, uint256 budget);
/// @notice The most fresh principal a pool may take in total was set.
/// @param poolId The pool.
/// @param cap The new cap (0 = no fresh stakes).
event PoolFreshCapSet(uint32 indexed poolId, uint256 cap);
/// @notice NEW EMT was staked into a pool. This is the ONLY creation event
/// of a fresh pool position — `IStaking.Staked` is never emitted for
/// it. Same parameters as `PoolReStaked`, so one decoder reads both.
/// @param user The staker.
/// @param poolId The pool (= the new position's `stage`).
/// @param stakeId The new position's id.
/// @param periodDays The chosen term.
/// @param principal The EMT staked.
/// @param reward The reward booked for it, taken from the pool's budget.
/// @param startTime When the lock starts.
/// @param bonusUnits Bonus units granted to this position (0 = none).
event PoolStaked(
address indexed user,
uint32 indexed poolId,
uint256 indexed stakeId,
uint32 periodDays,
uint256 principal,
uint256 reward,
uint64 startTime,
uint256 bonusUnits
);
/// @notice No pool has this id.
error PoolNotFound(uint32 poolId);
/// @notice The id is already a pool.
error PoolExists(uint32 poolId);
/// @notice The pool is disabled or outside its window.
error PoolClosed(uint32 poolId);
/// @notice The stake or restake would take the pool past a principal cap:
/// the restake book's `maxPrincipal`, or `poolFreshCap` for new EMT.
error PoolCapExceeded(uint32 poolId, uint256 need, uint256 cap);
/// @notice The position's stage is not one of the pool's sources.
error NotEligible(uint256 stakeId, uint32 stage);
/// @notice The id list is empty, too long, or not strictly ascending.
error InvalidBatch();
/// @notice The stake or restake would grant fewer bonus units than the
/// caller required.
error BonusBelowMin(uint256 units, uint256 minUnits);
/// @notice The pool's reward budget holds less than is needed.
error RewardBudgetExceeded(uint32 poolId, uint256 need, uint256 have);
/// @notice A fresh position cannot be restaked.
error FreshNotRestakable(uint256 stakeId);
/// @notice The operation is refused on a fresh position.
error FreshPosition(uint256 stakeId);
}
project/contracts/lib/Roles.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/// @title Roles
/// @author EarthMeta 2026.
/// @notice Canonical AccessControl role identifiers shared across the suite.
/// Using one library keeps role ids identical everywhere and prevents
/// copy-paste typos between contracts.
library Roles {
/// @notice May mint/burn NFTs on a collection. Held by the Hub (and, during
/// migration, the MigrationMinter).
bytes32 internal constant MINTER_ROLE = keccak256("EM_MINTER");
/// @notice May move soulbound Country NFTs (presidency). Held by the Hub.
bytes32 internal constant HUB_ROLE = keccak256("EM_HUB");
/// @notice May seed historical state during the one-time migration. Revoked
/// after migration completes.
bytes32 internal constant MIGRATOR_ROLE = keccak256("EM_MIGRATOR");
/// @notice May pause/unpause money-touching contracts (fast emergency lever).
bytes32 internal constant PAUSER_ROLE = keccak256("EM_PAUSER");
/// @notice May settle fiat/on-ramp purchases through the marketplace voucher
/// path. Cannot price arbitrarily or drain funds.
bytes32 internal constant FIAT_OPERATOR_ROLE = keccak256("EM_FIAT_OPERATOR");
/// @notice May perform on-behalf-of convenience actions (e.g. claim for a
/// user) where funds still flow to the user, not the keeper.
bytes32 internal constant KEEPER_ROLE = keccak256("EM_KEEPER");
/// @notice May sweep collected treasury funds (e.g. escrowed USDT).
bytes32 internal constant TREASURER_ROLE = keccak256("EM_TREASURER");
/// @notice May adjust the oracle safety band. Held by the Timelock.
bytes32 internal constant PRICE_ADMIN_ROLE = keccak256("EM_PRICE_ADMIN");
/// @notice May sign primary-sale mint vouchers (operational key, not an owner).
bytes32 internal constant MERCHANT_ROLE = keccak256("EM_MERCHANT");
/// @notice May register city/land metadata on the Hub (held by PrimarySale so
/// it can label a freshly-sold asset without full hub admin power).
bytes32 internal constant REGISTRAR_ROLE = keccak256("EM_REGISTRAR");
/// @notice May map a land to its city on the Hub, WRITE-ONCE only
/// (`registerLandOnce` / `registerLandsOnce`): it can fill an unmapped
/// land with a minted city and nothing else — never overwrite a
/// mapping, never touch city metadata, levels, presidency or tokens.
/// Held by the API's hot registrar key (an EOA) so a land a city owner
/// creates in the app becomes sellable within a minute. Distinct from
/// EM_REGISTRAR (PrimarySale), whose `registerLand` overwrites.
/// NOT harmless if leaked: it can squat every unmapped (incl. future)
/// land id on a wrong city — a DoS on its sale and a redirect of its
/// 1% governor royalty — and, together with a stolen EM_MERCHANT key,
/// make the attacker the paid seller of such lands. See
/// `EarthmetaHub.registerLandOnce` for the threat and recovery.
bytes32 internal constant LAND_REGISTRAR_ROLE = keccak256("EM_LAND_REGISTRAR");
/// @notice May move a transfer-restricted collection (City/Land in
/// marketplace-only mode). Held by the EarthMeta marketplace so every
/// secondary sale routes through the on-chain fee split; no other
/// operator (OpenSea/Blur/etc.) can move a locked token.
///
/// GRANT THIS ONLY TO A CONTRACT WHOSE EVERY TRANSFER PATH IS GATED
/// ON THE HOLDER'S OWN SIGNATURE. On City and Land it is no longer a
/// routing permission: `EarthmetaERC721Base.isApprovedForAll` reports
/// every holder of this role as an approved operator for EVERY owner,
/// so the grantee can move any token in the collection as far as
/// ERC-721 is concerned — that is what removes the seller's
/// `setApprovalForAll`. Granting it to an EOA hands that EOA the
/// whole collection. Revoking it withdraws the implicit approval from
/// every holder in one transaction, and under the operator lock also
/// stops the grantee moving anything at all.
bytes32 internal constant MARKETPLACE_ROLE = keccak256("EM_MARKETPLACE");
/// @notice May edit per-token metadata URIs (image/attributes JSON) after
/// mint. A narrow content-management key: cannot mint, move tokens or
/// funds, or change a city's economic weight.
bytes32 internal constant METADATA_ROLE = keccak256("EM_METADATA");
/// @notice May mint ONE City per redeemed platform gift through
/// `PrimarySale.mintGift` — no payment, City class only, each
/// `giftRef` once, bounded by the admin-set `giftBudget`, the optional
/// per-day cap and the gift level cap. Held by the API's hot gift
/// key (an EOA funded with gas only). Deliberately NOT EM_MIGRATOR:
/// that role also opens `seedSold` and `mintFor` of every class with
/// no count limit. Loss ceiling if leaked: at most `giftBudget`
/// unsold cities, minted to addresses of the thief's choosing, until
/// the role is revoked, the budget zeroed or PrimarySale paused.
bytes32 internal constant GIFT_MINTER_ROLE = keccak256("EM_GIFT_MINTER");
/// @notice May cancel signed orders BY HASH on the marketplace
/// (`EarthmetaMarketplace.cancelOrdersFor`) — the platform cleaning up
/// the signatures it has already retired off its own book (a repriced
/// or removed listing, a changed, withdrawn or declined offer), so a
/// user never pays gas to kill a signature the site no longer shows.
/// Held by the API's hot janitor key (an EOA funded with gas only).
/// It can ONLY mark an order hash consumed: never fill, transfer,
/// move funds, touch a nonce or un-cancel anything. Loss ceiling if
/// leaked: live listings and offers cancelled (a DoS on the book —
/// sellers and bidders re-sign, nothing is lost) and the key's ETH,
/// until the role is revoked. The API pages on every janitor cancel
/// it did not request (`order_janitor.unknown_cancel`).
bytes32 internal constant ORDER_JANITOR_ROLE = keccak256("EM_ORDER_JANITOR");
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"npm/@openzeppelin/[email protected]/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.