Verified contractExactMIT
Exchange
Address0x032eb1bbd6be063a45b62528f9b8b66ca7e93fb7
- Balance
0 ETH
- Transactions
1,036
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,285,227
- Creation transaction
- 0x7cc0af7dd6…c473645db5
37 files
- src/europoor/Exchange.solmain24.38 KB
- ../node_modules/@openzeppelin/contracts/access/Ownable.sol3.1 KB
- ../node_modules/@openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- ../node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- ../node_modules/@openzeppelin/contracts/interfaces/IERC165.sol193 B
- ../node_modules/@openzeppelin/contracts/interfaces/IERC20.sol182 B
- ../node_modules/@openzeppelin/contracts/interfaces/IERC2981.sol1.11 KB
- ../node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol6.54 KB
- ../node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- ../node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- ../node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- ../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol16.1 KB
- ../node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol4.93 KB
- ../node_modules/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol997 B
- ../node_modules/@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol792 B
- ../node_modules/@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol1.92 KB
- ../node_modules/@openzeppelin/contracts/token/common/ERC2981.sol5.32 KB
- ../node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- ../node_modules/@openzeppelin/contracts/utils/Panic.sol1.97 KB
- ../node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
- ../node_modules/@openzeppelin/contracts/utils/Strings.sol19.28 KB
- ../node_modules/@openzeppelin/contracts/utils/cryptography/Hashes.sol1.03 KB
- ../node_modules/@openzeppelin/contracts/utils/cryptography/MerkleProof.sol24.34 KB
- ../node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol879 B
- ../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- ../node_modules/@openzeppelin/contracts/utils/math/Math.sol32.15 KB
- ../node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol34.94 KB
- ../node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol2.61 KB
- src/europoor/BlockHashes.sol1.02 KB
- src/europoor/BytecodeArtStore.sol3.96 KB
- src/europoor/CashDesk.sol4.65 KB
- src/europoor/Denominations.sol726 B
- src/europoor/EntryWindow.sol16.38 KB
- src/europoor/EuropoorRoot.sol14 KB
- src/europoor/PackedEconomicSchedule.sol10.05 KB
- src/europoor/SeedBook.sol5.89 KB
- src/final-sepolia/DeterministicEconomyPreview.sol4.15 KB
src/europoor/Exchange.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {DeterministicEconomyPreview} from "../final-sepolia/DeterministicEconomyPreview.sol";
import {CashDesk} from "./CashDesk.sol";
import {EntryWindow} from "./EntryWindow.sol";
import {EuropoorRoot} from "./EuropoorRoot.sol";
import {IEconomicSchedule} from "./PackedEconomicSchedule.sol";
import {SeedBook} from "./SeedBook.sol";
/// @notice Buy the seven ordinary families with CASH and redeem them back, at the live historical
/// price (one real day per game year, starting when paid entry opens). The price moves every second
/// in a straight line from this game year's price to the next one's, so it never jumps at the turn
/// of the day and nobody can buy just before a known jump and redeem just after it.
/// @dev Approved economics: CASH spent on a purchase moves into a reserve; redemptions are paid from
/// that reserve only and revert when it cannot cover them. The treasury prints CASH at 6.2% per game
/// year, compounding, for the 100 years of the series, and all of it feeds that reserve: new money
/// reaches holders only by selling positions back. So notes outstanding + credit + reserve equals
/// the CASH that entered plus what was printed. Each family has a supply cap derived from the paid
/// money stock that grows continuously at its own annual rate. While entry is still open the paid money
/// stock is still growing, so caps and printing follow it until it is fixed at the close.
/// The bank's portfolio: what is redeemed is not destroyed. The bank keeps it, as central banks keep the
/// bonds, mortgages or shares they buy (and Spain's Sareb the homes of the rescued banks), and it still
/// counts against the family's cap. It sells it back only while prices rise, at most BANK_SALE_BPS of
/// its portfolio per game year, released gradually across the day (so there is nothing to race for at
/// the turn of the day), at the live price, and before any fresh unit is issued. What it earns goes to
/// the reserve.
/// The daily buyback curve: within one game day, what the reserve pays out follows a constant-product
/// curve over the reserve it held at the day's first redemption, R0. With D the value (after the fee)
/// already sold to the bank today and g the value of this sale, the sale pays C(D + g) - C(D) where
/// C(x) = R0 * x / (R0 + x). A sale of 1% of R0 is paid 99%, of 10% about 91%; whatever is sold, the
/// day pays out less than R0, so the reserve can never be emptied, and splitting a sale in many pays
/// exactly the same as one (the payouts telescope). A new game day starts a new curve on the reserve
/// of that moment: the bank buys every day, it only slows a rush, as the price schedule is public.
contract Exchange is CashDesk {
uint256 private constant E8 = 1e8;
uint256 private constant RAY = 1e27;
uint8 public constant FIRST_FAMILY = 1;
uint8 public constant LAST_FAMILY = 7;
uint8 public constant FLOWER = 8;
uint8 public constant STONE = 9;
/// @notice Fixed redemption prices per whole unit. They never move with the game year.
uint256 public constant FLOWER_PRICE_E8 = 20 * E8;
uint256 public constant STONE_PRICE_E8 = 100 * E8;
/// @notice Printing runs for the hundred game years of the price series, then stops.
uint256 public constant PRINTING_SECONDS = 100 days;
/// @notice Opening cover: the reserve may always draw on at least 40% of the money that entered,
/// as the Reichsbank (1924) and the Fed (1913) had to cover 40% of their notes. It is an advance on
/// the century's printing, not extra money: printing books nothing new until it passes the cover
/// (about six game years at 6.2%), so the total printed by 2024 is unchanged.
uint256 public constant COVER_BPS = 4_000;
uint256 public constant PRINTING_PPM_PER_YEAR = 62_000;
/// @notice Share of an ordinary redemption's value that stays in the reserve instead of being paid.
uint256 public constant REDEMPTION_FEE_BPS = 500;
/// @notice Share of its portfolio of a family the bank may sell back per game year, while prices rise.
uint256 public constant BANK_SALE_BPS = 1_000;
uint8 public constant SOURCE_BOUGHT = 1;
uint8 public constant SOURCE_CHANGE = 3;
uint8 public constant SOURCE_REDEEMED = 4;
/// @dev Same source as a sacrifice's remainder: what was not redeemed, under the same origin.
uint8 public constant SOURCE_REMAINDER = 11;
EntryWindow public immutable entry;
IEconomicSchedule public immutable schedule;
SeedBook public immutable seeds;
/// @notice The game clock starts here: the opening of paid entry.
uint256 public immutable opensAt;
/// @notice CASH spent on purchases plus CASH printed so far, less what redemptions paid out.
uint256 public reserveE8;
/// @notice CASH the treasury has printed into the reserve so far.
uint256 public printedE8;
/// @notice CASH printed to redeem FLOWER and STONE. It never passes through the reserve.
uint256 public legacyPrintedE8;
/// @notice Units of each family redeemed and held by the bank, not yet sold back.
mapping(uint8 => uint256) public bankUnitsE8;
uint256[7] private _growthFactorRay;
uint256 private immutable _printingFactorRay;
/// @dev Per family: the game day (+1) of the bank's sales being tracked, that day's full allowance
/// (BANK_SALE_BPS of the portfolio at its first sale of the day), and what it has sold that day.
mapping(uint8 => uint256) private _saleDay;
mapping(uint8 => uint256) private _saleAllowanceE8;
mapping(uint8 => uint256) private _saleSoldE8;
/// @dev Game day + 1 of the curve below; 0 before the first redemption.
uint256 private _curveDay;
/// @notice R0: the reserve at the first redemption of the current curve's game day.
uint256 public curveBaseE8;
/// @notice D: value (after the fee) sold to the bank on the current curve's game day.
uint256 public curveDrawnE8;
error MarketNotOpen();
error DeadlineExpired();
error InvalidFamily();
error SlippageExceeded();
error CapExceeded();
error InsufficientNotes();
error InsufficientReserve();
error Unauthorized();
event Bought(
address indexed account,
uint256 indexed id,
uint8 indexed family,
uint256 year,
uint256 priceE8,
uint256 costE8,
uint256 unitsE8,
uint256[] spentNotes
);
event Redeemed(
address indexed account, uint256 indexed id, uint8 indexed family, uint256 year, uint256 priceE8, uint256 proceedsE8
);
/// @notice A redemption's draw on today's buyback curve: `valueE8` sold (after the fee) paid `proceedsE8`.
event CurveDraw(uint256 indexed day, uint256 valueE8, uint256 proceedsE8, uint256 baseE8, uint256 drawnE8);
event LegacyRedeemed(address indexed account, uint256 indexed id, uint8 indexed family, uint256 priceE8, uint256 proceedsE8);
event ReserveFunded(address indexed account, uint256 valueE8);
/// @notice Part of the next purchase's units came from the bank's portfolio.
event BankSold(uint8 indexed family, uint256 unitsE8, uint256 leftE8);
event Printed(uint256 valueE8, uint256 totalPrintedE8);
constructor(EuropoorRoot root_, EntryWindow entry_, address schedule_, SeedBook seeds_, uint256 maxNotes_)
CashDesk(root_, maxNotes_)
{
if (
address(entry_.root()) != address(root_) || address(seeds_.root()) != address(root_)
|| schedule_.code.length == 0
) revert InvalidConfiguration();
uint256 start = entry_.opensAt();
// The schedule must have been built for this exact entry window.
if (start == 0 || IScheduleStart(schedule_).startTimestamp() != start) revert InvalidConfiguration();
entry = entry_;
schedule = IEconomicSchedule(schedule_);
seeds = seeds_;
opensAt = start;
// FOOD, WATER, GOLD, EQUITIES, HOUSING, ENERGY, ART: cap growth per game year, in ppm.
uint256[7] memory rates = [uint256(20_000), 5_000, 15_000, 20_000, 10_000, 20_000, 10_000];
for (uint256 i; i < 7; ++i) {
_growthFactorRay[i] = DeterministicEconomyPreview.factorFromAnnualPpm(rates[i]);
}
_printingFactorRay = DeterministicEconomyPreview.factorFromAnnualPpm(PRINTING_PPM_PER_YEAR);
}
// ------------------------------------------------------------------- views
/// @notice Share of the paid money stock that sizes each family's initial cap; 84% in total.
function shareBps(uint8 family) public pure returns (uint256) {
if (family == 1) return 1600;
if (family == 2 || family == 6) return 1400;
if (family == 3 || family == 5) return 1000;
if (family == 4) return 1200;
if (family == 7) return 800;
revert InvalidFamily();
}
function currentYear() public view returns (uint256) {
return schedule.currentYear();
}
/// @notice The price of one whole unit right now: the schedule's live price for the seven ordinary
/// families (what buy and redeem use); FLOWER and STONE keep their year price (they redeem at a
/// fixed price, see FLOWER_PRICE_E8 and STONE_PRICE_E8).
function priceE8(uint8 family) public view returns (uint256) {
if (family == FLOWER || family == STONE) return schedule.priceAt(family, schedule.currentYear());
return schedule.livePriceE8(family);
}
/// @notice Maximum units of a family that may exist right now.
function cap(uint8 family) public view returns (uint256) {
if (block.timestamp < opensAt) revert MarketNotOpen();
// Money from FLOWER and STONE redemptions buys in the same families, so it sizes them too.
uint256 allotted = Math.mulDiv(entry.paidM0E8() + legacyPrintedE8, shareBps(family), 10_000);
uint256 baseCap = Math.mulDiv(allotted, E8, schedule.priceAt(family, 0));
// Caps grow for the hundred game years of the series and then stay; growing forever would
// eventually overflow the index and stop every purchase.
uint256 elapsed = Math.min(block.timestamp - opensAt, PRINTING_SECONDS);
uint256 index = DeterministicEconomyPreview.indexRay(_growthFactorRay[family - 1], elapsed);
return Math.mulDiv(baseCap, index, RAY);
}
/// @notice Units the bank can sell back right now. Each game day while prices rise it may sell
/// BANK_SALE_BPS of its portfolio (as it stood at its first sale of the day), released pro rata to
/// the seconds elapsed in the day, less what it already sold that day; zero while prices fall. At
/// the first second of a day nothing is released yet, so there is no race at the turn of the day.
function bankForSaleE8(uint8 family) public view returns (uint256) {
if (!schedule.rising()) return 0;
(uint256 allowance, uint256 sold) = _saleToday(family);
(uint256 s, uint256 duration) = schedule.dayProgress();
uint256 released = Math.mulDiv(allowance, s, duration);
return released > sold ? released - sold : 0;
}
/// @dev Today's full allowance and what was sold of it, before any sale today: a fresh allowance.
function _saleToday(uint8 family) private view returns (uint256 allowance, uint256 sold) {
if (_saleDay[family] == schedule.gameDay() + 1) return (_saleAllowanceE8[family], _saleSoldE8[family]);
return (Math.mulDiv(bankUnitsE8[family], BANK_SALE_BPS, 10_000), 0);
}
/// @notice Units a purchase can get right now: the bank's sale allowance plus room under the cap.
function availableE8(uint8 family) external view returns (uint256) {
return _availableE8(family);
}
/// @notice CASH accrued by the 6.2% printing since the game started, never less than the 40%
/// opening cover of the money that entered, and not yet booked. Grows with every mint.
function pendingPrintE8() public view returns (uint256) {
if (block.timestamp < opensAt) return 0;
uint256 money = entry.paidM0E8();
uint256 elapsed = Math.min(block.timestamp - opensAt, PRINTING_SECONDS);
uint256 projected = Math.mulDiv(money, DeterministicEconomyPreview.indexRay(_printingFactorRay, elapsed), RAY);
uint256 owed = Math.max(projected - money, Math.mulDiv(money, COVER_BPS, 10_000));
return owed > printedE8 ? owed - printedE8 : 0;
}
/// @notice What a redemption can draw on right now: the booked reserve plus unbooked printing.
function availableReserveE8() external view returns (uint256) {
return reserveE8 + pendingPrintE8();
}
/// @notice Today's buyback curve as the next redemption would see it: R0 and the value already sold
/// today (a new game day starts from the reserve of that moment, with nothing sold).
function redeemCurve() public view returns (uint256 baseE8, uint256 drawnE8) {
return _curveState(reserveE8 + pendingPrintE8());
}
/// @notice What selling `valueE8` (after the fee) to the bank pays right now, on today's curve.
function curvePayoutE8(uint256 valueE8) public view returns (uint256) {
(uint256 base, uint256 drawn) = redeemCurve();
return _curvePayout(base, drawn, valueE8);
}
/// @notice What a budget buys at the live price: whole E8 units, and their exact cost (never above the budget).
function quoteBuy(uint8 family, uint256 budgetE8) public view returns (uint256 unitsE8, uint256 costE8) {
uint256 price = priceE8(family);
unitsE8 = Math.mulDiv(budgetE8, E8, price);
costE8 = Math.mulDiv(unitsE8, price, E8, Math.Rounding.Ceil);
}
// ----------------------------------------------------------------- actions
/// @notice Spend selected CASH notes (plus any credit) on one new position; the rest comes back as change.
function buy(uint8 family, uint256 budgetE8, uint256 minUnitsE8, uint256 deadline, uint256[] calldata notes)
external
nonReentrant
returns (uint256 id)
{
_requireLive(deadline);
if (family < FIRST_FAMILY || family > LAST_FAMILY) revert InvalidFamily();
uint256 price = schedule.livePriceE8(family);
uint256 units = Math.mulDiv(budgetE8, E8, price);
if (units == 0) revert ZeroValue();
if (units < minUnitsE8) revert SlippageExceeded();
id = _buy(family, price, units, notes);
}
/// @notice Buy up to `unitsE8` at no more than `maxPriceE8` per unit: as many as can be had right
/// now (the bank's sale allowance plus room under the cap), and at least `minUnitsE8`, so a purchase
/// that lands after someone else took part of the supply still fills instead of reverting. Notes
/// and credit must cover `unitsE8` at the live price; what is not spent comes back as change.
function buyUpTo(
uint8 family,
uint256 unitsE8,
uint256 minUnitsE8,
uint256 maxPriceE8,
uint256 deadline,
uint256[] calldata notes
) external nonReentrant returns (uint256 id, uint256 boughtE8) {
_requireLive(deadline);
if (family < FIRST_FAMILY || family > LAST_FAMILY) revert InvalidFamily();
uint256 price = schedule.livePriceE8(family);
if (price > maxPriceE8) revert SlippageExceeded();
boughtE8 = Math.min(unitsE8, _availableE8(family));
if (boughtE8 < minUnitsE8) revert SlippageExceeded();
id = _buy(family, price, boughtE8, notes);
}
/// @notice Turn a whole position back into CASH: an ordinary family at the live price, if the
/// reserve can pay it; FLOWER or STONE at its fixed price, in newly printed CASH.
function redeem(uint256 id, uint256 minCashE8, uint256 deadline) external nonReentrant {
_requireLive(deadline);
(uint8 family,,, uint256 units,) = root.tokenRecord(id);
if (family == FLOWER || family == STONE) {
_redeemLegacy(id, family, units, minCashE8);
return;
}
_redeemOrdinary(id, family, units, units, minCashE8);
}
/// @notice Redeem only `unitsE8` of an ordinary position (for example what the reserve can pay
/// now); the rest comes back as a new position with the same origin, so it keeps its artwork.
function redeemPart(uint256 id, uint256 unitsE8, uint256 minCashE8, uint256 deadline) external nonReentrant {
_requireLive(deadline);
(uint8 family,,, uint256 units,) = root.tokenRecord(id);
if (unitsE8 == 0 || unitsE8 > units) revert ZeroValue();
_redeemOrdinary(id, family, units, unitsE8, minCashE8);
}
/// @notice Books the printing accrued so far into the reserve. Anyone may call it; redemptions do.
function print() public returns (uint256 valueE8) {
valueE8 = pendingPrintE8();
if (valueE8 == 0) return 0;
printedE8 += valueE8;
reserveE8 += valueE8;
emit Printed(valueE8, printedE8);
}
/// @notice What redeeming `unitsE8` of an ordinary `family` pays now: the live value less the 5% fee
/// (`feeE8`), paid on today's buyback curve (so a large sale is paid less than value - fee).
function quoteRedeem(uint8 family, uint256 unitsE8) public view returns (uint256 payoutE8, uint256 feeE8) {
uint256 value = Math.mulDiv(unitsE8, priceE8(family), E8);
feeE8 = Math.mulDiv(value, REDEMPTION_FEE_BPS, 10_000, Math.Rounding.Ceil);
payoutE8 = curvePayoutE8(value - feeE8);
}
/// @notice CASH another module of this collection already destroyed for the reserve (the market's
/// royalty). Only live modules that may burn CASH can call it, so it never creates money.
function creditReserve(uint256 valueE8) external {
uint8 permissions = root.modulePermissions(msg.sender);
if (msg.sender == address(this) || permissions >= 0x80 || permissions & root.BURN() == 0) revert Unauthorized();
if (valueE8 == 0) return;
reserveE8 += valueE8;
emit ReserveFunded(msg.sender, valueE8);
}
/// @notice Give CASH to the reserve that pays redemptions. A gift: it creates no claim.
function fundReserve(uint256[] calldata notes) external nonReentrant {
uint256 value = _burnNotes(notes);
if (value == 0) revert ZeroValue();
reserveE8 += value;
emit ReserveFunded(msg.sender, value);
}
// --------------------------------------------------------------- internals
/// @dev Units a purchase can get right now: what _supply accepts.
function _availableE8(uint8 family) private view returns (uint256) {
uint256 held = root.outstandingUnitsE8(family) + bankUnitsE8[family];
uint256 limit = cap(family);
return bankForSaleE8(family) + (limit > held ? limit - held : 0);
}
/// @dev Issue `units` at `price`, paid from credit first and then the given notes; change comes back.
function _buy(uint8 family, uint256 price, uint256 units, uint256[] calldata notes) private returns (uint256 id) {
uint256 cost = Math.mulDiv(units, price, E8, Math.Rounding.Ceil);
if (units == 0 || cost == 0) revert ZeroValue();
_supply(family, units);
uint256 funds = _takeCredit(msg.sender) + _burnNotes(notes);
if (funds < cost) revert InsufficientNotes();
reserveE8 += cost;
id = root.mintAsset(msg.sender, family, units, 0, SOURCE_BOUGHT);
seeds.record(id);
emit Bought(msg.sender, id, family, schedule.currentYear(), price, cost, units, notes);
_payCash(msg.sender, funds - cost, id, SOURCE_CHANGE);
}
/// @dev The bank's portfolio sells first; only the rest is freshly issued, under the cap. Units the
/// bank holds count against the cap, so selling them never makes room for more.
function _supply(uint8 family, uint256 units) private {
uint256 forSale = bankForSaleE8(family);
uint256 fromBank = Math.min(units, forSale);
if (root.outstandingUnitsE8(family) + bankUnitsE8[family] + (units - fromBank) > cap(family)) revert CapExceeded();
if (fromBank == 0) return;
uint256 day = schedule.gameDay() + 1;
if (_saleDay[family] != day) {
_saleDay[family] = day;
_saleAllowanceE8[family] = Math.mulDiv(bankUnitsE8[family], BANK_SALE_BPS, 10_000);
_saleSoldE8[family] = fromBank;
} else {
_saleSoldE8[family] += fromBank;
}
bankUnitsE8[family] -= fromBank;
emit BankSold(family, fromBank, bankUnitsE8[family]);
}
function _redeemOrdinary(uint256 id, uint8 family, uint256 units, uint256 take, uint256 minCashE8) private {
if (family < FIRST_FAMILY || family > LAST_FAMILY) revert InvalidFamily();
uint256 year = schedule.currentYear();
uint256 price = schedule.livePriceE8(family);
uint256 value = Math.mulDiv(take, price, E8);
// The fee never leaves the reserve: it is simply not paid out.
uint256 proceeds = _drawCurve(value - Math.mulDiv(value, REDEMPTION_FEE_BPS, 10_000, Math.Rounding.Ceil), minCashE8);
(,,,, uint256 origin) = root.tokenRecord(id);
root.burn(id, msg.sender);
// Not destroyed: the bank keeps what it bought.
bankUnitsE8[family] += take;
if (units > take) root.mintAsset(msg.sender, family, units - take, origin, SOURCE_REMAINDER);
seeds.settle(4);
emit Redeemed(msg.sender, id, family, year, price, proceeds);
_payCash(msg.sender, _takeCredit(msg.sender) + proceeds, id, SOURCE_REDEEMED);
}
/// @dev FLOWER and STONE never cost CASH, so they have no claim on the reserve: their CASH is new.
function _redeemLegacy(uint256 id, uint8 family, uint256 units, uint256 minCashE8) private {
uint256 price = family == FLOWER ? FLOWER_PRICE_E8 : STONE_PRICE_E8;
uint256 proceeds = Math.mulDiv(units, price, E8);
if (proceeds == 0) revert ZeroValue();
if (proceeds < minCashE8) revert SlippageExceeded();
legacyPrintedE8 += proceeds;
root.burn(id, msg.sender);
emit LegacyRedeemed(msg.sender, id, family, price, proceeds);
_payCash(msg.sender, _takeCredit(msg.sender) + proceeds, id, SOURCE_REDEEMED);
}
/// @dev Pays `gross` (value after the fee) out of the reserve on today's curve, after booking the printing.
function _drawCurve(uint256 gross, uint256 minCashE8) private returns (uint256 proceeds) {
print();
(uint256 base, uint256 drawn) = _curveState(reserveE8);
proceeds = _curvePayout(base, drawn, gross);
if (proceeds == 0) revert ZeroValue();
// After the curve: the seller's protection if other sales landed first today.
if (proceeds < minCashE8) revert SlippageExceeded();
// Unreachable by construction (a day pays out less than R0); kept as a belt.
if (proceeds > reserveE8) revert InsufficientReserve();
uint256 day = schedule.gameDay();
_curveDay = day + 1;
curveBaseE8 = base;
curveDrawnE8 = drawn + gross;
reserveE8 -= proceeds;
emit CurveDraw(day, gross, proceeds, base, drawn + gross);
}
/// @dev (R0, D) for the current game day: the stored curve if it is today's, else a new day's.
function _curveState(uint256 reserveNow) private view returns (uint256 base, uint256 drawn) {
if (_curveDay == schedule.gameDay() + 1) return (curveBaseE8, curveDrawnE8);
return (reserveNow, 0);
}
/// @dev C(x) = base * x / (base + x), rounded down; a sale pays C(D + g) - C(D), so split sales telescope.
function _curve(uint256 base, uint256 x) private pure returns (uint256) {
return base == 0 ? 0 : Math.mulDiv(base, x, base + x);
}
function _curvePayout(uint256 base, uint256 drawn, uint256 valueE8) private pure returns (uint256) {
return _curve(base, drawn + valueE8) - _curve(base, drawn);
}
function _requireLive(uint256 deadline) private view {
if (block.timestamp < opensAt) revert MarketNotOpen();
if (block.timestamp > deadline) revert DeadlineExpired();
}
}
interface IScheduleStart {
function startTimestamp() external view returns (uint256);
}
../node_modules/@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
../node_modules/@openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
../node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
../node_modules/@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
../node_modules/@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
../node_modules/@openzeppelin/contracts/interfaces/IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC2981.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*
* NOTE: ERC-2981 allows setting the royalty to 100% of the price. In that case all the price would be sent to the
* royalty receiver and 0 tokens to the seller. Contracts dealing with royalty should consider empty transfers.
*/
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) external view returns (address receiver, uint256 royaltyAmount);
}
../node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
../node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
../node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
../node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @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 _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @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 _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* 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 {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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 rely 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 rely 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}.
* Opposedly, 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 high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "./IERC721.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {ERC721Utils} from "./utils/ERC721Utils.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
mapping(uint256 tokenId => address) private _owners;
mapping(address owner => uint256) private _balances;
mapping(uint256 tokenId => address) private _tokenApprovals;
mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc IERC721
function balanceOf(address owner) public view virtual returns (uint256) {
if (owner == address(0)) {
revert ERC721InvalidOwner(address(0));
}
return _balances[owner];
}
/// @inheritdoc IERC721
function ownerOf(uint256 tokenId) public view virtual returns (address) {
return _requireOwned(tokenId);
}
/// @inheritdoc IERC721Metadata
function name() public view virtual returns (string memory) {
return _name;
}
/// @inheritdoc IERC721Metadata
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/// @inheritdoc IERC721Metadata
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
_requireOwned(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/// @inheritdoc IERC721
function approve(address to, uint256 tokenId) public virtual {
_approve(to, tokenId, _msgSender());
}
/// @inheritdoc IERC721
function getApproved(uint256 tokenId) public view virtual returns (address) {
_requireOwned(tokenId);
return _getApproved(tokenId);
}
/// @inheritdoc IERC721
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/// @inheritdoc IERC721
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return _operatorApprovals[owner][operator];
}
/// @inheritdoc IERC721
function transferFrom(address from, address to, uint256 tokenId) public virtual {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
address previousOwner = _update(to, tokenId, _msgSender());
if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/// @inheritdoc IERC721
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/// @inheritdoc IERC721
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
transferFrom(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
* core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
*/
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
return _tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
* particular (ignoring whether it is owned by `owner`).
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
return
spender != address(0) &&
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
}
/**
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
* Reverts if:
* - `spender` does not have approval from `owner` for `tokenId`.
* - `spender` does not have approval to manage all of `owner`'s assets.
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
if (!_isAuthorized(owner, spender, tokenId)) {
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else {
revert ERC721InsufficientApproval(spender, tokenId);
}
}
}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
*
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
* remain consistent with one another.
*/
function _increaseBalance(address account, uint128 value) internal virtual {
unchecked {
_balances[account] += value;
}
}
/**
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
*
* Emits a {Transfer} event.
*
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
*/
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
address from = _ownerOf(tokenId);
// Perform (optional) operator check
if (auth != address(0)) {
_checkAuthorized(from, auth, tokenId);
}
// Execute the update
if (from != address(0)) {
// Clear approval. No need to re-authorize or emit the Approval event
_approve(address(0), tokenId, address(0), false);
unchecked {
_balances[from] -= 1;
}
}
if (to != address(0)) {
unchecked {
_balances[to] += 1;
}
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
return from;
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner != address(0)) {
revert ERC721InvalidSender(address(0));
}
}
/**
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal {
address previousOwner = _update(address(0), tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
* are aware of the ERC-721 standard to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is like {safeTransferFrom} in the sense that it invokes
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `tokenId` token must exist and be owned by `from`.
* - `to` cannot be the zero address.
* - `from` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId) internal {
_safeTransfer(from, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
* either the owner of the token, or approved to operate on all tokens held by this owner.
*
* Emits an {Approval} event.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address to, uint256 tokenId, address auth) internal {
_approve(to, tokenId, auth, true);
}
/**
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
* emitted in the context of transfers.
*/
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
// Avoid reading the owner unless necessary
if (emitEvent || auth != address(0)) {
address owner = _requireOwned(tokenId);
// We do not use _isAuthorized because single-token approvals should not be able to call approve
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
revert ERC721InvalidApprover(auth);
}
if (emitEvent) {
emit Approval(owner, to, tokenId);
}
}
_tokenApprovals[tokenId] = to;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Requirements:
* - operator can't be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
if (operator == address(0)) {
revert ERC721InvalidOperator(operator);
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
* Returns the owner.
*
* Overrides to ownership logic should be done to {_ownerOf}.
*/
function _requireOwned(uint256 tokenId) internal view returns (address) {
address owner = _ownerOf(tokenId);
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
return owner;
}
}
../node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
../node_modules/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity >=0.5.0;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
../node_modules/@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity >=0.6.2;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
../node_modules/@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/utils/ERC721Utils.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";
/**
* @dev Library that provide common ERC-721 utility functions.
*
* See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
*
* _Available since v5.1._
*/
library ERC721Utils {
/**
* @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
*
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
* Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC721Received(
address operator,
address from,
address to,
uint256 tokenId,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
// Token rejected
revert IERC721Errors.ERC721InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC721Receiver implementer
revert IERC721Errors.ERC721InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(reason, 0x20), mload(reason))
}
}
}
}
}
}
../node_modules/@openzeppelin/contracts/token/common/ERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/common/ERC2981.sol)
pragma solidity ^0.8.20;
import {IERC2981} from "../../interfaces/IERC2981.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the ERC. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 tokenId => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev The default royalty set is invalid (eg. (numerator / denominator) >= 1).
*/
error ERC2981InvalidDefaultRoyalty(uint256 numerator, uint256 denominator);
/**
* @dev The default royalty receiver is invalid.
*/
error ERC2981InvalidDefaultRoyaltyReceiver(address receiver);
/**
* @dev The royalty set for a specific `tokenId` is invalid (eg. (numerator / denominator) >= 1).
*/
error ERC2981InvalidTokenRoyalty(uint256 tokenId, uint256 numerator, uint256 denominator);
/**
* @dev The royalty receiver for `tokenId` is invalid.
*/
error ERC2981InvalidTokenRoyaltyReceiver(uint256 tokenId, address receiver);
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/// @inheritdoc IERC2981
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) public view virtual returns (address receiver, uint256 amount) {
RoyaltyInfo storage _royaltyInfo = _tokenRoyaltyInfo[tokenId];
address royaltyReceiver = _royaltyInfo.receiver;
uint96 royaltyFraction = _royaltyInfo.royaltyFraction;
if (royaltyReceiver == address(0)) {
royaltyReceiver = _defaultRoyaltyInfo.receiver;
royaltyFraction = _defaultRoyaltyInfo.royaltyFraction;
}
uint256 royaltyAmount = (salePrice * royaltyFraction) / _feeDenominator();
return (royaltyReceiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
uint256 denominator = _feeDenominator();
if (feeNumerator > denominator) {
// Royalty fee will exceed the sale price
revert ERC2981InvalidDefaultRoyalty(feeNumerator, denominator);
}
if (receiver == address(0)) {
revert ERC2981InvalidDefaultRoyaltyReceiver(address(0));
}
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual {
uint256 denominator = _feeDenominator();
if (feeNumerator > denominator) {
// Royalty fee will exceed the sale price
revert ERC2981InvalidTokenRoyalty(tokenId, feeNumerator, denominator);
}
if (receiver == address(0)) {
revert ERC2981InvalidTokenRoyaltyReceiver(tokenId, address(0));
}
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
../node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
../node_modules/@openzeppelin/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
../node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
../node_modules/@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
../node_modules/@openzeppelin/contracts/utils/cryptography/Hashes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
*
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
*
* NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
*/
function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
../node_modules/@openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
pragma solidity ^0.8.20;
import {Hashes} from "./Hashes.sol";
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*
* IMPORTANT: Consider memory side-effects when using custom hashing functions
* that access memory in an unsafe way.
*
* NOTE: This library supports proof verification for merkle trees built using
* custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
* leaf inclusion in trees built using non-commutative hashing functions requires
* additional logic that is not supported by this library.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProof(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function processProof(
bytes32[] memory proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProofCalldata(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function processProofCalldata(
bytes32[] calldata proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProof(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
}
../node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.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 ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
../node_modules/@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
../node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
../node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/europoor/BlockHashes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @notice Block hashes for the last 8191 blocks (about 27 hours), not just the last 256: the EVM
/// serves 256 itself and the EIP-2935 history contract (live on Ethereum since Pectra) serves the rest.
/// Returns zero for a block that is not in the past or is older than that window, or when the chain
/// has no history contract (a staticcall to an empty address returns no data).
library BlockHashes {
address internal constant HISTORY = 0x0000F90827F1C53a10cb7A02335B175320002935;
uint256 internal constant WINDOW = 8191;
function get(uint256 number) internal view returns (bytes32 hash) {
if (number >= block.number) return bytes32(0);
uint256 age = block.number - number;
if (age <= 256) return blockhash(number);
if (age > WINDOW) return bytes32(0);
(bool ok, bytes memory data) = HISTORY.staticcall(abi.encode(number));
if (ok && data.length == 32) hash = abi.decode(data, (bytes32));
}
}
src/europoor/BytecodeArtStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
/// @dev Runtime is exactly STOP || payload: inert, immutable and EIP-170 bounded.
contract ArtDataChunk {
constructor(bytes memory payload) {
require(payload.length > 0 && payload.length <= 24575, 'chunk size');
bytes memory runtime = bytes.concat(hex'00', payload);
assembly ('memory-safe') { return(add(runtime, 32), mload(runtime)) }
}
}
/// @notice Onchain store for artwork bytes: the owner appends the files of a fixed manifest, then
/// seals it. After the seal the catalog is immutable and every read is re-hashed against the manifest.
contract BytecodeArtStore is Ownable {
uint256 public constant MAX_PAYLOAD = 24575;
bytes32 public immutable manifestSha256;
bool public isSealed;
uint256 public totalBytes;
struct Chunk { address pointer; bytes32 codeHash; }
struct File { uint256 offset; uint256 length; bytes32 sha256Hash; }
Chunk[] public chunks;
File[] public files;
event ChunkAdded(uint256 indexed index, address pointer, bytes32 runtimeSha256);
event FileAdded(uint256 indexed index, uint256 offset, uint256 length, bytes32 sha256Hash);
event Sealed(bytes32 manifestSha256);
constructor(address publisher, bytes32 manifest) Ownable(publisher) {
require(block.chainid == 1 || block.chainid == 11155111 || block.chainid == 31337, 'unsupported chain');
require(manifest != 0, 'manifest required');
manifestSha256 = manifest;
}
modifier unsealed() { require(!isSealed, 'sealed'); _; }
function chunkCount() external view returns (uint256) { return chunks.length; }
function fileCount() external view returns (uint256) { return files.length; }
function appendChunk(bytes memory payload) external onlyOwner unsealed returns (address pointer) {
require(totalBytes % MAX_PAYLOAD == 0, 'previous chunk short');
pointer = address(new ArtDataChunk(payload));
chunks.push(Chunk(pointer, pointer.codehash));
totalBytes += payload.length;
emit ChunkAdded(chunks.length - 1, pointer, sha256(pointer.code));
}
function addFile(uint256 offset, uint256 length, bytes32 expectedHash)
external onlyOwner unsealed returns (uint256 id)
{
bytes memory data = _read(offset, length);
require(sha256(data) == expectedHash, 'file hash');
id = files.length;
files.push(File(offset, length, expectedHash));
emit FileAdded(id, offset, length, expectedHash);
}
function seal() external onlyOwner unsealed {
require(files.length > 0, 'empty catalog');
isSealed = true;
emit Sealed(manifestSha256);
}
function read(uint256 id) external view returns (bytes memory data) {
require(id < files.length, 'unknown file');
File memory file = files[id];
data = _read(file.offset, file.length);
require(sha256(data) == file.sha256Hash, 'file hash');
}
function _read(uint256 offset, uint256 length) private view returns (bytes memory out) {
require(length > 0 && length <= 65536 && offset <= totalBytes && length <= totalBytes - offset, 'file bounds');
out = new bytes(length);
uint256 copied;
while (copied < length) {
uint256 at = offset + copied;
Chunk memory chunk = chunks[at / MAX_PAYLOAD];
address pointer = chunk.pointer;
require(pointer.codehash == chunk.codeHash, 'changed bytecode');
uint256 start = at % MAX_PAYLOAD;
uint256 take = pointer.code.length - 1 - start;
if (take > length - copied) take = length - copied;
require(take > 0, 'truncated chunk');
assembly ('memory-safe') { extcodecopy(pointer, add(add(out, 32), copied), add(start, 1), take) }
copied += take;
}
}
}
src/europoor/CashDesk.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Denominations} from "./Denominations.sol";
import {EuropoorRoot} from "./EuropoorRoot.sol";
/// @notice What every module that takes and pays CASH shares: spending a holder's own notes, paying
/// out the fewest notes, and keeping what cannot be a note yet as credit.
/// @dev Credit is per module: sub-cent remainders and payouts beyond one transaction's note limit.
abstract contract CashDesk is ReentrancyGuard {
uint8 public constant SOURCE_CREDIT = 5;
/// @dev A market sale pays out three times (royalty, seller, buyer's change), about 56k gas per
/// note; 90 notes each keeps the worst sale near 15.6M gas, under the 16.7M per-transaction cap
/// (EIP-7825) with margin (96 measured 16.58M).
uint256 public constant MAX_NOTES_LIMIT = 90;
EuropoorRoot public immutable root;
uint256 public immutable maxNotes;
/// @notice CASH owed to a holder that is not in notes. Counted first on their next action here,
/// or claimed as notes.
mapping(address => uint256) public creditE8;
uint256 public totalCreditE8;
error InvalidConfiguration();
error NotCash();
error ZeroValue();
/// @dev valueE8 arrived as the consecutive notes firstSerial .. firstSerial + noteCount - 1; creditE8 was added to credit.
event CashPaid(address indexed account, uint256 valueE8, uint256 firstSerial, uint256 noteCount, uint256 creditE8);
/// @notice noteCount notes worth valueE8 were burned into the account's credit here.
event CreditDeposited(address indexed account, uint256 valueE8, uint256 noteCount);
constructor(EuropoorRoot root_, uint256 maxNotes_) {
if (address(root_).code.length == 0 || maxNotes_ < 2 || maxNotes_ > MAX_NOTES_LIMIT) revert InvalidConfiguration();
root = root_;
maxNotes = maxNotes_;
}
/// @notice Receive outstanding credit as notes, up to the per-transaction note limit.
function claimCredit() external nonReentrant {
uint256 credit = _takeCredit(msg.sender);
if (credit == 0) revert ZeroValue();
_payCash(msg.sender, credit, 0, SOURCE_CREDIT);
}
/// @notice Burn your own notes into your credit here, so a later action can spend more than one
/// transaction can burn in notes (each burned note costs gas; the largest is 500). Deposit over as
/// many transactions as needed: every action here counts credit first, and claimCredit turns it
/// back into notes.
function depositNotes(uint256[] calldata notes) external nonReentrant {
uint256 value = _burnNotes(notes);
if (value == 0) revert ZeroValue();
creditE8[msg.sender] += value;
totalCreditE8 += value;
emit CreditDeposited(msg.sender, value, notes.length);
}
function _takeCredit(address account) internal returns (uint256 credit) {
credit = creditE8[account];
if (credit != 0) {
creditE8[account] = 0;
totalCreditE8 -= credit;
}
}
/// @dev The root only burns a token for the owner named here, so a note that is not the
/// caller's, was already spent, or appears twice in the list reverts the whole action.
function _burnNotes(uint256[] calldata notes) internal returns (uint256 value) {
for (uint256 i; i < notes.length; ++i) {
(uint8 family,, uint256 face,,) = root.tokenRecord(notes[i]);
if (family != root.CASH()) revert NotCash();
root.burn(notes[i], msg.sender);
value += face;
}
}
/// @dev Fewest notes first; whatever does not fit in notes this time stays as credit.
function _payCash(address to, uint256 value, uint256 originId, uint8 source) internal {
if (value == 0) return;
uint256 firstSerial = root.nextSerial();
uint256 slots = maxNotes;
uint256 credit = value;
uint256[15] memory faces = Denominations.all();
for (uint256 i; i < Denominations.COUNT && slots != 0; ++i) {
uint256 count = Math.min(credit / faces[i], slots);
for (uint256 n; n < count; ++n) {
root.mintNote(to, faces[i], originId, source);
}
credit -= count * faces[i];
slots -= count;
}
if (credit != 0) {
creditE8[to] += credit;
totalCreditE8 += credit;
}
emit CashPaid(to, value - credit, firstSerial, maxNotes - slots, credit);
}
}
src/europoor/Denominations.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @notice The fifteen CASH faces in E8, largest first: seven notes (500..5) and eight coins (2..0.01).
library Denominations {
uint256 internal constant COUNT = 15;
uint256 internal constant NOT_FOUND = type(uint256).max;
function all() internal pure returns (uint256[15] memory) {
return [uint256(500e8), 200e8, 100e8, 50e8, 20e8, 10e8, 5e8, 2e8, 1e8, 5e7, 2e7, 1e7, 5e6, 2e6, 1e6];
}
function indexOf(uint256 faceValueE8) internal pure returns (uint256) {
uint256[15] memory faces = all();
for (uint256 i; i < COUNT; ++i) {
if (faces[i] == faceValueE8) return i;
}
return NOT_FOUND;
}
}
src/europoor/EntryWindow.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Denominations} from "./Denominations.sol";
import {EuropoorRoot} from "./EuropoorRoot.sol";
/// @notice The part of a Chainlink price feed this contract reads.
interface IPriceFeed {
function decimals() external view returns (uint8);
function latestRoundData() external view returns (uint80, int256, uint256, uint256, uint80);
}
/// @notice Paid entry: EURC in, the same nominal value out as individual CASH notes.
/// @dev The root owner schedules the 100-hour window with open(startsAt), not at deployment, so the
/// graph and the game can be deployed, bound and reviewed first. The game clock starts at the same
/// instant (year 1924 at startsAt), so the mint and the century go live together. Opening is
/// one-shot and the window is fixed.
/// EURC goes straight to the recipient; CASH carries no refund or redemption right.
/// Nobody can pay until the root's module set is sealed, so no module that mints can be bound once
/// public money has come in. open() itself cannot require the seal: the exchange reads opensAt when it
/// is deployed, and it must be bound before the seal. The recipient cannot pay: its payment would come
/// straight back to it, minting EP for free.
/// Who may pay: while an allowlist root is set, only listed wallets. A wallet proves itself once, with a
/// Merkle proof on its first payment, and stays admitted for the rest of the window; later orders need
/// no proof. The list is built offchain (holders, collaborations, claimed spots). With no root set,
/// anyone may pay.
/// Paying with ETH: once the owner sets two Chainlink feeds (ETH/USD and EUR/USD) before the window
/// opens, payEth turns the ETH sent into whole euros at the feeds' current price, mints that many EP as
/// if the same EURC had been paid, and forwards all the ETH to the same recipient. The feeds are fixed
/// for the whole window. The price is read onchain, never taken from the caller, so nobody can choose
/// the rate; the caller only sets the least EP it accepts.
contract EntryWindow is ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant WINDOW = 100 hours;
/// @notice How far ahead the window may be scheduled; guards against a mistyped start.
uint256 public constant MAX_LEAD = 30 days;
uint256 public constant E8_PER_EURC_MINOR = 100;
uint8 public constant SOURCE_PAID = 1;
/// @notice ETH payments mint whole euros; what is left below one euro goes to the recipient too.
uint256 public constant EURC_MINOR_PER_EURO = 1e6;
/// @notice Oldest price accepted from each feed: their heartbeats (1 h, 24 h) plus a margin.
uint256 public constant ETH_USD_MAX_AGE = 2 hours;
uint256 public constant EUR_USD_MAX_AGE = 26 hours;
EuropoorRoot public immutable root;
IERC20 public immutable paymentToken;
address public immutable eurcRecipient;
uint256 public immutable maxNotes;
uint256 public opensAt;
uint256 public closesAt;
/// @notice Total CASH issued through paid entry. It grows while the window is open (the game
/// already runs then) and is the fixed initial money stock once it closes.
uint256 public paidM0E8;
/// @notice Orders are scoped to their payer, so nobody else can spend or block an order id.
mapping(address => mapping(bytes32 => uint256)) public paidOrderAmount;
/// @notice Merkle root of the wallets allowed to pay; zero leaves entry open to anyone.
/// Leaf: keccak256(bytes.concat(keccak256(abi.encode(wallet)))), pairs hashed sorted.
bytes32 public allowlistRoot;
/// @notice Wallets that already proved they are listed.
mapping(address => bool) public admitted;
/// @notice Chainlink ETH/USD and EUR/USD; both zero means ETH is not accepted.
IPriceFeed public ethUsdFeed;
IPriceFeed public eurUsdFeed;
error InvalidConfiguration();
error Unauthorized();
error AlreadyOpened();
error NotReady();
error OutsidePaidWindow();
error InvalidAmount();
error OrderAlreadyUsed();
error OutputCap();
error UnrepresentableValue();
error InexactPayment();
error NotAllowlisted();
error EthNotAccepted();
error StalePrice();
error PriceMoved();
error RecipientCannotPay();
event Opened(uint256 opensAt, uint256 closesAt);
event AllowlistSet(bytes32 root);
event Admitted(address indexed wallet);
event EthPricingSet(address ethUsdFeed, address eurUsdFeed);
/// @dev Emitted next to Paid for an ETH payment: `weiPaid` bought `Paid.eurcMinor` worth of EP.
event PaidEth(bytes32 indexed order, address indexed payer, uint256 weiPaid);
/// @dev The order's notes are the consecutive serials firstSerial .. firstSerial + noteCount - 1.
event Paid(
bytes32 indexed order,
address indexed payer,
uint256 eurcMinor,
uint256 valueE8,
uint256 firstSerial,
uint256 noteCount
);
constructor(EuropoorRoot root_, address token, address recipient, uint256 maxNotes_) {
if (
address(root_).code.length == 0 || token.code.length == 0 || recipient == address(0)
|| recipient == token || recipient == address(root_) || recipient == address(this) || maxNotes_ < 2
|| maxNotes_ > 90 || IERC20Metadata(token).decimals() != 6
) revert InvalidConfiguration();
root = root_;
paymentToken = IERC20(token);
eurcRecipient = recipient;
maxNotes = maxNotes_;
}
/// @dev Window length; fixed at WINDOW here, shortened only by the test-network EntryWindowTest.
function _window() internal view virtual returns (uint256) {
return WINDOW;
}
/// @notice Schedules the one and only 100-hour window to start at startsAt (now or later).
/// Requires this module and the CASH art to be bound. Payments also wait for the module seal.
function open(uint256 startsAt) external {
if (msg.sender != root.owner()) revert Unauthorized();
if (opensAt != 0) revert AlreadyOpened();
if (startsAt < block.timestamp || startsAt > block.timestamp + MAX_LEAD) revert InvalidConfiguration();
if (
root.modulePermissions(address(this)) != root.MINT_NOTE()
|| address(root.rendererOf(root.CASH())) == address(0)
) revert NotReady();
opensAt = startsAt;
closesAt = startsAt + _window();
emit Opened(opensAt, closesAt);
}
/// @notice Sets or replaces the allowlist (zero opens entry to everyone). Possible until the window
/// closes, so late collaborations can be added. Wallets already admitted stay admitted.
function setAllowlist(bytes32 root_) external {
if (msg.sender != root.owner()) revert Unauthorized();
if (closesAt != 0 && block.timestamp >= closesAt) revert OutsidePaidWindow();
allowlistRoot = root_;
emit AllowlistSet(root_);
}
/// @notice Sets the two Chainlink feeds that price ETH payments, or clears both to refuse ETH.
/// Only before the window opens, so the rate source cannot change during the mint.
function setEthPricing(address ethUsd, address eurUsd) external {
if (msg.sender != root.owner()) revert Unauthorized();
if (opensAt != 0) revert AlreadyOpened();
if ((ethUsd == address(0)) != (eurUsd == address(0))) revert InvalidConfiguration();
if (ethUsd != address(0)) {
if (ethUsd.code.length == 0 || eurUsd.code.length == 0) revert InvalidConfiguration();
if (IPriceFeed(ethUsd).decimals() > 18 || IPriceFeed(eurUsd).decimals() > 18) revert InvalidConfiguration();
}
ethUsdFeed = IPriceFeed(ethUsd);
eurUsdFeed = IPriceFeed(eurUsd);
emit EthPricingSet(ethUsd, eurUsd);
}
/// @notice The EURC amount (6 decimals, whole euros) that `weiAmount` pays for right now.
function eurcForEth(uint256 weiAmount) public view returns (uint256) {
(uint256 ethUsd, uint256 ethScale, uint256 eurUsd, uint256 eurScale) = _prices();
// wei * (ethUsd / ethScale) / (eurUsd / eurScale) euros, in EURC minor units (1e6 per euro).
uint256 minor = Math.mulDiv(weiAmount, ethUsd * eurScale, eurUsd * ethScale * 1e12);
return minor - minor % EURC_MINOR_PER_EURO;
}
/// @notice The least wei that pays for `eurcMinor` (whole euros) at the current price.
function ethForEurc(uint256 eurcMinor) external view returns (uint256) {
(uint256 ethUsd, uint256 ethScale, uint256 eurUsd, uint256 eurScale) = _prices();
return Math.mulDiv(eurcMinor, eurUsd * ethScale * 1e12, ethUsd * eurScale, Math.Rounding.Ceil);
}
/// @notice Whether `wallet` may pay now with `proof` (an empty proof once admitted, or with no list).
function canPay(address wallet, bytes32[] calldata proof) external view returns (bool) {
return allowlistRoot == bytes32(0) || admitted[wallet] || MerkleProof.verifyCalldata(proof, allowlistRoot, _leaf(wallet));
}
/// @notice Pay with an explicit choice of faces: 50+50 is allowed despite a 100 denomination.
function pay(bytes32 order, uint256 eurcMinor, uint256[] calldata facesE8) external nonReentrant {
_admit(new bytes32[](0));
uint256[] memory faces = facesE8;
_pay(order, eurcMinor, faces);
}
/// @notice The same, for a listed wallet's first payment.
function pay(bytes32 order, uint256 eurcMinor, uint256[] calldata facesE8, bytes32[] calldata proof)
external
nonReentrant
{
_admit(proof);
uint256[] memory faces = facesE8;
_pay(order, eurcMinor, faces);
}
/// @notice Pay and receive the fewest notes that represent the amount.
function payAuto(bytes32 order, uint256 eurcMinor) external nonReentrant {
_admit(new bytes32[](0));
_pay(order, eurcMinor, breakdown(eurcMinor));
}
/// @notice The same, for a listed wallet's first payment.
function payAuto(bytes32 order, uint256 eurcMinor, bytes32[] calldata proof) external nonReentrant {
_admit(proof);
_pay(order, eurcMinor, breakdown(eurcMinor));
}
/// @notice Pay with ETH: mints the whole euros msg.value buys now, at least `minEurcMinor`.
function payEth(bytes32 order, uint256 minEurcMinor) external payable nonReentrant {
_admit(new bytes32[](0));
_payEth(order, minEurcMinor);
}
/// @notice The same, for a listed wallet's first payment.
function payEth(bytes32 order, uint256 minEurcMinor, bytes32[] calldata proof) external payable nonReentrant {
_admit(proof);
_payEth(order, minEurcMinor);
}
/// @notice Fewest-notes split of an EURC amount. Amounts must be whole cents.
function breakdown(uint256 eurcMinor) public view returns (uint256[] memory facesE8) {
uint256 remaining = eurcMinor * E8_PER_EURC_MINOR;
uint256[15] memory all = Denominations.all();
uint256 count;
for (uint256 i; i < Denominations.COUNT; ++i) {
count += remaining / all[i];
remaining %= all[i];
}
if (remaining != 0) revert UnrepresentableValue();
if (count == 0) revert InvalidAmount();
if (count > maxNotes) revert OutputCap();
facesE8 = new uint256[](count);
remaining = eurcMinor * E8_PER_EURC_MINOR;
uint256 at;
for (uint256 i; i < Denominations.COUNT; ++i) {
for (uint256 n = remaining / all[i]; n != 0; --n) {
facesE8[at++] = all[i];
}
remaining %= all[i];
}
}
function isOpen() external view returns (bool) {
return opensAt != 0 && block.timestamp >= opensAt && block.timestamp < closesAt;
}
function _leaf(address wallet) private pure returns (bytes32) {
return keccak256(bytes.concat(keccak256(abi.encode(wallet))));
}
function _admit(bytes32[] memory proof) private {
if (allowlistRoot == bytes32(0) || admitted[msg.sender]) return;
if (!MerkleProof.verify(proof, allowlistRoot, _leaf(msg.sender))) revert NotAllowlisted();
admitted[msg.sender] = true;
emit Admitted(msg.sender);
}
function _prices() private view returns (uint256 ethUsd, uint256 ethScale, uint256 eurUsd, uint256 eurScale) {
if (address(ethUsdFeed) == address(0)) revert EthNotAccepted();
ethUsd = _read(ethUsdFeed, ETH_USD_MAX_AGE);
eurUsd = _read(eurUsdFeed, EUR_USD_MAX_AGE);
ethScale = 10 ** ethUsdFeed.decimals();
eurScale = 10 ** eurUsdFeed.decimals();
}
function _read(IPriceFeed feed, uint256 maxAge) private view returns (uint256) {
(, int256 answer,, uint256 updatedAt,) = feed.latestRoundData();
if (answer <= 0 || updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) revert StalePrice();
return uint256(answer);
}
function _payEth(bytes32 order, uint256 minEurcMinor) private {
if (minEurcMinor == 0) revert InvalidAmount();
uint256 eurcMinor = eurcForEth(msg.value);
if (eurcMinor < minEurcMinor) revert PriceMoved();
uint256[] memory facesE8 = breakdown(eurcMinor);
uint256 value = _book(order, eurcMinor, facesE8);
// A plain value call moves exactly msg.value; the recipient may forward it on (a smart wallet).
(bool sent,) = eurcRecipient.call{value: msg.value}("");
if (!sent) revert InexactPayment();
_mint(order, eurcMinor, value, facesE8);
emit PaidEth(order, msg.sender, msg.value);
}
function _pay(bytes32 order, uint256 eurcMinor, uint256[] memory facesE8) private {
uint256 value = _book(order, eurcMinor, facesE8);
uint256 payerBefore = paymentToken.balanceOf(msg.sender);
uint256 recipientBefore = paymentToken.balanceOf(eurcRecipient);
paymentToken.safeTransferFrom(msg.sender, eurcRecipient, eurcMinor);
uint256 payerAfter = paymentToken.balanceOf(msg.sender);
uint256 recipientAfter = paymentToken.balanceOf(eurcRecipient);
if (
payerAfter > payerBefore || payerBefore - payerAfter != eurcMinor || recipientAfter < recipientBefore
|| recipientAfter - recipientBefore != eurcMinor
) revert InexactPayment();
_mint(order, eurcMinor, value, facesE8);
}
/// @dev Checks the window, the seal, the payer and the order and books it; the payment itself is the
/// caller's. Every pay path goes through here.
function _book(bytes32 order, uint256 eurcMinor, uint256[] memory facesE8) private returns (uint256 value) {
if (opensAt == 0 || block.timestamp < opensAt || block.timestamp >= closesAt) revert OutsidePaidWindow();
if (!root.bindingsSealed()) revert NotReady();
if (msg.sender == eurcRecipient) revert RecipientCannotPay();
if (order == bytes32(0) || eurcMinor == 0) revert InvalidAmount();
if (paidOrderAmount[msg.sender][order] != 0) revert OrderAlreadyUsed();
if (facesE8.length == 0 || facesE8.length > maxNotes) revert OutputCap();
for (uint256 i; i < facesE8.length; ++i) {
value += facesE8[i];
}
if (value != eurcMinor * E8_PER_EURC_MINOR) revert UnrepresentableValue();
paidOrderAmount[msg.sender][order] = eurcMinor;
paidM0E8 += value;
}
function _mint(bytes32 order, uint256 eurcMinor, uint256 value, uint256[] memory facesE8) private {
uint256 firstSerial = root.nextSerial();
for (uint256 i; i < facesE8.length; ++i) {
// The root rejects any value that is not one of the fifteen faces.
root.mintNote(msg.sender, facesE8[i], 0, SOURCE_PAID);
}
emit Paid(order, msg.sender, eurcMinor, value, firstSerial, facesE8.length);
}
}
src/europoor/EuropoorRoot.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol";
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Denominations} from "./Denominations.sol";
interface IFamilyRenderer {
function validateRecord(uint256 id, uint8 family, uint256 faceValueE8, uint256 unitsE8, uint256 originId)
external
view
returns (bool);
function render(uint256 id, uint8 family, uint256 faceValueE8, uint256 unitsE8, uint256 originId)
external
view
returns (string memory);
}
interface ITransferValidator {
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
}
/// @notice The single EUROPOOR collection: CASH notes (family 0), asset positions (families 1..9)
/// and Dead Blooms (family 10), the originals received by sacrifice.
/// @dev The root only owns identity, records, per-holder accounting and transfer validation.
/// Every economic rule (paid entry, primary purchase, market, treasury, legacy) lives in a module
/// that the owner binds once. A bound module can be retired but never re-bound or re-scoped, and
/// the owner has no direct mint or burn path. Binding a new module would give one, so the deploy
/// ends with sealBindings(): from then on the set of modules is final.
contract EuropoorRoot is ERC721, ERC2981, Ownable2Step {
uint8 public constant CASH = 0;
uint8 public constant MAX_FAMILY = 10;
uint8 public constant MINT_NOTE = 1;
uint8 public constant MINT_ASSET = 2;
uint8 public constant BURN = 4;
uint8 private constant ALL_PERMISSIONS = 7;
uint8 private constant RETIRED = 0x80;
/// @dev Royalties can be lowered, never raised above the 5% set at deployment.
uint96 private constant MAX_ROYALTY_BPS = 500;
struct Record {
uint8 family;
uint8 source;
uint64 faceValueE8;
uint96 unitsE8;
uint64 originId;
}
uint256 public nextSerial = 1;
uint256 public outstandingNotesE8;
mapping(address => uint256) public noteValueOf;
mapping(uint8 => uint256) public outstandingUnitsE8;
mapping(address => mapping(uint8 => uint256)) public assetUnitsOf;
mapping(uint8 => IFamilyRenderer) public rendererOf;
mapping(address => uint8) public modulePermissions;
mapping(uint256 => Record) private _records;
address private _transferValidator;
error UnsupportedChain();
error BindingsAreSealed();
error Unauthorized();
error InvalidBinding();
error InvalidFamily();
error InvalidAmount();
error InvalidOwner();
error UnknownToken();
error RendererUnavailable();
error OwnershipRequired();
event ModuleBound(address indexed module, uint8 permissions);
event BindingsSealed();
event ModuleRetired(address indexed module);
event RendererBound(uint8 indexed family, address indexed renderer);
event TransferValidatorUpdated(address oldValidator, address newValidator);
event MetadataNotifierBound(address indexed notifier);
/// @notice ERC-4906: the metadata (artwork) of `_tokenId` changed; marketplaces should refresh it.
event MetadataUpdate(uint256 _tokenId);
/// @notice ERC-4906: the metadata of every token from `_fromTokenId` to `_toTokenId` changed.
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
event Issued(
uint256 indexed id,
address indexed to,
uint8 indexed family,
uint256 faceValueE8,
uint256 unitsE8,
uint256 originId,
uint8 source
);
constructor(string memory name_, string memory symbol_, address owner_, address royaltyReceiver)
ERC721(name_, symbol_)
Ownable(owner_)
{
// Mainnet, Sepolia and the local chain only.
if (block.chainid != 1 && block.chainid != 11155111 && block.chainid != 31337) revert UnsupportedChain();
_setDefaultRoyalty(royaltyReceiver, 500);
}
// ---------------------------------------------------------------- bindings
/// @notice True once the owner has sealed the module set: no module can ever be bound again.
bool public bindingsSealed;
/// @notice One binding per module address, for its whole life. Permissions cannot be widened later.
function bindModule(address module, uint8 permissions) external onlyOwner {
if (bindingsSealed) revert BindingsAreSealed();
if (
module.code.length == 0 || module == address(this) || modulePermissions[module] != 0 || permissions == 0
|| permissions > ALL_PERMISSIONS
) revert InvalidBinding();
modulePermissions[module] = permissions;
emit ModuleBound(module, permissions);
}
/// @notice Irreversible: after this no module can be bound or retired, so nobody (owner included)
/// can ever gain a way to mint or burn, or stop a module holders rely on.
function sealBindings() external onlyOwner {
if (bindingsSealed) revert BindingsAreSealed();
bindingsSealed = true;
emit BindingsSealed();
}
/// @notice Irreversible stop for one module. This can only remove authority, never grant it.
function retireModule(address module) external onlyOwner {
// Once sealed the module set is final: retiring would strand bids, tickets and redemptions.
if (bindingsSealed) revert BindingsAreSealed();
uint8 permissions = modulePermissions[module];
if (permissions == 0 || permissions == RETIRED) revert InvalidBinding();
modulePermissions[module] = RETIRED;
emit ModuleRetired(module);
}
/// @notice Write-once renderer per family. The CASH renderer must accept all fifteen faces up front,
/// so a note mint never needs to re-validate artwork.
function bindRenderer(uint8 family, address renderer) external onlyOwner {
if (
family > MAX_FAMILY || address(rendererOf[family]) != address(0) || renderer.code.length == 0
|| renderer == address(this)
) revert InvalidBinding();
if (family == CASH) {
uint256[15] memory faces = Denominations.all();
for (uint256 i; i < Denominations.COUNT; ++i) {
if (!IFamilyRenderer(renderer).validateRecord(1, CASH, faces[i], 0, 0)) revert RendererUnavailable();
}
}
rendererOf[family] = IFamilyRenderer(renderer);
emit RendererBound(family, renderer);
}
/// @notice The one contract allowed to announce artwork changes (the seed book, which finishes the
/// artwork of positions after they are issued). It can only emit ERC-4906 events: no mint, burn or
/// record change. Write-once, like the renderers.
address public metadataNotifier;
function bindMetadataNotifier(address notifier) external onlyOwner {
if (metadataNotifier != address(0) || notifier.code.length == 0 || notifier == address(this)) {
revert InvalidBinding();
}
metadataNotifier = notifier;
emit MetadataNotifierBound(notifier);
}
// ------------------------------------------------------- module primitives
function mintNote(address to, uint256 faceValueE8, uint256 originId, uint8 source)
external
returns (uint256 id)
{
_requirePermission(MINT_NOTE);
if (address(rendererOf[CASH]) == address(0)) revert RendererUnavailable();
if (Denominations.indexOf(faceValueE8) == Denominations.NOT_FOUND) revert InvalidAmount();
if (originId >= nextSerial) revert UnknownToken();
id = nextSerial++;
_records[id] = Record(CASH, source, uint64(faceValueE8), 0, uint64(originId));
_mint(to, id);
emit Issued(id, to, CASH, faceValueE8, 0, originId, source);
}
/// @param originId Lineage of the artwork; zero means the new token is its own origin.
function mintAsset(address to, uint8 family, uint256 unitsE8, uint256 originId, uint8 source)
external
returns (uint256 id)
{
_requirePermission(MINT_ASSET);
if (family == CASH || family > MAX_FAMILY) revert InvalidFamily();
if (unitsE8 == 0 || unitsE8 > type(uint96).max) revert InvalidAmount();
if (originId >= nextSerial) revert UnknownToken();
IFamilyRenderer renderer = rendererOf[family];
if (address(renderer) == address(0)) revert RendererUnavailable();
id = nextSerial++;
if (originId == 0) originId = id;
_records[id] = Record(family, source, 0, uint96(unitsE8), uint64(originId));
if (!renderer.validateRecord(id, family, 0, unitsE8, originId)) revert RendererUnavailable();
_mint(to, id);
emit Issued(id, to, family, 0, unitsE8, originId, source);
}
/// @notice The module states whose token it is consuming; a stale or mistaken owner reverts.
function burn(uint256 id, address expectedOwner) external {
_requirePermission(BURN);
if (expectedOwner == address(0) || _ownerOf(id) != expectedOwner) revert InvalidOwner();
_burn(id);
}
/// @notice ERC-4906 refresh for `id`, emitted when its artwork is finished after issuance.
function notifyMetadataUpdate(uint256 id) external {
if (msg.sender != metadataNotifier) revert Unauthorized();
emit MetadataUpdate(id);
}
// ------------------------------------------------------------------- views
/// @notice Records stay readable after a burn; serials are never reused.
function tokenRecord(uint256 id)
external
view
returns (uint8 family, uint8 source, uint256 faceValueE8, uint256 unitsE8, uint256 originId)
{
if (id == 0 || id >= nextSerial) revert UnknownToken();
Record storage r = _records[id];
return (r.family, r.source, r.faceValueE8, r.unitsE8, r.originId);
}
function tokenURI(uint256 id) public view override returns (string memory) {
_requireOwned(id);
Record storage r = _records[id];
return rendererOf[r.family].render(id, r.family, r.faceValueE8, r.unitsE8, r.originId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981) returns (bool) {
// 0xad0d7f6c: ICreatorToken (ERC721-C transfer validator discovery). 0x49064906: ERC-4906.
return interfaceId == 0xad0d7f6c || interfaceId == 0x49064906 || super.supportsInterface(interfaceId);
}
/// @notice Disabled: without an owner, royalties and the transfer validator could never be
/// changed again. Ownership can still move to a new owner (two steps).
function renounceOwnership() public pure override {
revert OwnershipRequired();
}
// ----------------------------------------------- royalties and validation
function setDefaultRoyalty(address receiver, uint96 feeBps) external onlyOwner {
if (feeBps > MAX_ROYALTY_BPS) revert InvalidAmount();
_setDefaultRoyalty(receiver, feeBps);
}
function getTransferValidator() external view returns (address) {
return _transferValidator;
}
/// @dev validateTransfer(address,address,address,uint256), called as a view.
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
return (0xcaee23ea, true);
}
/// @notice Zero disables external validation. Bound modules settle under their own rules.
function setTransferValidator(address validator) external onlyOwner {
if (validator != address(0) && validator.code.length == 0) revert InvalidBinding();
emit TransferValidatorUpdated(_transferValidator, validator);
_transferValidator = validator;
}
// --------------------------------------------------------------- internals
function _requirePermission(uint8 permission) private view {
if (!_holds(msg.sender, permission)) revert Unauthorized();
}
function _holds(address module, uint8 permission) private view returns (bool) {
uint8 held = modulePermissions[module];
return held & RETIRED == 0 && held & permission != 0;
}
/// @notice Changes whenever an asset position moves or its approval changes. A market order made
/// at one nonce is void at any other, so an old order can never come back to life.
mapping(uint256 => uint256) public tokenNonce;
function _approve(address to, uint256 id, address auth, bool emitEvent) internal override {
super._approve(to, id, auth, emitEvent);
if (_records[id].family != CASH) ++tokenNonce[id];
}
function _update(address to, uint256 id, address auth) internal override returns (address from) {
from = super._update(to, id, auth);
if (_records[id].family != CASH && from != address(0)) ++tokenNonce[id];
if (from != address(0) && to != address(0)) {
address validator = _transferValidator;
if (validator != address(0) && !_holds(msg.sender, ALL_PERMISSIONS)) {
ITransferValidator(validator).validateTransfer(msg.sender, from, to, id);
}
}
Record storage r = _records[id];
if (r.family == CASH) {
uint256 face = r.faceValueE8;
if (from == address(0)) outstandingNotesE8 += face;
else noteValueOf[from] -= face;
if (to == address(0)) outstandingNotesE8 -= face;
else noteValueOf[to] += face;
} else {
uint8 family = r.family;
uint256 units = r.unitsE8;
if (from == address(0)) outstandingUnitsE8[family] += units;
else assetUnitsOf[from][family] -= units;
if (to == address(0)) outstandingUnitsE8[family] -= units;
else assetUnitsOf[to][family] += units;
}
}
}
src/europoor/PackedEconomicSchedule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
interface IEconomicSchedule {
function priceAt(uint8 asset, uint256 year) external view returns (uint256);
function currentYear() external view returns (uint256);
function gameDay() external view returns (uint256);
function rising() external view returns (bool);
function livePriceE8(uint8 asset) external view returns (uint256);
function dayProgress() external view returns (uint256 secondsIntoDay, uint256 duration);
}
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ArtDataChunk} from "./BytecodeArtStore.sol";
/// @notice Immutable public historical replay for local/Sepolia rehearsal, not a forecast or live market.
/// The replay is a pendulum that never stops: one game year per `dayDuration`, 1924 up to 2024, then
/// back down from 2024 to 1924, then up again, forever. Prices always come from the real series; only
/// the direction alternates, so every downswing is the century's inflation played backwards.
/// Live prices: inside each game day the price moves every second, in a straight line, from the
/// price of that day's year to the price of the next day's year (see `livePriceE8`), so there is no
/// jump at the turn of the day for anyone to trade across. `priceAt`, `cpiAt`, `currentYear`,
/// `gameDay` and `rising` keep their meaning: the year whose price applies at the START of the day.
/// @dev Prices are year-major: year * 10 + shared uint8 asset. Both payloads use uint128 big-endian.
/// Constructor ABI: (uint256 start, uint256 duration, bytes packedPrices, bytes packedCpi,
/// bytes32 expectedPriceCommitment, bytes32 expectedCpiCommitment). Default rehearsal duration
/// is 86400 seconds, the only one accepted on chain 1; test networks accept any nonzero duration.
/// Commitments hash abi.encode(uint256[]), NOT packed bytes. No owner, setters or SSTORE arrays.
contract PackedEconomicSchedule is IEconomicSchedule {
uint256 public constant E8 = 1e8;
uint256 public constant LAST_YEAR = 100;
/// @notice Game years in one full swing: 100 up and 100 down.
uint256 public constant CYCLE_YEARS = 200;
uint256 public constant PRICE_BYTES = 1010 * 16;
uint256 public constant CPI_BYTES = 101 * 16;
uint256 public immutable startTimestamp;
uint256 public immutable dayDuration;
bytes32 public immutable priceCommitment;
bytes32 public immutable cpiCommitment;
bytes32 public immutable scheduleCommitment;
bytes32 public immutable fullCommitment;
address public immutable pricePointer;
address public immutable cpiPointer;
bytes32 public immutable priceCodeHash;
bytes32 public immutable cpiCodeHash;
error UnsupportedChain();
error InvalidDuration();
error InvalidPrices();
error InvalidCpi();
error CommitmentMismatch();
error InvalidAssetOrYear();
error InvalidDataChunk();
constructor(
uint256 start,
uint256 duration,
bytes memory packedPrices,
bytes memory packedCpi,
bytes32 expectedPriceCommitment,
bytes32 expectedCpiCommitment
) {
// The exchange's printing period and growth rates assume one game year per real day; only test
// networks may run a faster clock.
if (duration == 0 || (block.chainid == 1 && duration != 1 days)) revert InvalidDuration();
if (block.chainid != 1 && block.chainid != 11155111 && block.chainid != 31337) revert UnsupportedChain();
if (packedPrices.length != PRICE_BYTES) revert InvalidPrices();
if (packedCpi.length != CPI_BYTES) revert InvalidCpi();
uint256[] memory prices = new uint256[](1010);
for (uint256 i; i < prices.length; ++i) {
uint256 value = _unpack(packedPrices, i);
if (value == 0 || (i % 10 == 0 && value != E8)) revert InvalidPrices();
prices[i] = value;
}
uint256[] memory cpi = new uint256[](101);
for (uint256 i; i < cpi.length; ++i) {
uint256 value = _unpack(packedCpi, i);
if (value == 0 || (i == 0 && value != E8)) revert InvalidCpi();
cpi[i] = value;
}
bytes32 pricesHash = keccak256(abi.encode(prices));
bytes32 cpiHash = keccak256(abi.encode(cpi));
if (pricesHash != expectedPriceCommitment || cpiHash != expectedCpiCommitment) revert CommitmentMismatch();
startTimestamp = start;
dayDuration = duration;
priceCommitment = pricesHash;
cpiCommitment = cpiHash;
// Preserve the original three-field commitment for existing integrations.
scheduleCommitment = keccak256(abi.encode(start, duration, pricesHash));
fullCommitment = keccak256(abi.encode(start, duration, pricesHash, cpiHash));
(pricePointer, priceCodeHash) = _store(packedPrices);
(cpiPointer, cpiCodeHash) = _store(packedCpi);
}
/// @notice Whole game years since the start; it keeps counting through every swing.
function gameDay() public view returns (uint256) {
if (block.timestamp <= startTimestamp) return 0;
return (block.timestamp - startTimestamp) / dayDuration;
}
/// @notice The year of the series whose prices apply now (0 = 1924, 100 = 2024).
function currentYear() external view returns (uint256) {
return yearOfDay(gameDay());
}
/// @notice True while prices go up (1924 towards 2024); false from 2024 back down to 1924.
function rising() external view returns (bool) {
return gameDay() % CYCLE_YEARS < LAST_YEAR;
}
function priceAt(uint8 asset, uint256 year) external view returns (uint256) {
if (asset > 9 || year > LAST_YEAR) revert InvalidAssetOrYear();
return _read(pricePointer, priceCodeHash, PRICE_BYTES, year * 10 + asset);
}
function cpiAt(uint256 year) external view returns (uint256) {
if (year > LAST_YEAR) revert InvalidAssetOrYear();
return _read(cpiPointer, cpiCodeHash, CPI_BYTES, year);
}
/// @notice The year of the series a game day belongs to, through the endless pendulum.
function yearOfDay(uint256 day) public pure returns (uint256) {
uint256 phase = day % CYCLE_YEARS;
return phase <= LAST_YEAR ? phase : CYCLE_YEARS - phase;
}
/// @notice Seconds elapsed in the current game day (0 before the start) and the day's length.
function dayProgress() public view returns (uint256 secondsIntoDay, uint256 duration) {
duration = dayDuration;
if (block.timestamp > startTimestamp) secondsIntoDay = (block.timestamp - startTimestamp) % duration;
}
/// @notice The price of `asset` right now. It equals priceAt(asset, currentYear()) at the first
/// second of every game day and moves linearly, second by second, towards the price of the next
/// day's year (down as well as up, and through both turns of the pendulum). Year 0 before the start.
/// @dev Rounded towards the price at the start of the day: the move so far is floor(|next - now| *
/// s / D). So it is exact at s = 0, never leaves the segment between the two prices (never 0,
/// as every price is > 0), and is monotone second by second; the rounding is below 1e-8 EP
/// per unit and is the same for buyers and redeemers, far inside the 5% redemption fee.
function livePriceE8(uint8 asset) external view returns (uint256) {
if (asset > 9) revert InvalidAssetOrYear();
(uint256 day, uint256 s) = _clock();
uint256 from = _read(pricePointer, priceCodeHash, PRICE_BYTES, yearOfDay(day) * 10 + asset);
if (s == 0) return from;
uint256 to = _read(pricePointer, priceCodeHash, PRICE_BYTES, yearOfDay(day + 1) * 10 + asset);
return _lerp(from, to, s);
}
/// @notice The consumer price index right now, moving like `livePriceE8` (1e8 in 1924).
function liveCpiE8() external view returns (uint256) {
(uint256 day, uint256 s) = _clock();
uint256 from = _read(cpiPointer, cpiCodeHash, CPI_BYTES, yearOfDay(day));
if (s == 0) return from;
uint256 to = _read(cpiPointer, cpiCodeHash, CPI_BYTES, yearOfDay(day + 1));
return _lerp(from, to, s);
}
function _clock() private view returns (uint256 day, uint256 s) {
if (block.timestamp <= startTimestamp) return (0, 0);
uint256 elapsed = block.timestamp - startTimestamp;
return (elapsed / dayDuration, elapsed % dayDuration);
}
/// @dev from + (to - from) * s / D, rounded towards `from`.
function _lerp(uint256 from, uint256 to, uint256 s) private view returns (uint256) {
return to >= from ? from + Math.mulDiv(to - from, s, dayDuration) : from - Math.mulDiv(from - to, s, dayDuration);
}
function _unpack(bytes memory payload, uint256 index) private pure returns (uint256 value) {
// Load an aligned pair, including padded final CPI word; never read beyond the allocation.
assembly ("memory-safe") { value := mload(add(add(payload, 32), mul(div(index, 2), 32))) }
return index % 2 == 0 ? value >> 128 : value & type(uint128).max;
}
function _store(bytes memory payload) private returns (address pointer, bytes32 codeHash) {
codeHash = keccak256(bytes.concat(hex"00", payload));
pointer = address(new ArtDataChunk(payload));
if (pointer.code.length != payload.length + 1 || pointer.codehash != codeHash) revert InvalidDataChunk();
}
function _read(address pointer, bytes32 codeHash, uint256 payloadLength, uint256 index)
private
view
returns (uint256 value)
{
if (pointer.code.length != payloadLength + 1 || pointer.codehash != codeHash) revert InvalidDataChunk();
// Public callers bound index first. Copy exactly one uint128 past the leading STOP byte.
assembly ("memory-safe") {
extcodecopy(pointer, 0, add(1, mul(index, 16)), 16)
value := shr(128, mload(0))
}
}
}
src/europoor/SeedBook.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {BlockHashes} from "./BlockHashes.sol";
import {EuropoorRoot} from "./EuropoorRoot.sol";
/// @notice One random seed per asset position. Generated artwork, rarity included, derives from it.
/// @dev The seed comes from the hash of the block AFTER the one that issued the position, so nobody
/// can know it inside the issuing transaction and revert on a rarity they dislike. Issuing queues the
/// position; any later issuance, a redemption, or anyone calling `settle` fixes the seeds whose next
/// block exists, in queue order. That hash stays readable for 8191 blocks (about 27 hours, see
/// BlockHashes). A seed left unsettled even longer is re-anchored to the block it is found in and fixed
/// from the hash of the block after that, which nobody knows yet: no seed is ever known in advance, and
/// only a hash that can no longer be read is replaced, so a readable roll is never re-rolled. Until
/// settled, `seedOf` is zero and the renderer shows the artwork as still being drawn; settling tells
/// marketplaces to refresh (ERC-4906, through the root) once the root has bound this book for it.
/// The builder of that next block could in theory steer it; for artwork variety that is accepted.
contract SeedBook {
uint256 private constant SETTLE_PER_RECORD = 8;
EuropoorRoot public immutable root;
mapping(uint256 => bytes32) public seedOf;
/// @notice The block whose successor's hash will fix the seed; zero if never queued.
mapping(uint256 => uint256) public anchorBlock;
uint256[] private _queue;
uint256 private _head;
error Unauthorized();
error InvalidToken();
error AlreadyRecorded();
event SeedQueued(uint256 indexed id, uint256 blockNumber);
event SeedRecorded(uint256 indexed id, bytes32 seed);
/// @notice The seed's block hash expired before anyone settled it: it now comes from the hash of
/// the block after `blockNumber`.
event SeedReanchored(uint256 indexed id, uint256 blockNumber);
constructor(EuropoorRoot root_) {
if (address(root_).code.length == 0) revert InvalidToken();
root = root_;
}
/// @notice Called by the module that just issued `id`. Queues it and settles older seeds.
function record(uint256 id) external {
uint8 permissions = root.modulePermissions(msg.sender);
// Any retired module carries the high bit; live issuers hold MINT_ASSET.
if (permissions >= 0x80 || permissions & root.MINT_ASSET() == 0) revert Unauthorized();
(uint8 family,,,,) = root.tokenRecord(id);
if (family == root.CASH()) revert InvalidToken();
if (anchorBlock[id] != 0) revert AlreadyRecorded();
anchorBlock[id] = block.number;
_queue.push(id);
emit SeedQueued(id, block.number);
_settle(SETTLE_PER_RECORD);
}
/// @notice Fixes up to `max` waiting seeds whose next block exists. Anyone may call it. If the next
/// seed's hash has expired, this call re-anchors it (and the expired ones right behind it, up to
/// `max`) instead, and they are fixed a block or more later.
function settle(uint256 max) external returns (uint256 done) {
return _settle(max);
}
/// @notice Issued, seed not fixed yet: the artwork is still being drawn.
function isPending(uint256 id) external view returns (bool) {
return anchorBlock[id] != 0 && seedOf[id] == bytes32(0);
}
/// @notice Positions waiting for their seed.
function pendingCount() external view returns (uint256) {
return _queue.length - _head;
}
/// @notice Waiting seeds whose next block exists, so `settle` can act on them now (an expired one
/// is re-anchored first), counted up to 256. What a keeper reads before sending `settle`.
function settleable() external view returns (uint256 count) {
uint256 end = _queue.length;
for (uint256 i = _head; i < end && count < 256 && block.number > anchorBlock[_queue[i]] + 1; ++i) {
++count;
}
}
function _settle(uint256 max) private returns (uint256 done) {
bool notify;
bool notifyChecked;
while (done < max && _head < _queue.length) {
uint256 id = _queue[_head];
uint256 anchor = anchorBlock[id];
if (block.number <= anchor + 1) break;
bytes32 hash = BlockHashes.get(anchor + 1);
// Older than the history window: wait for a hash nobody knows yet, never a known fallback.
if (hash == bytes32(0)) {
_reanchor(max - done);
break;
}
++_head;
++done;
bytes32 seed = keccak256(abi.encode(hash, address(root), id));
seedOf[id] = seed;
emit SeedRecorded(id, seed);
if (!notifyChecked) {
notifyChecked = true;
notify = root.metadataNotifier() == address(this);
}
// The artwork just changed from "being drawn" to final: tell marketplaces to refresh.
if (notify) root.notifyMetadataUpdate(id);
}
}
/// @dev Moves the expired seeds at the head of the queue (at most `max`) to the current block.
/// The first seed whose hash is still readable (or not mined yet) ends the run: it keeps its roll,
/// and so does every seed queued after it (their anchors are no older). Queue places never change.
function _reanchor(uint256 max) private {
for (uint256 i = _head; i < _queue.length && i - _head < max; ++i) {
uint256 id = _queue[i];
uint256 anchor = anchorBlock[id];
if (block.number <= anchor + 1 || BlockHashes.get(anchor + 1) != bytes32(0)) break;
anchorBlock[id] = block.number;
emit SeedReanchored(id, block.number);
}
}
}
src/final-sepolia/DeterministicEconomyPreview.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @notice Pure test-only integer economy preview; NOT a price oracle or an authorized mint policy.
/// @dev One game year = 86400 seconds. The first 100 years are the historical
/// comparison window, not a terminal cap. Ray powers use exponentiation by squaring
/// with floor after EACH uint256-checked multiplication. Display money and supply
/// each floor(start * index / RAY); price E8 floors(startPriceE8 * moneyIndex /
/// supplyIndex), intentionally independent of rounded displayed quantities.
library DeterministicEconomyPreview {
error InvalidInput();
error RegimeRequired();
error ZeroPrice();
uint256 internal constant RAY = 1e27;
uint256 internal constant HISTORY_SECONDS = 100 days;
uint256 internal constant YEAR_SECONDS = 1 days;
function _factor(uint256 value) private pure {
if (value < RAY || value > 2 * RAY) revert InvalidInput();
}
function _index(uint256 factorRay, uint256 elapsedSeconds) private pure returns (uint256 result) {
result = RAY;
while (elapsedSeconds != 0) {
if (elapsedSeconds & 1 != 0) result = result * factorRay / RAY;
elapsedSeconds >>= 1;
if (elapsedSeconds != 0) factorRay = factorRay * factorRay / RAY;
}
}
function indexRay(uint256 perSecondFactorRay, uint256 elapsedSeconds) internal pure returns (uint256) {
_factor(perSecondFactorRay);
return _index(perSecondFactorRay, elapsedSeconds);
}
/// @dev Largest integer per-second factor whose floored one-day RAY index
/// does not exceed RAY*(1+annualPpm/1e6). Exact bisection, no floating point.
/// A year-end index is bounded by, but not necessarily equal to, annual target.
function factorFromAnnualPpm(uint256 annualPpm) internal pure returns (uint256) {
if (annualPpm > 1_000_000) revert InvalidInput();
uint256 target = RAY + annualPpm * RAY / 1_000_000;
uint256 low = RAY;
uint256 high = RAY + RAY / YEAR_SECONDS;
while (low < high) {
uint256 mid = (low + high + 1) / 2;
if (_index(mid, YEAR_SECONDS) <= target) low = mid;
else high = mid - 1;
}
return low;
}
function preview(uint256 startMoney, uint256 startSupply, uint256 startPriceE8,
uint256 moneyFactorRay, uint256 supplyFactorRay, uint256 elapsedSeconds)
internal pure returns (uint256 money, uint256 supply, uint256 priceE8)
{
if (elapsedSeconds > HISTORY_SECONDS) revert RegimeRequired();
return _preview(startMoney, startSupply, startPriceE8, moneyFactorRay, supplyFactorRay, elapsedSeconds, false);
}
/// @dev Explicit simulation choice only; neither branch authorizes onchain policy.
/// cashStops=true holds the money index at day 100 while supply keeps compounding.
function previewWithRegime(uint256 startMoney, uint256 startSupply, uint256 startPriceE8,
uint256 moneyFactorRay, uint256 supplyFactorRay, uint256 elapsedSeconds, bool cashStops)
internal pure returns (uint256 money, uint256 supply, uint256 priceE8)
{
return _preview(startMoney, startSupply, startPriceE8, moneyFactorRay, supplyFactorRay, elapsedSeconds, cashStops);
}
function _preview(uint256 startMoney, uint256 startSupply, uint256 startPriceE8,
uint256 moneyFactorRay, uint256 supplyFactorRay, uint256 elapsedSeconds, bool cashStops)
private pure returns (uint256 money, uint256 supply, uint256 priceE8)
{
_factor(moneyFactorRay);
_factor(supplyFactorRay);
if (startMoney == 0 || startSupply == 0 || startPriceE8 == 0) revert InvalidInput();
uint256 moneyIndex = _index(moneyFactorRay, cashStops && elapsedSeconds > HISTORY_SECONDS ? HISTORY_SECONDS : elapsedSeconds);
uint256 supplyIndex = _index(supplyFactorRay, elapsedSeconds);
money = startMoney * moneyIndex / RAY;
supply = startSupply * supplyIndex / RAY;
priceE8 = startPriceE8 * moneyIndex / supplyIndex;
if (priceE8 == 0) revert ZeroPrice();
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=../node_modules/@openzeppelin/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.