From f2769993b5a0ca2cde8374126058981eb2c288ef Mon Sep 17 00:00:00 2001 From: Bot Date: Sun, 30 Aug 2026 23:16:04 +0800 Subject: [PATCH] feat: initial commit for wtf-contract v2 --- README.md | 283 ++++ .../contracts/interfaces/IERC6909.sol | 125 ++ .../contracts/utils/introspection/IERC165.sol | 25 + .../solady/src/utils/FixedPointMathLib.sol | 1312 ++++++++++++++++ curve/src/curves/CurveBase.sol | 16 + curve/src/curves/PowerLDACurveV2.sol | 334 +++++ curve/src/curves/math/LDAMath.sol | 71 + curve/src/curves/math/PowerLDAMath.sol | 209 +++ curve/src/curves/math/PowerMath.sol | 354 +++++ curve/src/curves/math/PowerMathV2.sol | 174 +++ curve/src/interfaces/IRegistry.sol | 28 + curve/src/interfaces/IWTFCurve.sol | 144 ++ curve/src/interfaces/IWTFMarket.sol | 43 + curve/src/libraries/Decoder.sol | 54 + curve/src/libraries/Errors.sol | 139 ++ curve/src/libraries/LogExpMath.sol | 510 +++++++ curve/src/libraries/Market.sol | 214 +++ curve/src/libraries/RedeemMath.sol | 125 ++ curve/src/libraries/RedeemMathV2.sol | 140 ++ curve/src/libraries/WTFMath.sol | 93 ++ .../access/AccessControlUpgradeable.sol | 232 +++ ...essControlDefaultAdminRulesUpgradeable.sol | 402 +++++ .../contracts/proxy/utils/Initializable.sol | 6 + .../contracts/utils/ContextUpgradeable.sol | 35 + .../utils/introspection/ERC165Upgradeable.sol | 32 + .../contracts/access/IAccessControl.sol | 99 ++ .../IAccessControlDefaultAdminRules.sol | 193 +++ .../contracts/interfaces/IERC1363.sol | 87 ++ .../contracts/interfaces/IERC165.sol | 7 + .../contracts/interfaces/IERC20.sol | 7 + .../contracts/interfaces/IERC20Metadata.sol | 7 + .../contracts/interfaces/IERC5313.sol | 17 + .../contracts/interfaces/IERC6909.sol | 126 ++ .../contracts/proxy/utils/Initializable.sol | 239 +++ .../contracts/token/ERC20/IERC20.sol | 80 + .../token/ERC20/extensions/IERC20Metadata.sol | 27 + .../contracts/token/ERC20/utils/SafeERC20.sol | 281 ++++ .../contracts/utils/Arrays.sol | 736 +++++++++ .../contracts/utils/Comparators.sol | 20 + .../contracts/utils/Panic.sol | 58 + .../utils/ReentrancyGuardTransient.sol | 85 ++ .../contracts/utils/SlotDerivation.sol | 156 ++ .../contracts/utils/StorageSlot.sol | 144 ++ .../contracts/utils/TransientSlot.sol | 184 +++ .../contracts/utils/introspection/ERC165.sol | 26 + .../contracts/utils/introspection/IERC165.sol | 26 + .../contracts/utils/math/Math.sol | 757 ++++++++++ .../contracts/utils/math/SafeCast.sol | 1163 +++++++++++++++ .../contracts/utils/structs/EnumerableSet.sol | 793 ++++++++++ .../solady/src/utils/FixedPointMathLib.sol | 1313 +++++++++++++++++ main/lib/solady/src/utils/SSTORE2.sol | 260 ++++ main/src/WTFERC6909.sol | 308 ++++ main/src/WTFMarketV2.sol | 762 ++++++++++ main/src/controllerv2/ControllerStorage.sol | 122 ++ main/src/controllerv2/Governance.sol | 253 ++++ main/src/controllerv2/MarketFactory.sol | 152 ++ main/src/controllerv2/Registry.sol | 250 ++++ main/src/controllerv2/WTFControllerV2.sol | 556 +++++++ main/src/interfaces/IRegistry.sol | 60 + main/src/interfaces/IWTFControllerV2.sol | 67 + main/src/interfaces/IWTFCurve.sol | 145 ++ main/src/interfaces/IWTFMarket.sol | 44 + main/src/interfaces/IWTFMarketV2.sol | 65 + main/src/libraries/Errors.sol | 147 ++ main/src/libraries/Event.sol | 319 ++++ main/src/libraries/LogExpMath.sol | 511 +++++++ main/src/libraries/Market.sol | 215 +++ main/src/libraries/QuestionV2.sol | 286 ++++ main/src/libraries/RedeemMath.sol | 126 ++ main/src/libraries/StringLib.sol | 661 +++++++++ main/src/libraries/TokenHelper.sol | 125 ++ main/src/libraries/WTFMath.sol | 82 + mock/MockERC20.sol | 58 + mock/TestProxy.sol | 36 + 74 files changed, 17341 insertions(+) create mode 100644 README.md create mode 100644 curve/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol create mode 100644 curve/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol create mode 100644 curve/lib/solady/src/utils/FixedPointMathLib.sol create mode 100644 curve/src/curves/CurveBase.sol create mode 100644 curve/src/curves/PowerLDACurveV2.sol create mode 100644 curve/src/curves/math/LDAMath.sol create mode 100644 curve/src/curves/math/PowerLDAMath.sol create mode 100644 curve/src/curves/math/PowerMath.sol create mode 100644 curve/src/curves/math/PowerMathV2.sol create mode 100644 curve/src/interfaces/IRegistry.sol create mode 100644 curve/src/interfaces/IWTFCurve.sol create mode 100644 curve/src/interfaces/IWTFMarket.sol create mode 100644 curve/src/libraries/Decoder.sol create mode 100644 curve/src/libraries/Errors.sol create mode 100644 curve/src/libraries/LogExpMath.sol create mode 100644 curve/src/libraries/Market.sol create mode 100644 curve/src/libraries/RedeemMath.sol create mode 100644 curve/src/libraries/RedeemMathV2.sol create mode 100644 curve/src/libraries/WTFMath.sol create mode 100644 main/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol create mode 100644 main/lib/openzeppelin-contracts-upgradeable/contracts/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol create mode 100644 main/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol create mode 100644 main/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol create mode 100644 main/lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlDefaultAdminRules.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/interfaces/IERC5313.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/Arrays.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/Comparators.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/Panic.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/math/Math.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol create mode 100644 main/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol create mode 100644 main/lib/solady/src/utils/FixedPointMathLib.sol create mode 100644 main/lib/solady/src/utils/SSTORE2.sol create mode 100644 main/src/WTFERC6909.sol create mode 100644 main/src/WTFMarketV2.sol create mode 100644 main/src/controllerv2/ControllerStorage.sol create mode 100644 main/src/controllerv2/Governance.sol create mode 100644 main/src/controllerv2/MarketFactory.sol create mode 100644 main/src/controllerv2/Registry.sol create mode 100644 main/src/controllerv2/WTFControllerV2.sol create mode 100644 main/src/interfaces/IRegistry.sol create mode 100644 main/src/interfaces/IWTFControllerV2.sol create mode 100644 main/src/interfaces/IWTFCurve.sol create mode 100644 main/src/interfaces/IWTFMarket.sol create mode 100644 main/src/interfaces/IWTFMarketV2.sol create mode 100644 main/src/libraries/Errors.sol create mode 100644 main/src/libraries/Event.sol create mode 100644 main/src/libraries/LogExpMath.sol create mode 100644 main/src/libraries/Market.sol create mode 100644 main/src/libraries/QuestionV2.sol create mode 100644 main/src/libraries/RedeemMath.sol create mode 100644 main/src/libraries/StringLib.sol create mode 100644 main/src/libraries/TokenHelper.sol create mode 100644 main/src/libraries/WTFMath.sol create mode 100644 mock/MockERC20.sol create mode 100644 mock/TestProxy.sol diff --git a/README.md b/README.md new file mode 100644 index 0000000..16f9b7f --- /dev/null +++ b/README.md @@ -0,0 +1,283 @@ +# WTFX 核心智能合约系统设计与实战开发指南 + +> **项目名称**:WTFX (原 WTFPred / WTF Market) +> **核心定位**:基于 Bonding Curve(多结果联动幂律 LDA 曲线)的高频预测市场协议,支持内盘快速发射与毕业后无缝转入现货/订单簿。 +> **设计语言**:Solidity `^0.8.29` / `Cancun EVM` / `Arbitrum Nitro` + +--- + +## 目录 +1. [系统整体架构与核心组件](#1-系统整体架构与核心组件) +2. [经济模型与核心数学机制](#2-经济模型与核心数学机制) +3. [分档位治理体系与单市场覆盖](#3-分档位治理体系与单市场覆盖) +4. [完整生命周期与业务流程](#4-完整生命周期与业务流程) +5. [目录结构与代码组织](#5-目录结构与代码组织) +6. [编译、部署与测试指南 (Robinhood Chain & 本地)](#6-编译部署与测试指南) +7. [关键接口速查与开发示例](#7-关键接口速查与开发示例) + +--- + +## 1. 系统整体架构与核心组件 + +WTFX 采用模块化解耦与可升级代理架构(Upgradeable Proxy Pattern),核心由三大支柱构成: + +``` + ┌────────────────────────┐ + │ WTFX 用户 / 交易者 │ + └───────────┬────────────┘ + │ (Mint/Redeem/Claim/Transfer) + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ WTFMarketV2.sol │ +│ - ERC-6909 多代币标准(每个结果选项一个 TokenId: 1, 2, 4...) │ +│ - 市场资金池状态机(Trading -> Graduated / Finalised / Refunded)│ +└──────────────┬──────────────────────────────┬───────────────┘ + │ │ + (查询联动曲线边际价与成本) (查询市场元数据、档位与治理配置) + ▼ ▼ +┌─────────────────────────────┐┌──────────────────────────────┐ +│ PowerLDACurveV2.sol ││ WTFControllerV2.sol │ +│ - 幂律 LDA 联合曲线计算库 ││ (Upgradeable Proxy + Facade)│ +│ - calMarginalPrice / Seed ││ - MarketFactory (建盘分发) │ +│ - 多结果自平衡与时间衰减 ││ - Governance (分档位与参数) │ +│ ││ - Registry (命题确权与争议期) │ +└─────────────────────────────┘└──────────────────────────────┘ +``` + +### 核心合约模块职责 +1. **`WTFControllerV2.sol` (中枢控制器)**: + - 作为协议的主入口与可升级代理实现(Proxy Pattern); + - **`MarketFactory`**:负责根据创作者配置部署专属 `WTFMarketV2` 实例,并完成初始流动性(Seed)注入; + - **`Governance`**:管理创作者手续费分成、中心化收益钱包(Central Wallet)、全局默认毕业阈值与 **分档位(Tiers)/ 单市场覆盖(Overrides)**; + - **`Registry`**:负责链上命题元数据确权(`questionId`)、选项绑定与裁决争议期管理。 +2. **`WTFMarketV2.sol` (预测市场交易实例)**: + - 采用 **ERC-6909** 多资产标准,每个预测选项对应一个独立的 `tokenId`(如 `Yes = 1`, `No = 2`); + - 独立托管抵押品(WUSD / USDC),执行交易者的买入(`mintCollateralToExactOt`)与卖出(`redeemExactOtToCollateral`); + - 实现市场毕业(`graduate`)、全员返还(`refund`)以及最终兑付(`claim`)。 +3. **`PowerLDACurveV2.sol` (联合曲线引擎)**: + - 基于幂律连续拍卖(Linear Discrete Auction / Power Curve)算法; + - 实现任意数量选项(2 ~ 255 个)的联动价格发现; + - 保证资金池抵押品与代币铸造的严格守恒与无摩擦做市。 + +--- + +## 2. 经济模型与核心数学机制 + +### 2.1 创作者 Seed 机制(冷启动注入) +创作者建盘时需注入一定量的底仓(Seed OT),例如每个选项 1 ~ 10 OT: +- **零额外费用**:初始 Seed 调用 `curve.calSeedCost`,不收取创作者手续费; +- **博弈论本质**:Seed 锁在池子中作为底仓,创作者持有全套结果代币。即使盘子无人交易,创作者可通过 `refund()` 或到期 `claim()` **100% 取回大部分本金**。 + +### 2.2 交易手续费流向 (Fee Split) +每一笔买入/卖出交易扣除的 `feeRate`(创作者建盘时在 0.1% ~ 3.0% 之间自主选择并冻结): +- **50% 创作者激励**:直接沉淀为创作者待提取收入; +- **50% 平台中心化钱包**:流入超级管理员配置的 `centralWallet`。 + +### 2.3 毕业(Graduation)机制 +当买方狂热将资金池推升至阈值时触发毕业: +- **触发条件**:`totalMarketCap >= thresholdMcap` 或 `maxSupplySingle >= thresholdMaxSupply`; +- **毕业效果**: + 1. 联合曲线立即永久冻结,停止 Curve 买卖; + 2. 按照各选项最终边际价格归一化计算概率分布,锁定 `redeemValue`; + 3. 资金池流动性与代币可平滑迁移至外部 CLOB 订单簿或 AMM 现货池。 + +--- + +## 3. 分档位治理体系与单市场覆盖 + +系统彻底废弃全局一刀切设计,建立了三级优先级的治理读取模型: + +$$ ext{生效参数} = \mathbf{单市场独立覆盖 (Override)} \succ \mathbf{所属市场档位 (Tier)} \succ \mathbf{全局兜底配置 (Global Default)}$$ + +### 3.1 预设标准档位参数 (Robinhood / Production Grade) + +| 档位 | 命名 | 定位与场景 | 毕业 mcap | 单结果供给 | 争议窗口期 | +| :--- | :--- | :--- | :--- | :--- | :--- | +| **Tier 1** | **PvP 极速盘** | 链上热点、KOL 互撕、数小时结算 | **$3,000 WUSD** | 50,000 OT | **10 分钟 (600s)** | +| **Tier 2** | **社区主流盘** | 赛事决赛、周度行情、经济指标 | **$25,000 WUSD** | 300,000 OT | **2 小时 (7200s)** | +| **Tier 3** | **旗舰宏观盘** | 总统大选、宏观政策、机构大盘 | **$100,000 WUSD**| 1,000,000 OT| **24 小时 (86400s)**| +| **Tier 0** | **全局默认** | 兜底未分档市场 | $10,000 WUSD | 100,000 OT | 1 小时 (3600s) | + +### 3.2 治理接口说明 +- `setMarketTier(tierId, mcap, maxSupply, disputeWindow)`:管理员配置指定档位的标准参数; +- `setMarketTierBinding(market, tierId)`:为特定市场切换绑定的档位; +- `setMarketConfigOverride(market, mcap, maxSupply, disputeWindow, isCustom)`:为某个重要盘子定制独一无二的阈值(`isCustom=true` 立即生效覆盖,`isCustom=false` 撤销并回退到档位)。 + +--- + +## 4. 完整生命周期与业务流程 + +``` +[创作者建盘] ──> [联合曲线交易阶段] ──> [触发毕业] (自动/Keeper冻结曲线) + │ + ▼ (事件截止) + [创作者裁决] (resolveOutcome -> finaliseOutcome) + │ + ▼ + [争议窗口期内] (10分钟 ~ 24小时) + ├── 超级管理员改判 (overrideFinalise) + └── 创作者/管理员全员返还 (refund) + │ + ▼ (争议期结束) + [赢家兑付] (claim 销毁获胜 OT 领取抵押品) +``` + +--- + +## 5. 目录结构与代码组织 + +`wtf-contract/` 目录下包含了完整的合约体系与依赖: + +``` +wtf-contract/ +├── main/ # 核心主合约体系 +│ ├── src/ +│ │ ├── controllerv2/ # 控制器、工厂、存储与治理逻辑 +│ │ │ ├── ControllerStorage.sol # 统一存储槽与数据结构定义 +│ │ │ ├── Governance.sol # 治理分档位与费率逻辑 +│ │ │ ├── MarketFactory.sol # 市场部署与 Seed 注入 +│ │ │ ├── Registry.sol # 命题注册与裁决逻辑 +│ │ │ └── WTFControllerV2.sol # 主入口与代理合约 +│ │ ├── interfaces/ # 外部与内部接口 +│ │ │ ├── IRegistry.sol +│ │ │ ├── IWTFControllerV2.sol +│ │ │ ├── IWTFCurve.sol +│ │ │ └── IWTFMarketV2.sol +│ │ ├── libraries/ # 核心算法、事件与自定义错误 +│ │ │ ├── Errors.sol # 统一 EVM Custom Errors +│ │ │ ├── Event.sol # 链上日志定义 +│ │ │ ├── QuestionV2.sol # 命题状态与哈希算法 +│ │ │ └── WTFMath.sol # 高精度定点数数学库 +│ │ ├── WTFERC6909.sol # 极简高效 ERC-6909 多代币实现 +│ │ └── WTFMarketV2.sol # 预测市场交易与资金池状态机 +│ └── lib/ # OpenZeppelin & Solady 标准依赖库 +│ +├── curve/ # 联合曲线与高阶数学计算库 +│ └── src/ +│ └── curves/ +│ ├── math/ # 幂律与 LDA 边际价求解器 +│ │ ├── PowerLDAMath.sol +│ │ ├── PowerMath.sol +│ │ └── LDAMath.sol +│ └── PowerLDACurveV2.sol # 联合曲线合约 +│ +└── mock/ # 测试辅助合约 + ├── MockERC20.sol # 支持无限 Mint 领水的 WUSD 抵押品 + └── TestProxy.sol # 极简 Delegatecall 可升级代理 +``` + +--- + +## 6. 编译、部署与测试指南 + +### 6.1 本地与 Robinhood Chain 测试网环境要求 +- **Node.js**: `>= 18.0.0` +- **Solidity 编译器**: `0.8.29` +- **EVM Target**: `cancun` (或 `paris` / `shanghai`,若目标链不支持 Cancun EIP-1153,可在 `MarketV2` 中使用标准 ReentrancyGuard) + +### 6.2 部署到 Robinhood Chain Testnet 快速配置 + +在 Hardhat 配置文件中添加测试网网络: +```javascript +module.exports = { + solidity: { + version: "0.8.29", + settings: { + evmVersion: "cancun", + optimizer: { enabled: true, runs: 200 } + } + }, + networks: { + robinhoodTestnet: { + url: "https://rpc.testnet.chain.robinhood.com", + chainId: 46630, + accounts: [process.env.PRIVATE_KEY] // 部署者私钥 + } + } +}; +``` + +### 6.3 部署核心步骤 +1. **部署抵押品 (WUSD)**:部署 `MockERC20("WTF USD", "WUSD", 18)`; +2. **部署联合曲线**:部署 `PowerLDACurveV2`; +3. **部署控制器代理**: + - 部署 `Registry` 库并链接部署 `WTFControllerV2` 实现; + - 部署 `TestProxy` 指向实现合约; + - 调用 `controller.initialize(admin, treasury, defaultFeeRate, delay)`; +4. **初始化参数与档位**: + - 授权抵押品与曲线进入白名单; + - 调用 `setMarketTier` 初始化 Tier 1 ($3k)、Tier 2 ($25k)、Tier 3 ($100k)。 + +--- + +## 7. 关键接口速查与开发示例 + +### 1) 创建预测市场 (`deployMarket`) +```solidity +QuestionParams memory qParams = QuestionParams({ + timestampEnd: block.timestamp + 7 days, + title: "WTFX?Robinhood Chain 主网本季度会上线吗?", + ancillaryData: "0x", + imageUri: "https://...", + outcomeNames: ["会", "不会"], + outcomeImageUris: ["", ""] +}); + +MarketParams memory mParams = MarketParams({ + parentTokenId: 0, + collateral: wusdAddress, + curve: curveAddress, + timestampStart: block.timestamp, + feeRate: 6000000000000000, // 0.6% + tierId: 1 // Tier 1: PvP 盘 +}); + +// otSeed = 1e18 (每选项 1 个 OT) +(bytes32 questionId, address market) = controller.deployMarket( + qParams, + mParams, + oracleAddress, + 1 ether +); +``` + +### 2) 买入指定结果代币 (`mintCollateralToExactOt`) +```solidity +// 在 market 合约中买入 10 个 Yes (tokenId = 1) +uint256 tokenId = 1; // 2^0 +uint256 otAmount = 10 ether; + +// 先 approve 给 market 合约抵押品 +wusd.approve(market, type(uint256).max); + +// 执行买入 +market.mintCollateralToExactOt( + msg.sender, + tokenId, + otAmount, + "" +); +``` + +### 3) 创作者裁决与结算 (`resolveOutcome` & `finaliseOutcome`) +```solidity +uint256 winningAnswer = 1; // 2^0 表示 Yes 赢 + +// 1. 提交裁决 +controller.resolveOutcome(questionId, winningAnswer); + +// 2. 定案并开启争议期 +controller.finaliseOutcome(questionId, winningAnswer); +``` + +### 4) 争议期后领取获胜收益 (`claim`) +```solidity +uint256[] memory tokenIds = new uint256[](1); +tokenIds[0] = 1; + +uint256[] memory amounts = new uint256[](1); +amounts[0] = 10 ether; // 销毁 10 个 Yes + +// 自动根据资金池总金额结算抵押品返回至接收者 +market.claim(msg.sender, tokenIds, amounts); +``` diff --git a/curve/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol b/curve/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol new file mode 100644 index 0000000..dd90d62 --- /dev/null +++ b/curve/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/IERC6909.sol) + +pragma solidity >=0.6.2; + +import {IERC165} from "../utils/introspection/IERC165.sol"; + +/** + * @dev Required interface of an ERC-6909 compliant contract, as defined in the + * https://eips.ethereum.org/EIPS/eip-6909[ERC]. + */ +interface IERC6909 is IERC165 { + /** + * @dev Emitted when the allowance of a `spender` for an `owner` is set for a token of type `id`. + * The new allowance is `amount`. + */ + event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount); + + /** + * @dev Emitted when `owner` grants or revokes operator status for a `spender`. + */ + event OperatorSet(address indexed owner, address indexed spender, bool approved); + + /** + * @dev Emitted when `amount` tokens of type `id` are moved from `sender` to `receiver` initiated by `caller`. + */ + event Transfer( + address caller, + address indexed sender, + address indexed receiver, + uint256 indexed id, + uint256 amount + ); + + /** + * @dev Returns the amount of tokens of type `id` owned by `owner`. + */ + function balanceOf(address owner, uint256 id) external view returns (uint256); + + /** + * @dev Returns the amount of tokens of type `id` that `spender` is allowed to spend on behalf of `owner`. + * + * NOTE: Does not include operator allowances. + */ + function allowance(address owner, address spender, uint256 id) external view returns (uint256); + + /** + * @dev Returns true if `spender` is set as an operator for `owner`. + */ + function isOperator(address owner, address spender) external view returns (bool); + + /** + * @dev Sets an approval to `spender` for `amount` of tokens of type `id` from the caller's tokens. An `amount` of + * `type(uint256).max` signifies an unlimited approval. + * + * Must return true. + */ + function approve(address spender, uint256 id, uint256 amount) external returns (bool); + + /** + * @dev Grants or revokes unlimited transfer permission of any token id to `spender` for the caller's tokens. + * + * Must return true. + */ + function setOperator(address spender, bool approved) external returns (bool); + + /** + * @dev Transfers `amount` of token type `id` from the caller's account to `receiver`. + * + * Must return true. + */ + function transfer(address receiver, uint256 id, uint256 amount) external returns (bool); + + /** + * @dev Transfers `amount` of token type `id` from `sender` to `receiver`. + * + * Must return true. + */ + function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool); +} + +/** + * @dev Optional extension of {IERC6909} that adds metadata functions. + */ +interface IERC6909Metadata is IERC6909 { + /** + * @dev Returns the name of the token of type `id`. + */ + function name(uint256 id) external view returns (string memory); + + /** + * @dev Returns the ticker symbol of the token of type `id`. + */ + function symbol(uint256 id) external view returns (string memory); + + /** + * @dev Returns the number of decimals for the token of type `id`. + */ + function decimals(uint256 id) external view returns (uint8); +} + +/** + * @dev Optional extension of {IERC6909} that adds content URI functions. + */ +interface IERC6909ContentURI is IERC6909 { + /** + * @dev Returns URI for the contract. + */ + function contractURI() external view returns (string memory); + + /** + * @dev Returns the URI for the token of type `id`. + */ + function tokenURI(uint256 id) external view returns (string memory); +} + +/** + * @dev Optional extension of {IERC6909} that adds a token supply function. + */ +interface IERC6909TokenSupply is IERC6909 { + /** + * @dev Returns the total supply of the token of type `id`. + */ + function totalSupply(uint256 id) external view returns (uint256); +} diff --git a/curve/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol b/curve/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol new file mode 100644 index 0000000..be1932f --- /dev/null +++ b/curve/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol @@ -0,0 +1,25 @@ +// 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); +} diff --git a/curve/lib/solady/src/utils/FixedPointMathLib.sol b/curve/lib/solady/src/utils/FixedPointMathLib.sol new file mode 100644 index 0000000..2353363 --- /dev/null +++ b/curve/lib/solady/src/utils/FixedPointMathLib.sol @@ -0,0 +1,1312 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.4; + +/// @notice Arithmetic library with operations for fixed-point numbers. +/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol) +/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) +library FixedPointMathLib { + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* CUSTOM ERRORS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev The operation failed, as the output exceeds the maximum value of uint256. + error ExpOverflow(); + + /// @dev The operation failed, as the output exceeds the maximum value of uint256. + error FactorialOverflow(); + + /// @dev The operation failed, due to an overflow. + error RPowOverflow(); + + /// @dev The mantissa is too big to fit. + error MantissaOverflow(); + + /// @dev The operation failed, due to an multiplication overflow. + error MulWadFailed(); + + /// @dev The operation failed, due to an multiplication overflow. + error SMulWadFailed(); + + /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. + error DivWadFailed(); + + /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. + error SDivWadFailed(); + + /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. + error MulDivFailed(); + + /// @dev The division failed, as the denominator is zero. + error DivFailed(); + + /// @dev The full precision multiply-divide operation failed, either due + /// to the result being larger than 256 bits, or a division by a zero. + error FullMulDivFailed(); + + /// @dev The output is undefined, as the input is less-than-or-equal to zero. + error LnWadUndefined(); + + /// @dev The input outside the acceptable domain. + error OutOfDomain(); + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* CONSTANTS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev The scalar of ETH and most ERC20s. + uint256 internal constant WAD = 1e18; + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* SIMPLIFIED FIXED POINT OPERATIONS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Equivalent to `(x * y) / WAD` rounded down. + function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. + if gt(x, div(not(0), y)) { + if y { + mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. + revert(0x1c, 0x04) + } + } + z := div(mul(x, y), WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded down. + function sMulWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`. + if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) { + mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`. + revert(0x1c, 0x04) + } + z := sdiv(z, WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. + function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := div(mul(x, y), WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. + function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := sdiv(mul(x, y), WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded up. + function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. + if iszero(eq(div(z, y), x)) { + if y { + mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. + revert(0x1c, 0x04) + } + } + z := add(iszero(iszero(mod(z, WAD))), div(z, WAD)) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks. + function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD)) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down. + function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. + if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { + mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. + revert(0x1c, 0x04) + } + z := div(mul(x, WAD), y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down. + function sDivWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, WAD) + // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`. + if iszero(mul(y, eq(sdiv(z, WAD), x))) { + mstore(0x00, 0x5c43740d) // `SDivWadFailed()`. + revert(0x1c, 0x04) + } + z := sdiv(z, y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. + function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := div(mul(x, WAD), y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. + function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := sdiv(mul(x, WAD), y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded up. + function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. + if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { + mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. + revert(0x1c, 0x04) + } + z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks. + function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) + } + } + + /// @dev Equivalent to `x` to the power of `y`. + /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`. + /// Note: This function is an approximation. + function powWad(int256 x, int256 y) internal pure returns (int256) { + // Using `ln(x)` means `x` must be greater than 0. + return expWad((lnWad(x) * y) / int256(WAD)); + } + + /// @dev Returns `exp(x)`, denominated in `WAD`. + /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln + /// Note: This function is an approximation. Monotonically increasing. + function expWad(int256 x) internal pure returns (int256 r) { + unchecked { + // When the result is less than 0.5 we return zero. + // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`. + if (x <= -41446531673892822313) return r; + + /// @solidity memory-safe-assembly + assembly { + // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as + // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`. + if iszero(slt(x, 135305999368893231589)) { + mstore(0x00, 0xa37bfec9) // `ExpOverflow()`. + revert(0x1c, 0x04) + } + } + + // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96` + // for more intermediate precision and a binary basis. This base conversion + // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78. + x = (x << 78) / 5 ** 18; + + // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers + // of two such that exp(x) = exp(x') * 2**k, where k is an integer. + // Solving this gives k = round(x / log(2)) and x' = x - k * log(2). + int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96; + x = x - k * 54916777467707473351141471128; + + // `k` is in the range `[-61, 195]`. + + // Evaluate using a (6, 7)-term rational approximation. + // `p` is made monic, we'll multiply by a scale factor later. + int256 y = x + 1346386616545796478920950773328; + y = ((y * x) >> 96) + 57155421227552351082224309758442; + int256 p = y + x - 94201549194550492254356042504812; + p = ((p * y) >> 96) + 28719021644029726153956944680412240; + p = p * x + (4385272521454847904659076985693276 << 96); + + // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. + int256 q = x - 2855989394907223263936484059900; + q = ((q * x) >> 96) + 50020603652535783019961831881945; + q = ((q * x) >> 96) - 533845033583426703283633433725380; + q = ((q * x) >> 96) + 3604857256930695427073651918091429; + q = ((q * x) >> 96) - 14423608567350463180887372962807573; + q = ((q * x) >> 96) + 26449188498355588339934803723976023; + + /// @solidity memory-safe-assembly + assembly { + // Div in assembly because solidity adds a zero check despite the unchecked. + // The q polynomial won't have zeros in the domain as all its roots are complex. + // No scaling is necessary because p is already `2**96` too large. + r := sdiv(p, q) + } + + // r should be in the range `(0.09, 0.25) * 2**96`. + + // We now need to multiply r by: + // - The scale factor `s ≈ 6.031367120`. + // - The `2**k` factor from the range reduction. + // - The `1e18 / 2**96` factor for base conversion. + // We do this all at once, with an intermediate result in `2**213` + // basis, so the final right shift is always by a positive amount. + r = int256( + (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k) + ); + } + } + + /// @dev Returns `ln(x)`, denominated in `WAD`. + /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln + /// Note: This function is an approximation. Monotonically increasing. + function lnWad(int256 x) internal pure returns (int256 r) { + /// @solidity memory-safe-assembly + assembly { + // We want to convert `x` from `10**18` fixed point to `2**96` fixed point. + // We do this by multiplying by `2**96 / 10**18`. But since + // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here + // and add `ln(2**96 / 10**18)` at the end. + + // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`. + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + // We place the check here for more optimal stack operations. + if iszero(sgt(x, 0)) { + mstore(0x00, 0x1615e638) // `LnWadUndefined()`. + revert(0x1c, 0x04) + } + // forgefmt: disable-next-item + r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), + 0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)) + + // Reduce range of x to (1, 2) * 2**96 + // ln(2^k * x) = k * ln(2) + ln(x) + x := shr(159, shl(r, x)) + + // Evaluate using a (8, 8)-term rational approximation. + // `p` is made monic, we will multiply by a scale factor later. + // forgefmt: disable-next-item + let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir. + sar(96, mul(add(43456485725739037958740375743393, + sar(96, mul(add(24828157081833163892658089445524, + sar(96, mul(add(3273285459638523848632254066296, + x), x))), x))), x)), 11111509109440967052023855526967) + p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857) + p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526) + p := sub(mul(p, x), shl(96, 795164235651350426258249787498)) + // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. + + // `q` is monic by convention. + let q := add(5573035233440673466300451813936, x) + q := add(71694874799317883764090561454958, sar(96, mul(x, q))) + q := add(283447036172924575727196451306956, sar(96, mul(x, q))) + q := add(401686690394027663651624208769553, sar(96, mul(x, q))) + q := add(204048457590392012362485061816622, sar(96, mul(x, q))) + q := add(31853899698501571402653359427138, sar(96, mul(x, q))) + q := add(909429971244387300277376558375, sar(96, mul(x, q))) + + // `p / q` is in the range `(0, 0.125) * 2**96`. + + // Finalization, we need to: + // - Multiply by the scale factor `s = 5.549…`. + // - Add `ln(2**96 / 10**18)`. + // - Add `k * ln(2)`. + // - Multiply by `10**18 / 2**96 = 5**18 >> 78`. + + // The q polynomial is known not to have zeros in the domain. + // No scaling required because p is already `2**96` too large. + p := sdiv(p, q) + // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`. + p := mul(1677202110996718588342820967067443963516166, p) + // Add `ln(2) * k * 5**18 * 2**192`. + // forgefmt: disable-next-item + p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p) + // Add `ln(2**96 / 10**18) * 5**18 * 2**192`. + p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p) + // Base conversion: mul `2**18 / 2**192`. + r := sar(174, p) + } + } + + /// @dev Returns `W_0(x)`, denominated in `WAD`. + /// See: https://en.wikipedia.org/wiki/Lambert_W_function + /// a.k.a. Product log function. This is an approximation of the principal branch. + /// Note: This function is an approximation. Monotonically increasing. + function lambertW0Wad(int256 x) internal pure returns (int256 w) { + // forgefmt: disable-next-item + unchecked { + if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`. + (int256 wad, int256 p) = (int256(WAD), x); + uint256 c; // Whether we need to avoid catastrophic cancellation. + uint256 i = 4; // Number of iterations. + if (w <= 0x1ffffffffffff) { + if (-0x4000000000000 <= w) { + i = 1; // Inputs near zero only take one step to converge. + } else if (w <= -0x3ffffffffffffff) { + i = 32; // Inputs near `-1/e` take very long to converge. + } + } else if (uint256(w >> 63) == uint256(0)) { + /// @solidity memory-safe-assembly + assembly { + // Inline log2 for more performance, since the range is small. + let v := shr(49, w) + let l := shl(3, lt(0xff, v)) + l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)), + 0x0706060506020504060203020504030106050205030304010505030400000000)), 49) + w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13)) + c := gt(l, 60) + i := add(2, add(gt(l, 53), c)) + } + } else { + int256 ll = lnWad(w = lnWad(w)); + /// @solidity memory-safe-assembly + assembly { + // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`. + w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll)) + i := add(3, iszero(shr(68, x))) + c := iszero(shr(143, x)) + } + if (c == uint256(0)) { + do { // If `x` is big, use Newton's so that intermediate values won't overflow. + int256 e = expWad(w); + /// @solidity memory-safe-assembly + assembly { + let t := mul(w, div(e, wad)) + w := sub(w, sdiv(sub(t, x), div(add(e, t), wad))) + } + if (p <= w) break; + p = w; + } while (--i != uint256(0)); + /// @solidity memory-safe-assembly + assembly { + w := sub(w, sgt(w, 2)) + } + return w; + } + } + do { // Otherwise, use Halley's for faster convergence. + int256 e = expWad(w); + /// @solidity memory-safe-assembly + assembly { + let t := add(w, wad) + let s := sub(mul(w, e), mul(x, wad)) + w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t))))) + } + if (p <= w) break; + p = w; + } while (--i != c); + /// @solidity memory-safe-assembly + assembly { + w := sub(w, sgt(w, 2)) + } + // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of + // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation. + if (c == uint256(0)) return w; + int256 t = w | 1; + /// @solidity memory-safe-assembly + assembly { + x := sdiv(mul(x, wad), t) + } + x = (t * (wad + lnWad(x))); + /// @solidity memory-safe-assembly + assembly { + w := sdiv(x, add(wad, t)) + } + } + } + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* GENERAL NUMBER UTILITIES */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Returns `a * b == x * y`, with full precision. + function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y) + internal + pure + returns (bool result) + { + /// @solidity memory-safe-assembly + assembly { + result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0)))) + } + } + + /// @dev Calculates `floor(x * y / d)` with full precision. + /// Throws if result overflows a uint256 or when `d` is zero. + /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv + function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // 512-bit multiply `[p1 p0] = x * y`. + // Compute the product mod `2**256` and mod `2**256 - 1` + // then use the Chinese Remainder Theorem to reconstruct + // the 512 bit result. The result is stored in two 256 + // variables such that `product = p1 * 2**256 + p0`. + + // Temporarily use `z` as `p0` to save gas. + z := mul(x, y) // Lower 256 bits of `x * y`. + for {} 1 {} { + // If overflows. + if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { + let mm := mulmod(x, y, not(0)) + let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. + + /*------------------- 512 by 256 division --------------------*/ + + // Make division exact by subtracting the remainder from `[p1 p0]`. + let r := mulmod(x, y, d) // Compute remainder using mulmod. + let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`. + // Make sure `z` is less than `2**256`. Also prevents `d == 0`. + // Placing the check here seems to give more optimal stack operations. + if iszero(gt(d, p1)) { + mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. + revert(0x1c, 0x04) + } + d := div(d, t) // Divide `d` by `t`, which is a power of two. + // Invert `d mod 2**256` + // Now that `d` is an odd number, it has an inverse + // modulo `2**256` such that `d * inv = 1 mod 2**256`. + // Compute the inverse by starting with a seed that is correct + // correct for four bits. That is, `d * inv = 1 mod 2**4`. + let inv := xor(2, mul(3, d)) + // Now use 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. + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128 + z := + mul( + // Divide [p1 p0] by the factors of two. + // Shift in bits from `p1` into `p0`. For this we need + // to flip `t` such that it is `2**256 / t`. + or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), + mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256 + ) + break + } + z := div(z, d) + break + } + } + } + + /// @dev Calculates `floor(x * y / d)` with full precision. + /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits. + /// Performs the full 512 bit calculation regardless. + function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d) + internal + pure + returns (uint256 z) + { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + let mm := mulmod(x, y, not(0)) + let p1 := sub(mm, add(z, lt(mm, z))) + let t := and(d, sub(0, d)) + let r := mulmod(x, y, d) + d := div(d, t) + let inv := xor(2, mul(3, d)) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + z := + mul( + or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), + mul(sub(2, mul(d, inv)), inv) + ) + } + } + + /// @dev Calculates `floor(x * y / d)` with full precision, rounded up. + /// Throws if result overflows a uint256 or when `d` is zero. + /// Credit to Uniswap-v3-core under MIT license: + /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol + function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + z = fullMulDiv(x, y, d); + /// @solidity memory-safe-assembly + assembly { + if mulmod(x, y, d) { + z := add(z, 1) + if iszero(z) { + mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. + revert(0x1c, 0x04) + } + } + } + } + + /// @dev Calculates `floor(x * y / 2 ** n)` with full precision. + /// Throws if result overflows a uint256. + /// Credit to Philogy under MIT license: + /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol + function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Temporarily use `z` as `p0` to save gas. + z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`. + for {} 1 {} { + if iszero(or(iszero(x), eq(div(z, x), y))) { + let k := and(n, 0xff) // `n`, cleaned. + let mm := mulmod(x, y, not(0)) + let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. + // | p1 | z | + // Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 | + // Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 | + // Check that final `z` doesn't overflow by checking that p1_0 = 0. + if iszero(shr(k, p1)) { + z := add(shl(sub(256, k), p1), shr(k, z)) + break + } + mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. + revert(0x1c, 0x04) + } + z := shr(and(n, 0xff), z) + break + } + } + } + + /// @dev Returns `floor(x * y / d)`. + /// Reverts if `x * y` overflows, or `d` is zero. + function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. + if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { + mstore(0x00, 0xad251c27) // `MulDivFailed()`. + revert(0x1c, 0x04) + } + z := div(z, d) + } + } + + /// @dev Returns `ceil(x * y / d)`. + /// Reverts if `x * y` overflows, or `d` is zero. + function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. + if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { + mstore(0x00, 0xad251c27) // `MulDivFailed()`. + revert(0x1c, 0x04) + } + z := add(iszero(iszero(mod(z, d))), div(z, d)) + } + } + + /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`. + function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) { + /// @solidity memory-safe-assembly + assembly { + let g := n + let r := mod(a, n) + for { let y := 1 } 1 {} { + let q := div(g, r) + let t := g + g := r + r := sub(t, mul(r, q)) + let u := x + x := y + y := sub(u, mul(y, q)) + if iszero(r) { break } + } + x := mul(eq(g, 1), add(x, mul(slt(x, 0), n))) + } + } + + /// @dev Returns `ceil(x / d)`. + /// Reverts if `d` is zero. + function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + if iszero(d) { + mstore(0x00, 0x65244e4e) // `DivFailed()`. + revert(0x1c, 0x04) + } + z := add(iszero(iszero(mod(x, d))), div(x, d)) + } + } + + /// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`. + function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(gt(x, y), sub(x, y)) + } + } + + /// @dev Returns `max(0, x - y)`. + function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(gt(x, y), sub(x, y)) + } + } + + /// @dev Returns `min(2 ** 256 - 1, x + y)`. + function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(sub(0, lt(add(x, y), x)), add(x, y)) + } + } + + /// @dev Returns `min(2 ** 256 - 1, x * y)`. + function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y)) + } + } + + /// @dev Returns `condition ? x : y`, without branching. + function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), iszero(condition))) + } + } + + /// @dev Returns `condition ? x : y`, without branching. + function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), iszero(condition))) + } + } + + /// @dev Returns `condition ? x : y`, without branching. + function ternary(bool condition, address x, address y) internal pure returns (address z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), iszero(condition))) + } + } + + /// @dev Returns `x != 0 ? x : y`, without branching. + function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(x, mul(y, iszero(x))) + } + } + + /// @dev Returns `x != bytes32(0) ? x : y`, without branching. + function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(x, mul(y, iszero(x))) + } + } + + /// @dev Returns `x != address(0) ? x : y`, without branching. + function coalesce(address x, address y) internal pure returns (address z) { + /// @solidity memory-safe-assembly + assembly { + z := or(x, mul(y, iszero(shl(96, x)))) + } + } + + /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`. + /// Reverts if the computation overflows. + function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`. + if x { + z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x` + let half := shr(1, b) // Divide `b` by 2. + // Divide `y` by 2 every iteration. + for { y := shr(1, y) } y { y := shr(1, y) } { + let xx := mul(x, x) // Store x squared. + let xxRound := add(xx, half) // Round to the nearest number. + // Revert if `xx + half` overflowed, or if `x ** 2` overflows. + if or(lt(xxRound, xx), shr(128, x)) { + mstore(0x00, 0x49f7642b) // `RPowOverflow()`. + revert(0x1c, 0x04) + } + x := div(xxRound, b) // Set `x` to scaled `xxRound`. + // If `y` is odd: + if and(y, 1) { + let zx := mul(z, x) // Compute `z * x`. + let zxRound := add(zx, half) // Round to the nearest number. + // If `z * x` overflowed or `zx + half` overflowed: + if or(xor(div(zx, x), z), lt(zxRound, zx)) { + // Revert if `x` is non-zero. + if x { + mstore(0x00, 0x49f7642b) // `RPowOverflow()`. + revert(0x1c, 0x04) + } + } + z := div(zxRound, b) // Return properly scaled `zxRound`. + } + } + } + } + } + + /// @dev Returns the square root of `x`, rounded down. + function sqrt(uint256 x) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`. + z := 181 // The "correct" value is 1, but this saves a multiplication later. + + // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad + // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. + + // Let `y = x / 2**r`. We check `y >= 2**(k + 8)` + // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`. + let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffffff, shr(r, x)))) + z := shl(shr(1, r), z) + + // Goal was to get `z*z*y` within a small factor of `x`. More iterations could + // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`. + // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small. + // That's not possible if `x < 256` but we can just verify those cases exhaustively. + + // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`. + // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`. + // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps. + + // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)` + // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`, + // with largest error when `s = 1` and when `s = 256` or `1/256`. + + // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`. + // Then we can estimate `sqrt(y)` using + // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`. + + // There is no overflow risk here since `y < 2**136` after the first branch above. + z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181. + + // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + + // If `x+1` is a perfect square, the Babylonian method cycles between + // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor. + // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division + z := sub(z, lt(div(x, z), z)) + } + } + + /// @dev Returns the cube root of `x`, rounded down. + /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license: + /// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy + /// Formally verified by xuwinnie: + /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf + function cbrt(uint256 x) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + // Makeshift lookup table to nudge the approximate log2 result. + z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3))) + // Newton-Raphson's. + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + // Round down. + z := sub(z, lt(div(x, mul(z, z)), z)) + } + } + + /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down. + function sqrtWad(uint256 x) internal pure returns (uint256 z) { + unchecked { + if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18); + z = (1 + sqrt(x)) * 10 ** 9; + z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1; + } + /// @solidity memory-safe-assembly + assembly { + z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down. + } + } + + /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down. + /// Formally verified by xuwinnie: + /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf + function cbrtWad(uint256 x) internal pure returns (uint256 z) { + unchecked { + if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36); + z = (1 + cbrt(x)) * 10 ** 12; + z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3; + } + /// @solidity memory-safe-assembly + assembly { + let p := x + for {} 1 {} { + if iszero(shr(229, p)) { + if iszero(shr(199, p)) { + p := mul(p, 100000000000000000) // 10 ** 17. + break + } + p := mul(p, 100000000) // 10 ** 8. + break + } + if iszero(shr(249, p)) { p := mul(p, 100) } + break + } + let t := mulmod(mul(z, z), z, p) + z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down. + } + } + + /// @dev Returns `sqrt(x * y)`. Also called the geometric mean. + function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) { + if (x == y) return x; + uint256 p = rawMul(x, y); + if (y == rawDiv(p, x)) return sqrt(p); + for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) { + if ((p = fullMulDivUnchecked(x, y, z)) >= z) break; + } + } + + /// @dev Returns the factorial of `x`. + function factorial(uint256 x) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := 1 + if iszero(lt(x, 58)) { + mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`. + revert(0x1c, 0x04) + } + for {} x { x := sub(x, 1) } { z := mul(z, x) } + } + } + + /// @dev Returns the log2 of `x`. + /// Equivalent to computing the index of the most significant bit (MSB) of `x`. + /// Returns 0 if `x` is zero. + function log2(uint256 x) internal pure returns (uint256 r) { + /// @solidity memory-safe-assembly + assembly { + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + // forgefmt: disable-next-item + r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), + 0x0706060506020504060203020504030106050205030304010505030400000000)) + } + } + + /// @dev Returns the log2 of `x`, rounded up. + /// Returns 0 if `x` is zero. + function log2Up(uint256 x) internal pure returns (uint256 r) { + r = log2(x); + /// @solidity memory-safe-assembly + assembly { + r := add(r, lt(shl(r, 1), x)) + } + } + + /// @dev Returns the log10 of `x`. + /// Returns 0 if `x` is zero. + function log10(uint256 x) internal pure returns (uint256 r) { + /// @solidity memory-safe-assembly + assembly { + if iszero(lt(x, 100000000000000000000000000000000000000)) { + x := div(x, 100000000000000000000000000000000000000) + r := 38 + } + if iszero(lt(x, 100000000000000000000)) { + x := div(x, 100000000000000000000) + r := add(r, 20) + } + if iszero(lt(x, 10000000000)) { + x := div(x, 10000000000) + r := add(r, 10) + } + if iszero(lt(x, 100000)) { + x := div(x, 100000) + r := add(r, 5) + } + r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999))))) + } + } + + /// @dev Returns the log10 of `x`, rounded up. + /// Returns 0 if `x` is zero. + function log10Up(uint256 x) internal pure returns (uint256 r) { + r = log10(x); + /// @solidity memory-safe-assembly + assembly { + r := add(r, lt(exp(10, r), x)) + } + } + + /// @dev Returns the log256 of `x`. + /// Returns 0 if `x` is zero. + function log256(uint256 x) internal pure returns (uint256 r) { + /// @solidity memory-safe-assembly + assembly { + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(shr(3, r), lt(0xff, shr(r, x))) + } + } + + /// @dev Returns the log256 of `x`, rounded up. + /// Returns 0 if `x` is zero. + function log256Up(uint256 x) internal pure returns (uint256 r) { + r = log256(x); + /// @solidity memory-safe-assembly + assembly { + r := add(r, lt(shl(shl(3, r), 1), x)) + } + } + + /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`. + /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent). + function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) { + /// @solidity memory-safe-assembly + assembly { + mantissa := x + if mantissa { + if iszero(mod(mantissa, 1000000000000000000000000000000000)) { + mantissa := div(mantissa, 1000000000000000000000000000000000) + exponent := 33 + } + if iszero(mod(mantissa, 10000000000000000000)) { + mantissa := div(mantissa, 10000000000000000000) + exponent := add(exponent, 19) + } + if iszero(mod(mantissa, 1000000000000)) { + mantissa := div(mantissa, 1000000000000) + exponent := add(exponent, 12) + } + if iszero(mod(mantissa, 1000000)) { + mantissa := div(mantissa, 1000000) + exponent := add(exponent, 6) + } + if iszero(mod(mantissa, 10000)) { + mantissa := div(mantissa, 10000) + exponent := add(exponent, 4) + } + if iszero(mod(mantissa, 100)) { + mantissa := div(mantissa, 100) + exponent := add(exponent, 2) + } + if iszero(mod(mantissa, 10)) { + mantissa := div(mantissa, 10) + exponent := add(exponent, 1) + } + } + } + } + + /// @dev Convenience function for packing `x` into a smaller number using `sci`. + /// The `mantissa` will be in bits [7..255] (the upper 249 bits). + /// The `exponent` will be in bits [0..6] (the lower 7 bits). + /// Use `SafeCastLib` to safely ensure that the `packed` number is small + /// enough to fit in the desired unsigned integer type: + /// ``` + /// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether)); + /// ``` + function packSci(uint256 x) internal pure returns (uint256 packed) { + (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`. + /// @solidity memory-safe-assembly + assembly { + if shr(249, x) { + mstore(0x00, 0xce30380c) // `MantissaOverflow()`. + revert(0x1c, 0x04) + } + packed := or(shl(7, x), packed) + } + } + + /// @dev Convenience function for unpacking a packed number from `packSci`. + function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) { + unchecked { + unpacked = (packed >> 7) * 10 ** (packed & 0x7f); + } + } + + /// @dev Returns the average of `x` and `y`. Rounds towards zero. + function avg(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = (x & y) + ((x ^ y) >> 1); + } + } + + /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity. + function avg(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = (x >> 1) + (y >> 1) + (x & y & 1); + } + } + + /// @dev Returns the absolute value of `x`. + function abs(int256 x) internal pure returns (uint256 z) { + unchecked { + z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255); + } + } + + /// @dev Returns the absolute distance between `x` and `y`. + function dist(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y)) + } + } + + /// @dev Returns the absolute distance between `x` and `y`. + function dist(int256 x, int256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y)) + } + } + + /// @dev Returns the minimum of `x` and `y`. + function min(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), lt(y, x))) + } + } + + /// @dev Returns the minimum of `x` and `y`. + function min(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), slt(y, x))) + } + } + + /// @dev Returns the maximum of `x` and `y`. + function max(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), gt(y, x))) + } + } + + /// @dev Returns the maximum of `x` and `y`. + function max(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), sgt(y, x))) + } + } + + /// @dev Returns `x`, bounded to `minValue` and `maxValue`. + function clamp(uint256 x, uint256 minValue, uint256 maxValue) + internal + pure + returns (uint256 z) + { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, minValue), gt(minValue, x))) + z := xor(z, mul(xor(z, maxValue), lt(maxValue, z))) + } + } + + /// @dev Returns `x`, bounded to `minValue` and `maxValue`. + function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, minValue), sgt(minValue, x))) + z := xor(z, mul(xor(z, maxValue), slt(maxValue, z))) + } + } + + /// @dev Returns greatest common divisor of `x` and `y`. + function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + for { z := x } y {} { + let t := y + y := mod(z, y) + z := t + } + } + } + + /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`, + /// with `t` clamped between `begin` and `end` (inclusive). + /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). + /// If `begins == end`, returns `t <= begin ? a : b`. + function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end) + internal + pure + returns (uint256) + { + if (begin > end) (t, begin, end) = (~t, ~begin, ~end); + if (t <= begin) return a; + if (t >= end) return b; + unchecked { + if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin); + return a - fullMulDiv(a - b, t - begin, end - begin); + } + } + + /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`. + /// with `t` clamped between `begin` and `end` (inclusive). + /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). + /// If `begins == end`, returns `t <= begin ? a : b`. + function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end) + internal + pure + returns (int256) + { + if (begin > end) (t, begin, end) = (~t, ~begin, ~end); + if (t <= begin) return a; + if (t >= end) return b; + // forgefmt: disable-next-item + unchecked { + if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a), + uint256(t - begin), uint256(end - begin))); + return int256(uint256(a) - fullMulDiv(uint256(a - b), + uint256(t - begin), uint256(end - begin))); + } + } + + /// @dev Returns if `x` is an even number. Some people may need this. + function isEven(uint256 x) internal pure returns (bool) { + return x & uint256(1) == uint256(0); + } + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* RAW NUMBER OPERATIONS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Returns `x + y`, without checking for overflow. + function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = x + y; + } + } + + /// @dev Returns `x + y`, without checking for overflow. + function rawAdd(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = x + y; + } + } + + /// @dev Returns `x - y`, without checking for underflow. + function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = x - y; + } + } + + /// @dev Returns `x - y`, without checking for underflow. + function rawSub(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = x - y; + } + } + + /// @dev Returns `x * y`, without checking for overflow. + function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = x * y; + } + } + + /// @dev Returns `x * y`, without checking for overflow. + function rawMul(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = x * y; + } + } + + /// @dev Returns `x / y`, returning 0 if `y` is zero. + function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := div(x, y) + } + } + + /// @dev Returns `x / y`, returning 0 if `y` is zero. + function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := sdiv(x, y) + } + } + + /// @dev Returns `x % y`, returning 0 if `y` is zero. + function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mod(x, y) + } + } + + /// @dev Returns `x % y`, returning 0 if `y` is zero. + function rawSMod(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := smod(x, y) + } + } + + /// @dev Returns `(x + y) % d`, return 0 if `d` if zero. + function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := addmod(x, y, d) + } + } + + /// @dev Returns `(x * y) % d`, return 0 if `d` if zero. + function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mulmod(x, y, d) + } + } +} diff --git a/curve/src/curves/CurveBase.sol b/curve/src/curves/CurveBase.sol new file mode 100644 index 0000000..acf19b9 --- /dev/null +++ b/curve/src/curves/CurveBase.sol @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +struct GuessParam { + uint256 otGuessMin; + uint256 otGuessMax; + uint256 otDeltaGuessOffchain; + uint256 maxIterations; + uint256 eps; +} + +library Guesser { + function calMid(GuessParam memory guess) internal pure returns (uint256) { + return (guess.otGuessMin + guess.otGuessMax + 1) / 2; + } +} diff --git a/curve/src/curves/PowerLDACurveV2.sol b/curve/src/curves/PowerLDACurveV2.sol new file mode 100644 index 0000000..c91da0d --- /dev/null +++ b/curve/src/curves/PowerLDACurveV2.sol @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import {IWTFCurve} from "@wtf/src/interfaces/IWTFCurve.sol"; +import {IRegistry} from "@wtf/src/interfaces/IRegistry.sol"; +import {PowerMath, PowerMint} from "@wtf/src/curves/math/PowerMath.sol"; +import {PowerLDAMint} from "@wtf/src/curves/math/PowerLDAMath.sol"; +import {LDAMath} from "@wtf/src/curves/math/LDAMath.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {Decoder} from "@wtf/lib/Decoder.sol"; +import {GuessParam} from "@wtf/src/curves/CurveBase.sol"; +import {FixedPointMathLib} from "@solady/utils/FixedPointMathLib.sol"; +import {IERC6909TokenSupply} from "@openzeppelin/contracts/interfaces/IERC6909.sol"; +import {IWTFMarket} from "@wtf/src/interfaces/IWTFMarket.sol"; +import {PowerRedeemV2} from "@wtf/src/curves/math/PowerMathV2.sol"; +import {RedeemMathV2} from "@wtf/lib/RedeemMathV2.sol"; + +contract PowerLDACurveV2 is IWTFCurve { + using PowerMath for PowerMath.CurveParams; + using FixedPointMathLib for uint256; + using WTFMath for uint256; + + struct MarketState { + RedeemMathV2.RedeemParams redeem; + LDAMath.LDAPremiumParams premium; + uint256 feeRate; + uint256 otCurrent; + uint256 tick; + } + + // PowerCurve + uint256 public immutable C1; + uint256 public immutable C2; + uint256 public immutable START; + + // Redeem + uint256 public immutable TIME_KINK_START; + uint256 public immutable TIME_KINK_END; + uint256 public immutable RATE_BASE_MIN; + uint256 public immutable RATE_BASE_MAX; + uint256 public immutable LS_ROOT; + + uint256 public immutable TICK; + + // LDA + uint256 public immutable PHI_DELTA_MAX; + uint256 public immutable WINDOW_STATIC; + + constructor( + uint256 _c1, + uint256 _c2, + uint256 _start, + uint256 _timeKinkStart, + uint256 _timeKinkEnd, + uint256 _rateBaseMin, + uint256 _rateBaseMax, + uint256 _lsRoot, + uint256 _tick, + uint256 _phiDeltaMax, + uint256 _windowFixed + ) { + C1 = _c1; + C2 = _c2; + START = _start; + // NOTE: "free" shares creates weird math problems especially when redeeming, so start from a non-free point + PowerMath.CurveParams memory curve = readCurve(); + if (!curve.isValid()) revert Errors.CurveInvalidCost(START); + + if (_timeKinkEnd <= _timeKinkStart) revert Errors.CurveInvalidStartEnd(); + TIME_KINK_START = _timeKinkStart; + TIME_KINK_END = _timeKinkEnd; + RATE_BASE_MIN = _rateBaseMin; + RATE_BASE_MAX = _rateBaseMax; + LS_ROOT = _lsRoot; + + TICK = _tick; + + PHI_DELTA_MAX = _phiDeltaMax; + WINDOW_STATIC = _windowFixed; + } + + /// @inheritdoc IWTFCurve + function calMarginalPrice(address market, uint256 tokenId) external view returns (uint256 price) { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + + price = PowerLDAMint.calMarginalPrice(curve, state.premium, state.otCurrent); + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + price = price.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + + /// @inheritdoc IWTFCurve + function calMintCostByOtDelta( + address market, + uint256 tokenId, + uint256 otDelta, + bytes calldata /*data*/ + ) + external + view + returns (uint256 collateralFromUser, uint256 collateralToTreasury) + { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + if (otDelta % state.tick != 0) revert Errors.CurveOtDeltaNotOnTick(otDelta, state.tick); + + (collateralFromUser, collateralToTreasury) = + PowerLDAMint.calSwap(curve, state.premium, state.feeRate, state.otCurrent, otDelta); + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + collateralFromUser = collateralFromUser.fullMulDivUp(10 ** collateralDecimals, WTFMath.WTF_ONE); + collateralToTreasury = collateralToTreasury.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + + /// @inheritdoc IWTFCurve + function calRedeemValueByOtDelta( + address market, + uint256 tokenId, + uint256 otDelta, + bytes calldata /*data*/ + ) + external + view + returns (uint256 collateralToUser, uint256 collateralToTreasury) + { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + if (otDelta % state.tick != 0) revert Errors.CurveOtDeltaNotOnTick(otDelta, state.tick); + + (collateralToUser, collateralToTreasury) = + PowerRedeemV2.calSwap(curve, state.redeem, state.feeRate, state.otCurrent, otDelta); + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + collateralToUser = collateralToUser.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + collateralToTreasury = collateralToTreasury.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + + /// @inheritdoc IWTFCurve + /// @notice seed does not pay LDA premiums + function calSeedCostByOtDeltas( + address market, + uint256[] calldata tokenIds, + uint256[] calldata otDeltas, + bytes calldata /*dataSwap*/ + ) external view returns (uint256[] memory collateralsFromUser, uint256[] memory collateralsToTreasury) { + if (tokenIds.length != otDeltas.length) revert Errors.MarketArrayLengthsMismatch(); + + PowerMath.CurveParams memory curve = readCurve(); + + uint256 len = tokenIds.length; + collateralsFromUser = new uint256[](len); + collateralsToTreasury = new uint256[](len); + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + for (uint256 i = 0; i < len; ++i) { + uint256 otDelta = otDeltas[i]; + if (otDelta == 0) continue; + + MarketState memory state = readMarketState(market, tokenIds[i]); + + // seed bypasses LDA premium + (uint256 collateralFromUser, uint256 collateralToTreasury) = + PowerMint.calSwap(curve, state.feeRate, state.otCurrent, otDelta); + collateralsFromUser[i] = collateralFromUser.fullMulDivUp(10 ** collateralDecimals, WTFMath.WTF_ONE); + collateralsToTreasury[i] = collateralToTreasury.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + } + + /// @inheritdoc IWTFCurve + function calOtDeltaByMintCost(address market, uint256 tokenId, uint256 collateralDelta, bytes calldata data) + external + view + returns (uint256 otDelta, uint256 collateralFromUser) + { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + + GuessParam memory guess = Decoder.decodeGuessParam(data); + if (guess.otDeltaGuessOffchain % state.tick != 0) { + revert Errors.CurveOtDeltaNotOnTick(guess.otDeltaGuessOffchain, state.tick); + } + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + uint256 collateralDeltaScaled = collateralDelta.fullMulDiv(WTFMath.WTF_ONE, 10 ** collateralDecimals); + + (otDelta, collateralFromUser) = PowerLDAMint.guessOtDelta( + curve, state.premium, state.feeRate, guess, collateralDeltaScaled, state.otCurrent, state.tick + ); + collateralFromUser = collateralFromUser.fullMulDivUp(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + + /// @inheritdoc IWTFCurve + function calOtDeltaByRedeemValue(address market, uint256 tokenId, uint256 collateralDelta, bytes calldata data) + external + view + returns (uint256 otDelta, uint256 collateralToUser) + { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + + GuessParam memory guess = Decoder.decodeGuessParam(data); + if (guess.otDeltaGuessOffchain % state.tick != 0) { + revert Errors.CurveOtDeltaNotOnTick(guess.otDeltaGuessOffchain, state.tick); + } + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + uint256 collateralDeltaScaled = collateralDelta.fullMulDiv(WTFMath.WTF_ONE, 10 ** collateralDecimals); + + (otDelta, collateralToUser) = PowerRedeemV2.guessOtDelta( + curve, state.redeem, state.feeRate, guess, collateralDeltaScaled, state.otCurrent, state.tick + ); + collateralToUser = collateralToUser.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + + /// @notice Read immutable curve params. + function readCurve() public view returns (PowerMath.CurveParams memory curve) { + curve = PowerMath.CurveParams({c1: C1, c2: C2, start: START}); + } + + /// @notice Read state of market required for calculations, including LDA premium. + function readMarketState(address market, uint256 tokenId) public view returns (MarketState memory state) { + address registry = IWTFMarket(market).registry(); + (, uint256 feeRate,, uint128 timestampEnd,,) = IRegistry(registry).getConfig(market); + + uint256 otCurrent = IERC6909TokenSupply(market).totalSupply(tokenId); + uint128 timestampStart = IWTFMarket(market).timestampStart(); + + RedeemMathV2.RedeemParams memory redeem = RedeemMathV2.newRedeemParams( + timestampStart, + timestampEnd, + block.timestamp.toUint128(), + TIME_KINK_START, + TIME_KINK_END, + RATE_BASE_MIN, + RATE_BASE_MAX, + LS_ROOT + ); + LDAMath.LDAPremiumParams memory premium = + LDAMath.newPremiumParams(PHI_DELTA_MAX, WINDOW_STATIC, timestampStart, timestampEnd, block.timestamp); + + state = MarketState({redeem: redeem, premium: premium, feeRate: feeRate, otCurrent: otCurrent, tick: TICK}); + } + + /// @inheritdoc IWTFCurve + function simCost(uint256 otSupply) external view returns (uint256 cost) { + PowerMath.CurveParams memory curve = readCurve(); + return curve.calCost(otSupply); + } + + /// @inheritdoc IWTFCurve + function simCost(address market, uint256 tokenId, uint256 otSupply) external view returns (uint256 cost) { + if (otSupply == 0) return 0; + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + (cost,) = PowerLDAMint.calSwap(curve, state.premium, 0, 0, otSupply); + } + + /// @inheritdoc IWTFCurve + function simMarginalPrice(uint256 otSupply) external view returns (uint256 price) { + PowerMath.CurveParams memory curve = readCurve(); + return curve.calMarginalPrice(otSupply); + } + + /// @inheritdoc IWTFCurve + function simMarginalPrice(address market, uint256 tokenId, uint256 otSupply) external view returns (uint256 price) { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + return PowerLDAMint.calMarginalPrice(curve, state.premium, otSupply); + } + + /// @inheritdoc IWTFCurve + /// @dev DO NOT RELY ON THIS FOR ONCHAIN LOGIC + function extrapolateMintForOffchainOnly(address market, uint256 tokenId, uint256 otFrom, uint256 otDelta) + external + view + returns (uint256 collateralFromUser, uint256 collateralToTreasury) + { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + + (collateralFromUser, collateralToTreasury) = + PowerLDAMint.calSwap(curve, state.premium, state.feeRate, otFrom, otDelta); + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + collateralFromUser = collateralFromUser.fullMulDivUp(10 ** collateralDecimals, WTFMath.WTF_ONE); + collateralToTreasury = collateralToTreasury.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + + /// @inheritdoc IWTFCurve + /// @dev DO NOT RELY ON THIS FOR ONCHAIN LOGIC + /// @dev same as PowerCurveSimplified.sol + function extrapolateRedeemForOffchainOnly(address market, uint256 tokenId, uint256 otFrom, uint256 otDelta) + external + view + returns (uint256 collateralToUser, uint256 collateralToTreasury) + { + PowerMath.CurveParams memory curve = readCurve(); + MarketState memory state = readMarketState(market, tokenId); + + (collateralToUser, collateralToTreasury) = + PowerRedeemV2.calSwap(curve, state.redeem, state.feeRate, otFrom, otDelta); + + uint256 collateralDecimals = IWTFMarket(market).collateralDecimals(); + collateralToUser = collateralToUser.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + collateralToTreasury = collateralToTreasury.fullMulDiv(10 ** collateralDecimals, WTFMath.WTF_ONE); + } + + /// @inheritdoc IWTFCurve + function simSeed(uint256[] calldata tokenIds, uint256[] calldata otDeltas, uint8 collateralDecimals, uint80 feeRate) + external + view + returns (uint256 collateralFromUserTotal, uint256 collateralToTreasuryTotal) + { + if (tokenIds.length != otDeltas.length) revert Errors.MarketArrayLengthsMismatch(); + + PowerMath.CurveParams memory curve = readCurve(); + uint256 len = tokenIds.length; + uint256 collateralScale = 10 ** collateralDecimals; + for (uint256 i = 0; i < len; ++i) { + if (otDeltas[i] == 0) continue; + + (uint256 collateralFromUser, uint256 collateralToTreasury) = + PowerMint.calSwap(curve, feeRate, 0, otDeltas[i]); + collateralFromUserTotal += collateralFromUser.fullMulDivUp(collateralScale, WTFMath.WTF_ONE); + collateralToTreasuryTotal += collateralToTreasury.fullMulDiv(collateralScale, WTFMath.WTF_ONE); + } + } + + function timeKink() external view returns (uint256) { + return TIME_KINK_START; + } +} diff --git a/curve/src/curves/math/LDAMath.sol b/curve/src/curves/math/LDAMath.sol new file mode 100644 index 0000000..7369f86 --- /dev/null +++ b/curve/src/curves/math/LDAMath.sol @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {FixedPointMathLib} from "@solady/utils/FixedPointMathLib.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; + +library LDAMath { + using FixedPointMathLib for uint256; + + uint256 private constant DYNAMIC_WINDOW_DENOM = 10; // 10% + + /** + * phi(t) = 1 + phiDeltaMax*(T-t)/T + * mint(x,t) = phi(t)*( cost(phi(t)*(x+delta)) - cost(phi(t)*x) ) + * marginal_price(x,t) = phi(t)^2 * d cost(phi(t)*x)/dx + */ + struct LDAPremiumParams { + uint256 phi; + uint256 phiSquared; + } + + function newPremiumParams( + uint256 phiDeltaMax, + uint256 windowFixed, + uint256 timeStart, + uint256 timeEnd, + uint256 timeMint + ) internal pure returns (LDAPremiumParams memory premium) { + if (timeEnd < timeStart) revert Errors.CurveInvalidStartEnd(); + + // note: guard clause above guarantees timeEnd >= timeStart + uint256 duration = timeEnd - timeStart; + uint256 windowDynamic = duration / DYNAMIC_WINDOW_DENOM; + uint256 window = WTFMath.min(windowDynamic, windowFixed); + if (window == 0) return _premiumLess(); + + uint256 elapsed = timeMint > timeStart ? timeMint - timeStart : 0; + if (elapsed >= window) return _premiumLess(); + + if (phiDeltaMax == 0) return _premiumLess(); + uint256 phi = WTFMath.WTF_ONE + phiDeltaMax.fullMulDivUp(window - elapsed, window); + uint256 phiSquared = phi.fullMulDivUp(phi, WTFMath.WTF_ONE); + + premium = LDAPremiumParams({phi: phi, phiSquared: phiSquared}); + } + + function hasPremium(LDAPremiumParams memory self) internal pure returns (bool) { + return self.phi > WTFMath.WTF_ONE; + } + + function applyPremiumToSupply(LDAPremiumParams memory self, uint256 supply) internal pure returns (uint256) { + return supply.fullMulDiv(self.phi, WTFMath.WTF_ONE); + } + + function applyPremiumToSupplyUp(LDAPremiumParams memory self, uint256 supply) internal pure returns (uint256) { + return supply.fullMulDivUp(self.phi, WTFMath.WTF_ONE); + } + + function applyPremiumToCost(LDAPremiumParams memory self, uint256 collateralCost) internal pure returns (uint256) { + return collateralCost.fullMulDivUp(self.phi, WTFMath.WTF_ONE); + } + + function applyPremiumToPrice(LDAPremiumParams memory self, uint256 rawPrice) internal pure returns (uint256) { + return rawPrice.fullMulDiv(self.phiSquared, WTFMath.WTF_ONE); + } + + function _premiumLess() private pure returns (LDAPremiumParams memory) { + return LDAPremiumParams({phi: WTFMath.WTF_ONE, phiSquared: WTFMath.WTF_ONE}); + } +} diff --git a/curve/src/curves/math/PowerLDAMath.sol b/curve/src/curves/math/PowerLDAMath.sol new file mode 100644 index 0000000..9611176 --- /dev/null +++ b/curve/src/curves/math/PowerLDAMath.sol @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import {FixedPointMathLib} from "@solady/utils/FixedPointMathLib.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {GuessParam, Guesser} from "@wtf/src/curves/CurveBase.sol"; +import {PowerMath, PowerMint, stepFromDiff} from "@wtf/src/curves/math/PowerMath.sol"; +import {LDAMath} from "@wtf/src/curves/math/LDAMath.sol"; + +library PowerLDAMint { + using PowerMath for PowerMath.CurveParams; + using LDAMath for LDAMath.LDAPremiumParams; + using FixedPointMathLib for uint256; + using Guesser for GuessParam; + + struct GuessPointer { + uint256 iter; + uint256 tickCurr; + uint256 collateralDeltaLast; + } + + function calSwap( + PowerMath.CurveParams memory curve, + LDAMath.LDAPremiumParams memory premium, + uint256 feeRate, + uint256 otSupply, + uint256 otDelta + ) internal pure returns (uint256 collateralFromUser, uint256 collateralToTreasury) { + // mint(x,t) = phi(t)*( cost(phi(t)*(x+delta)) - cost(phi(t)*x) ) + if (!premium.hasPremium()) { + return PowerMint.calSwap(curve, feeRate, otSupply, otDelta); + } + + if (otDelta == 0) revert Errors.MarketSwapAmountCannotBeZero(); + + uint256 otFromScaled = premium.applyPremiumToSupply(otSupply); + uint256 otToScaled = premium.applyPremiumToSupplyUp(otSupply + otDelta); + uint256 collateralFrom = curve.calCost(otFromScaled); + uint256 collateralTo = curve.calCostUp(otToScaled); + + // GOAL: maximize collateralFromUser => user pays highest estimated cost + // NOTE: it cannot be -ve, a -ve area implies you get paid to buy outcomes + uint256 collateralCost = collateralTo > collateralFrom ? collateralTo - collateralFrom : 1; + collateralCost = premium.applyPremiumToCost(collateralCost); + + // treasury takes additional %, user pays another extra for mints + collateralToTreasury = collateralCost.fullMulDivUp(feeRate, WTFMath.WTF_ONE); + collateralFromUser = collateralCost + collateralToTreasury; + } + + function calMarginalPrice( + PowerMath.CurveParams memory curve, + LDAMath.LDAPremiumParams memory premium, + uint256 otSupply + ) internal pure returns (uint256) { + // marginal_price(x,t) = phi(t)^2 * d cost(phi(t)*x)/dx + if (!premium.hasPremium()) { + return curve.calMarginalPrice(otSupply); + } + + uint256 scaledSupply = premium.applyPremiumToSupply(otSupply); + uint256 rawPrice = curve.calMarginalPrice(scaledSupply); + return premium.applyPremiumToPrice(rawPrice); + } + + /** + * swap (exactIn) collateral -> ? ot + * + * @dev guess can be unreachable (especially with large ticks & small target) as 1 tick can exceed the target + */ + function guessOtDelta( + PowerMath.CurveParams memory curve, + LDAMath.LDAPremiumParams memory premium, + uint256 feeRate, + GuessParam memory guess, + uint256 collateralDeltaTarget, + uint256 otSupply, + uint256 tick + ) + internal + pure + returns ( + uint256, /*otDeltaGuess*/ + uint256 /*collateralDeltaRequired*/ + ) + { + if (!premium.hasPremium()) { + return PowerMint.guessOtDelta(curve, feeRate, guess, collateralDeltaTarget, otSupply, tick); + } + + GuessPointer memory ptr; + guess.otGuessMin = 0; + guess.otGuessMax = 0; + + // 1. set current tick pointer + ptr.tickCurr = _getTickPtr(curve, premium, guess, collateralDeltaTarget, otSupply, tick); + + // 2. refine both bounds via discrete newton & current tick pointer (must use ticks, else it degrades) + bool isSolved = _refineNewton(curve, premium, feeRate, guess, ptr, collateralDeltaTarget, otSupply, tick); + if (isSolved) { + return (ptr.tickCurr * tick, ptr.collateralDeltaLast); + } + + // 3. binary search with refined bounds + return _binarySearch(curve, premium, feeRate, guess, ptr, collateralDeltaTarget, otSupply, tick); + } + + function _getTickPtr( + PowerMath.CurveParams memory curve, + LDAMath.LDAPremiumParams memory premium, + GuessParam memory guess, + uint256 collateralDeltaTarget, + uint256 otSupply, + uint256 tick + ) private pure returns (uint256 tickCurr) { + if (guess.otDeltaGuessOffchain != 0) { + tickCurr = guess.otDeltaGuessOffchain / tick; + if (tickCurr == 0) tickCurr = 1; + } else { + uint256 price = PowerLDAMint.calMarginalPrice(curve, premium, otSupply); + if (price == 0) price = 1; + tickCurr = collateralDeltaTarget.fullMulDiv(WTFMath.WTF_ONE, price) / tick; + if (tickCurr == 0) tickCurr = 1; + } + } + + function _refineNewton( + PowerMath.CurveParams memory curve, + LDAMath.LDAPremiumParams memory premium, + uint256 feeRate, + GuessParam memory guess, + GuessPointer memory ptr, + uint256 collateralDeltaTarget, + uint256 otSupply, + uint256 tick + ) private pure returns (bool isSolved) { + for (ptr.iter = 0; ptr.iter < guess.maxIterations; ++ptr.iter) { + uint256 otDeltaGuessCurr = ptr.tickCurr * tick; + (uint256 collateralDelta,) = PowerLDAMint.calSwap(curve, premium, feeRate, otSupply, otDeltaGuessCurr); + + // hit target by chance return early + if (WTFMath.isASmallerApproxB(collateralDelta, collateralDeltaTarget, guess.eps)) { + ptr.collateralDeltaLast = collateralDelta; + return true; + } + + uint256 price = PowerLDAMint.calMarginalPrice(curve, premium, otSupply + otDeltaGuessCurr); + if (price == 0) price = 1; + + if (collateralDelta > collateralDeltaTarget) { + // set one bound (case: overguess) + guess.otGuessMax = ptr.tickCurr; + + // no solution: target collateral is less than 1 tick + if (ptr.tickCurr == 1) { + revert Errors.GuessTargetUnreachable(collateralDelta, collateralDeltaTarget); + } + if (guess.otGuessMin > 0) return false; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDelta - collateralDeltaTarget, price, tick); + ptr.tickCurr = ptr.tickCurr > tickStep ? ptr.tickCurr - tickStep : 1; + } else { + // set one bound (case: underguess) + guess.otGuessMin = ptr.tickCurr; + if (guess.otGuessMax > 0) return false; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDeltaTarget - collateralDelta, price, tick); + ptr.tickCurr += tickStep; + } + } + revert Errors.GuessExceedMaxInterpolationIterations(guess.maxIterations); + } + + function _binarySearch( + PowerMath.CurveParams memory curve, + LDAMath.LDAPremiumParams memory premium, + uint256 feeRate, + GuessParam memory guess, + GuessPointer memory ptr, + uint256 collateralDeltaTarget, + uint256 otSupply, + uint256 tick + ) private pure returns (uint256, uint256) { + for (ptr.iter = 0; ptr.iter < guess.maxIterations; ++ptr.iter) { + uint256 tickGuess = guess.calMid(); + uint256 otDeltaGuessCurr = tickGuess * tick; + (ptr.collateralDeltaLast,) = calSwap(curve, premium, feeRate, otSupply, otDeltaGuessCurr); + + if (WTFMath.isASmallerApproxB(ptr.collateralDeltaLast, collateralDeltaTarget, guess.eps)) { + return (otDeltaGuessCurr, ptr.collateralDeltaLast); + } + + if (ptr.collateralDeltaLast <= collateralDeltaTarget) { + if (tickGuess == guess.otGuessMin) break; + guess.otGuessMin = tickGuess; + } else { + if (tickGuess == guess.otGuessMax) break; + guess.otGuessMax = tickGuess; + } + } + if (ptr.iter >= guess.maxIterations) { + revert Errors.GuessExceedMaxIterations(guess.maxIterations); + } else { + // show no solution (clearer) + revert Errors.GuessTargetUnreachable(ptr.collateralDeltaLast, collateralDeltaTarget); + } + } +} diff --git a/curve/src/curves/math/PowerMath.sol b/curve/src/curves/math/PowerMath.sol new file mode 100644 index 0000000..e39f96f --- /dev/null +++ b/curve/src/curves/math/PowerMath.sol @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +import "@solady/utils/FixedPointMathLib.sol"; +import "@wtf/lib/WTFMath.sol"; +import "@wtf/lib/LogExpMath.sol"; +import "@wtf/lib/RedeemMath.sol"; +import "@wtf/lib/Errors.sol"; +import "@wtf/src/curves/CurveBase.sol"; + +function stepFromDiff(uint256 collateralDiff, uint256 price, uint256 tick) pure returns (uint256) { + uint256 tickStep = FixedPointMathLib.fullMulDivUp(collateralDiff, WTFMath.WTF_ONE, price); + tickStep = (tickStep + tick - 1) / tick; + if (tickStep == 0) tickStep = 1; + return tickStep; +} + +library PowerMint { + using PowerMath for PowerMath.CurveParams; + using FixedPointMathLib for uint256; + using Guesser for GuessParam; + + function calSwap(PowerMath.CurveParams memory curve, uint256 feeRate, uint256 otSupply, uint256 otDelta) + internal + pure + returns (uint256 collateralFromUser, uint256 collateralToTreasury) + { + // collateral to pool = cost + // fee to treasury = cost * feeRate + // user pays cost * (1 + feeRate) + if (otDelta == 0) revert Errors.MarketSwapAmountCannotBeZero(); + + uint256 otFrom = otSupply; + uint256 otTo = otFrom + otDelta; + uint256 collateralFrom = curve.calCost(otFrom); + uint256 collateralTo = curve.calCostUp(otTo); + + // GOAL: maximize collateralFromUser => user pays highest estimated cost + // NOTE: it cannot be -ve, a -ve area implies you get paid to buy outcomes + uint256 collateralCost = collateralTo > collateralFrom ? collateralTo - collateralFrom : 1; + + // treasury takes additional %, user pays another extra for mints + collateralToTreasury = collateralCost.fullMulDivUp(feeRate, WTFMath.WTF_ONE); + collateralFromUser = collateralCost + collateralToTreasury; + } + + /** + * swap (exactIn) collateral -> ? ot + * + * @dev guess can be unreachable (especially with large ticks & small target) as 1 tick can exceed the target + */ + function guessOtDelta( + PowerMath.CurveParams memory curve, + uint256 feeRate, + GuessParam memory guess, + uint256 collateralDeltaTarget, + uint256 otSupply, + uint256 tick + ) + internal + pure + returns ( + uint256, /*otDeltaGuess*/ + uint256 /*collateralDeltaRequired*/ + ) + { + // A LOT easier to guess by ticks => convert discontinuous search space {1000, 2000, 3000,...} to {1, 2, 3,...} + // guess.otGuessMin = tickLower, guess.otGuessMax = tickUpper + + // 0. save current tick pointer for refining bounds + uint256 tickCurr; + guess.otGuessMin = 0; + guess.otGuessMax = 0; + + // 1. set current tick pointer + if (guess.otDeltaGuessOffchain != 0) { + tickCurr = guess.otDeltaGuessOffchain / tick; // note: may not be multiplier of tick? + if (tickCurr == 0) tickCurr = 1; + } else { + uint256 price = curve.calMarginalPrice(otSupply); + if (price == 0) price = 1; + tickCurr = collateralDeltaTarget.fullMulDiv(WTFMath.WTF_ONE, price) / tick; + if (tickCurr == 0) tickCurr = 1; + } + + // 2. refine both bounds via discrete newton & current tick pointer (must use ticks, else it degrades) + uint256 iter; + for (iter = 0; iter < guess.maxIterations; ++iter) { + uint256 otDeltaGuessCurr = tickCurr * tick; + (uint256 collateralDelta,) = PowerMint.calSwap(curve, feeRate, otSupply, otDeltaGuessCurr); + + // hit target by chance return early + if (WTFMath.isASmallerApproxB(collateralDelta, collateralDeltaTarget, guess.eps)) { + return (otDeltaGuessCurr, collateralDelta); + } + + uint256 price = curve.calMarginalPrice(otSupply + otDeltaGuessCurr); + if (price == 0) price = 1; + + if (collateralDelta > collateralDeltaTarget) { + // set one bound (case: overguess) + guess.otGuessMax = tickCurr; + + // no solution: target collateral is less than 1 tick + if (tickCurr == 1) { + revert Errors.GuessTargetUnreachable(collateralDelta, collateralDeltaTarget); + } + + if (guess.otGuessMin > 0) break; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDelta - collateralDeltaTarget, price, tick); + tickCurr = tickCurr > tickStep ? tickCurr - tickStep : 1; + } else { + // set one bound (case: underguess) + guess.otGuessMin = tickCurr; + if (guess.otGuessMax > 0) break; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDeltaTarget - collateralDelta, price, tick); + tickCurr += tickStep; + } + } + if (iter >= guess.maxIterations) { + revert Errors.GuessExceedMaxInterpolationIterations(guess.maxIterations); + } + + // 3. binary search with refined bounds + uint256 collateralDeltaLast; + for (iter = 0; iter < guess.maxIterations; ++iter) { + uint256 tickGuess = guess.calMid(); + uint256 otDeltaGuessCurr = tickGuess * tick; + (collateralDeltaLast,) = PowerMint.calSwap(curve, feeRate, otSupply, otDeltaGuessCurr); + + if (WTFMath.isASmallerApproxB(collateralDeltaLast, collateralDeltaTarget, guess.eps)) { + return (otDeltaGuessCurr, collateralDeltaLast); + } + + if (collateralDeltaLast <= collateralDeltaTarget) { + if (tickGuess == guess.otGuessMin) break; + guess.otGuessMin = tickGuess; + } else { + if (tickGuess == guess.otGuessMax) break; + guess.otGuessMax = tickGuess; + } + } + if (iter >= guess.maxIterations) { + revert Errors.GuessExceedMaxIterations(guess.maxIterations); + } else { + // show no solution (clearer) + revert Errors.GuessTargetUnreachable(collateralDeltaLast, collateralDeltaTarget); + } + } +} + +library PowerRedeem { + using PowerMath for PowerMath.CurveParams; + using FixedPointMathLib for uint256; + using Guesser for GuessParam; + + struct GuessPointer { + uint256 iter; + uint256 tickMax; + uint256 tickCurr; + uint256 collateralDeltaLast; + } + + function calSwap( + PowerMath.CurveParams memory curve, + RedeemMath.RedeemParams memory redeem, + uint256 feeRate, + uint256 otSupply, + uint256 otDelta + ) internal pure returns (uint256 collateralToUser, uint256 collateralToTreasury) { + // collateral from pool = cost * (1-taxRate) + // fee to treasury = cost * (1-taxRate) * (feeRate) + if (otDelta == 0) revert Errors.MarketSwapAmountCannotBeZero(); + + uint256 otFrom = otSupply; + uint256 otTo = otFrom - otDelta; + uint256 collateralFrom = curve.calCost(otFrom); + uint256 collateralTo = curve.calCostUp(otTo); + // NOTE: it cannot be -ve, a -ve area implies you pay to sell outcomes + // GOAL: minimize collateralTotal => user receives lowest estimated value + uint256 collateralTotal = 0; + if (collateralFrom > collateralTo) { + collateralTotal = collateralFrom - collateralTo; + } + + uint256 taxRate = RedeemMath.calRedeemTaxRate(redeem, otFrom + curve.start, otDelta + curve.start); + uint256 collateralFromPool = collateralTotal.fullMulDiv(WTFMath.WTF_ONE - taxRate, WTFMath.WTF_ONE); + collateralToTreasury = collateralFromPool.fullMulDivUp(feeRate, WTFMath.WTF_ONE); + collateralToUser = collateralFromPool - collateralToTreasury; + } + + /** + * swap ? ot -> (exactOut) collateral + * + * @dev guess can be unreachable (especially with large ticks): + * 1. collateral amount is too small, thus 1 tick exceeds the target + * 2. collateral amount is too large, thus entire redeeming ot supply exceeds the target + * @dev redeem formula changes wrt to otDeltaGuess, leading to possible edge cases + */ + function guessOtDelta( + PowerMath.CurveParams memory curve, + RedeemMath.RedeemParams memory redeem, + uint256 feeRate, + GuessParam memory guess, + uint256 collateralDeltaTarget, + uint256 otSupply, + uint256 tick + ) + internal + pure + returns ( + uint256, /*otDeltaGuess*/ + uint256 /*collateralDeltaReturned*/ + ) + { + // A LOT easier to guess by ticks => convert discontinuous search space {1000, 2000, 3000,...} to {1, 2, 3,...} + // guess.otGuessMin = tickLower, guess.otGuessMax = tickUpper + + // no solution: nothing to redeem + if (otSupply < tick) { + revert Errors.GuessTargetUnreachable(0, collateralDeltaTarget); + } + + // 0. save current tick pointer for refining bounds + GuessPointer memory ptr; + ptr.tickCurr = 0; + ptr.tickMax = otSupply / tick; + guess.otGuessMin = 0; + guess.otGuessMax = 0; + + // 1. set current tick pointer + if (guess.otDeltaGuessOffchain != 0) { + ptr.tickCurr = WTFMath.clamp(guess.otDeltaGuessOffchain / tick, 1, ptr.tickMax); // note: may not be multiplier of tick? + } else { + uint256 price = curve.calMarginalPrice(otSupply); + if (price == 0) price = 1; + ptr.tickCurr = WTFMath.clamp(collateralDeltaTarget.fullMulDiv(WTFMath.WTF_ONE, price) / tick, 1, ptr.tickMax); + } + + // 2. refine both bounds via discrete newton & current tick pointer (must use ticks, else it degrades) + for (ptr.iter = 0; ptr.iter < guess.maxIterations; ++ptr.iter) { + uint256 otDeltaGuessCurr = ptr.tickCurr * tick; + (uint256 collateralDelta,) = PowerRedeem.calSwap(curve, redeem, feeRate, otSupply, otDeltaGuessCurr); + + // hit target by chance return early + if (WTFMath.isASmallerApproxB(collateralDelta, collateralDeltaTarget, guess.eps)) { + return (otDeltaGuessCurr, collateralDelta); + } + + // otSupply >= otDeltaGuessCurr since clamped earlier + uint256 price = curve.calMarginalPrice(otSupply - otDeltaGuessCurr); // note: not exactly the derivative when redeem + if (price == 0) price = 1; + + if (collateralDelta > collateralDeltaTarget) { + // set one bound (case: overguess) + guess.otGuessMax = ptr.tickCurr; + + // no solution: target collateral is less than 1 tick + if (ptr.tickCurr == 1) { + revert Errors.GuessTargetUnreachable(collateralDelta, collateralDeltaTarget); + } + + if (guess.otGuessMin > 0) break; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDelta - collateralDeltaTarget, price, tick); + ptr.tickCurr = ptr.tickCurr > tickStep ? ptr.tickCurr - tickStep : 1; + } else { + // set one bound (case: underguess) + guess.otGuessMin = ptr.tickCurr; + + // no solution: target collateral is more than supply's tick + if (ptr.tickCurr == ptr.tickMax) { + revert Errors.GuessTargetUnreachable(collateralDelta, collateralDeltaTarget); + } + + if (guess.otGuessMax > 0) break; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDeltaTarget - collateralDelta, price, tick); + ptr.tickCurr = WTFMath.clamp(ptr.tickCurr + tickStep, 1, ptr.tickMax); + } + } + if (ptr.iter >= guess.maxIterations) { + revert Errors.GuessExceedMaxInterpolationIterations(guess.maxIterations); + } + + // 3. binary search with refined bounds + for (ptr.iter = 0; ptr.iter < guess.maxIterations; ++ptr.iter) { + uint256 tickGuess = guess.calMid(); + uint256 otDeltaGuessCurr = tickGuess * tick; + (ptr.collateralDeltaLast,) = PowerRedeem.calSwap(curve, redeem, feeRate, otSupply, otDeltaGuessCurr); + + if (WTFMath.isASmallerApproxB(ptr.collateralDeltaLast, collateralDeltaTarget, guess.eps)) { + return (otDeltaGuessCurr, ptr.collateralDeltaLast); + } + + if (ptr.collateralDeltaLast <= collateralDeltaTarget) { + if (tickGuess == guess.otGuessMin) break; + guess.otGuessMin = tickGuess; + } else { + if (tickGuess == guess.otGuessMax) break; + guess.otGuessMax = tickGuess; + } + } + if (ptr.iter >= guess.maxIterations) { + revert Errors.GuessExceedMaxIterations(guess.maxIterations); + } else { + // show no solution (clearer) + revert Errors.GuessTargetUnreachable(ptr.collateralDeltaLast, collateralDeltaTarget); + } + } +} + +library PowerMath { + using LogExpMath for uint256; + using FixedPointMathLib for uint256; + using PowerMath for CurveParams; + + /** + * cost(x) = x^(c1+1)/c2 + * marginal_price(x) = d cost(x)/dx = (c1+1)*x^c1/c2 + * forward_price(x) = cost(x+1) - cost(x) + */ + struct CurveParams { + uint256 c1; + uint256 c2; + uint256 start; + } + + function calCost(CurveParams memory self, uint256 otSupply) internal pure returns (uint256) { + // cost(x) = x^(c1+1)/c2 + uint256 numerator = (otSupply + self.start).pow(self.c1 + LogExpMath.UONE_18); + return numerator.fullMulDiv(WTFMath.WTF_ONE, self.c2); + } + + function calCostUp(CurveParams memory self, uint256 otSupply) internal pure returns (uint256) { + // cost(x) = x^(c1+1)/c2 + uint256 numerator = (otSupply + self.start).pow(self.c1 + LogExpMath.UONE_18); + return numerator.fullMulDivUp(WTFMath.WTF_ONE, self.c2); + } + + function calMarginalPrice(CurveParams memory self, uint256 otSupply) internal pure returns (uint256) { + // marginal_price(x) = d cost(x)/dx = (c1+1)*x^c1/c2 + uint256 xPowC1 = (otSupply + self.start).pow(self.c1); + return (self.c1 + WTFMath.WTF_ONE).fullMulDiv(xPowC1, self.c2); + } + + function isValid(CurveParams memory self) internal pure returns (bool) { + uint256 costStart = self.calCost(0); + uint256 price = self.calMarginalPrice(0); + return (self.start >= WTFMath.toUint256(LogExpMath.LN_36_UPPER_BOUND)) && (costStart != 0) && (price != 0); + } +} diff --git a/curve/src/curves/math/PowerMathV2.sol b/curve/src/curves/math/PowerMathV2.sol new file mode 100644 index 0000000..56aced1 --- /dev/null +++ b/curve/src/curves/math/PowerMathV2.sol @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +import {FixedPointMathLib} from "@solady/utils/FixedPointMathLib.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {Guesser, GuessParam} from "@wtf/src/curves/CurveBase.sol"; +import {PowerMath, stepFromDiff} from "@wtf/src/curves/math/PowerMath.sol"; +import {RedeemMathV2} from "@wtf/lib/RedeemMathV2.sol"; + +/** + * @dev There is no PowerMintV2 as only redeem formulas are upgraded. + * Please use PowerMint or PowerLDAMint. + */ +library PowerRedeemV2 { + using PowerMath for PowerMath.CurveParams; + using FixedPointMathLib for uint256; + using Guesser for GuessParam; + + struct GuessPointer { + uint256 iter; + uint256 tickMax; + uint256 tickCurr; + uint256 collateralDeltaLast; + } + + function calSwap( + PowerMath.CurveParams memory curve, + RedeemMathV2.RedeemParams memory redeem, + uint256 feeRate, + uint256 otSupply, + uint256 otDelta + ) internal pure returns (uint256 collateralToUser, uint256 collateralToTreasury) { + // collateral from pool = cost * (1 - taxRate) + // fee to treasury = cost * (1 - taxRate) * feeRate + if (otDelta == 0) revert Errors.MarketSwapAmountCannotBeZero(); + + uint256 otFrom = otSupply; + uint256 otTo = otFrom - otDelta; + uint256 collateralFrom = curve.calCost(otFrom); + uint256 collateralTo = curve.calCostUp(otTo); + // NOTE: it cannot be -ve, a -ve area implies you pay to sell outcomes + // GOAL: minimize collateralTotal => user receives lowest estimated value + uint256 collateralTotal = 0; + if (collateralFrom > collateralTo) { + collateralTotal = collateralFrom - collateralTo; + } + + uint256 taxRate = RedeemMathV2.calRedeemTaxRate(redeem, otFrom + curve.start, otDelta + curve.start); + uint256 collateralFromPool = collateralTotal.fullMulDiv(WTFMath.WTF_ONE - taxRate, WTFMath.WTF_ONE); + collateralToTreasury = collateralFromPool.fullMulDivUp(feeRate, WTFMath.WTF_ONE); + collateralToUser = collateralFromPool - collateralToTreasury; + } + + /** + * swap ? ot -> (exactOut) collateral + * + * @dev guess can be unreachable (especially with large ticks): + * 1. collateral amount is too small, thus 1 tick exceeds the target + * 2. collateral amount is too large, thus entire redeeming ot supply exceeds the target + * @dev redeem formula changes wrt to otDeltaGuess, leading to possible edge cases + */ + function guessOtDelta( + PowerMath.CurveParams memory curve, + RedeemMathV2.RedeemParams memory redeem, + uint256 feeRate, + GuessParam memory guess, + uint256 collateralDeltaTarget, + uint256 otSupply, + uint256 tick + ) + internal + pure + returns ( + uint256, /*otDeltaGuess*/ + uint256 /*collateralDeltaReturned*/ + ) + { + // A LOT easier to guess by ticks => convert discontinuous search space {1000, 2000, 3000,...} to {1, 2, 3,...} + // guess.otGuessMin = tickLower, guess.otGuessMax = tickUpper + + // no solution: nothing to redeem + if (otSupply < tick) { + revert Errors.GuessTargetUnreachable(0, collateralDeltaTarget); + } + + // 0. save current tick pointer for refining bounds + GuessPointer memory ptr; + ptr.tickCurr = 0; + ptr.tickMax = otSupply / tick; + guess.otGuessMin = 0; + guess.otGuessMax = 0; + + // 1. set current tick pointer + if (guess.otDeltaGuessOffchain != 0) { + ptr.tickCurr = WTFMath.clamp(guess.otDeltaGuessOffchain / tick, 1, ptr.tickMax); + } else { + uint256 price = curve.calMarginalPrice(otSupply); + if (price == 0) price = 1; + ptr.tickCurr = WTFMath.clamp(collateralDeltaTarget.fullMulDiv(WTFMath.WTF_ONE, price) / tick, 1, ptr.tickMax); + } + + // 2. refine both bounds via discrete newton & current tick pointer (must use ticks, else it degrades) + for (ptr.iter = 0; ptr.iter < guess.maxIterations; ++ptr.iter) { + uint256 otDeltaGuessCurr = ptr.tickCurr * tick; + (uint256 collateralDelta,) = PowerRedeemV2.calSwap(curve, redeem, feeRate, otSupply, otDeltaGuessCurr); + + // hit target by chance return early + if (WTFMath.isASmallerApproxB(collateralDelta, collateralDeltaTarget, guess.eps)) { + return (otDeltaGuessCurr, collateralDelta); + } + + // otSupply >= otDeltaGuessCurr since clamped earlier + uint256 price = curve.calMarginalPrice(otSupply - otDeltaGuessCurr); // note: not exactly the derivative when redeem + if (price == 0) price = 1; + + if (collateralDelta > collateralDeltaTarget) { + // set one bound (case: overguess) + guess.otGuessMax = ptr.tickCurr; + + // no solution: target collateral is less than 1 tick + if (ptr.tickCurr == 1) { + revert Errors.GuessTargetUnreachable(collateralDelta, collateralDeltaTarget); + } + + if (guess.otGuessMin > 0) break; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDelta - collateralDeltaTarget, price, tick); + ptr.tickCurr = ptr.tickCurr > tickStep ? ptr.tickCurr - tickStep : 1; + } else { + // set one bound (case: underguess) + guess.otGuessMin = ptr.tickCurr; + + // no solution: target collateral is more than supply's tick + if (ptr.tickCurr == ptr.tickMax) { + revert Errors.GuessTargetUnreachable(collateralDelta, collateralDeltaTarget); + } + + if (guess.otGuessMax > 0) break; // refinement complete + + uint256 tickStep = stepFromDiff(collateralDeltaTarget - collateralDelta, price, tick); + ptr.tickCurr = WTFMath.clamp(ptr.tickCurr + tickStep, 1, ptr.tickMax); + } + } + if (ptr.iter >= guess.maxIterations) { + revert Errors.GuessExceedMaxInterpolationIterations(guess.maxIterations); + } + + // 3. binary search with refined bounds + for (ptr.iter = 0; ptr.iter < guess.maxIterations; ++ptr.iter) { + uint256 tickGuess = guess.calMid(); + uint256 otDeltaGuessCurr = tickGuess * tick; + (ptr.collateralDeltaLast,) = PowerRedeemV2.calSwap(curve, redeem, feeRate, otSupply, otDeltaGuessCurr); + + if (WTFMath.isASmallerApproxB(ptr.collateralDeltaLast, collateralDeltaTarget, guess.eps)) { + return (otDeltaGuessCurr, ptr.collateralDeltaLast); + } + + if (ptr.collateralDeltaLast <= collateralDeltaTarget) { + if (tickGuess == guess.otGuessMin) break; + guess.otGuessMin = tickGuess; + } else { + if (tickGuess == guess.otGuessMax) break; + guess.otGuessMax = tickGuess; + } + } + if (ptr.iter >= guess.maxIterations) { + revert Errors.GuessExceedMaxIterations(guess.maxIterations); + } else { + // show no solution (clearer) + revert Errors.GuessTargetUnreachable(ptr.collateralDeltaLast, collateralDeltaTarget); + } + } +} diff --git a/curve/src/interfaces/IRegistry.sol b/curve/src/interfaces/IRegistry.sol new file mode 100644 index 0000000..1a20756 --- /dev/null +++ b/curve/src/interfaces/IRegistry.sol @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +interface IRegistry { + function isFinalised(bytes32 questionId) external view returns (bool finalised); + + function getOutcomeAnswer(bytes32 questionId) external view returns (uint256 answer); + + function getOutcomeEnd(bytes32 questionId) external view returns (uint128 timestampEnd); + + function getNumOutcomes(bytes32 questionId) external view returns (uint256 numOutcomes); + + function getOutcomeNames(bytes32 questionId) external view returns (string[] memory names); + + function getConfig(address market) + external + view + returns ( + address _treasury, + uint80 _feeRate, + uint256 _numOutcomes, + uint128 _timestampEnd, + uint256 _answer, + bool _isFinalised + ); + + function isPaused() external view returns (bool); +} diff --git a/curve/src/interfaces/IWTFCurve.sol b/curve/src/interfaces/IWTFCurve.sol new file mode 100644 index 0000000..b8b96bd --- /dev/null +++ b/curve/src/interfaces/IWTFCurve.sol @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +interface IWTFCurve { + /** + * @notice calculate marginal price of an OT. Marginal price refers to the cost to buy an infinitesimal amount of OT. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * @return price marginal price, scaled to decimals of collateral + */ + function calMarginalPrice(address market, uint256 tokenId) external view returns (uint256 price); + + /** + * @notice calculate cost of OT given OT to mint. Cost refers to the total amount of collateral required. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * @return collateralFromUser amount of collateral required from user. note that part of it goes to treasury as fees + * @return collateralToTreasury fee of trade, given to treasury + * @dev may contain state-modifying calls, note the lack of `view` modifier + */ + function calMintCostByOtDelta(address market, uint256 tokenId, uint256 otDelta, bytes calldata dataSwap) + external + returns (uint256 collateralFromUser, uint256 collateralToTreasury); + + /** + * @notice calculate value of OT given OT to redeem. Value refers to the total amount of collateral the OT is worth. Term is similar, but not the same as cost. + * @return collateralToUser amount of collateral given to user. note that amount is POST fees (fees are already deducted) + * @return collateralToTreasury fee of trade, given to treasury + * @dev may contain state-modifying calls, note the lack of `view` modifier + */ + function calRedeemValueByOtDelta(address market, uint256 tokenId, uint256 otDelta, bytes calldata dataSwap) + external + returns (uint256 collateralToUser, uint256 collateralToTreasury); + + /** + * @notice calculate cost of OTs given OTs to seed. Cost refers to the total amount of collateral required. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * the curve is agnostic to whether fees are charged and if OTs are given back to the seeder or to treasury. + * @notice this function is called only for seed. Non-seed transactions do not use this. + * seeding is different from minting as it is used to initialise the market, thus it is crucial for: + * - setting up an initial "rate" for multi-dimensional bonding curves (i.e LMSR, AMMs) whereby invariants affect each other + * - bypassing user-facing special mechanics (i.e mint premiums) + * - seed at a fixed price without quotations (i.e RFQ or an external oracle) + * - creating a curve where no OTs are minted and only collateral is donated (use dataSwap with otDeltas of 0) + * @return collateralsFromUser amount of collaterals required from user + * @return collateralsToTreasury fee of seed, given to treasury + * @dev the curve can still implement the exact same formulas as mints, and it is not required to offer a preferntial quote + * @dev may contain state-modifying calls, note the lack of `view` modifier + * @dev guessing from collaterals is not provided due to possibility of onchain reverts with multiple swaps + */ + function calSeedCostByOtDeltas( + address market, + uint256[] calldata tokenIds, + uint256[] calldata otDeltas, + bytes calldata dataSwap + ) external returns (uint256[] memory collateralsFromUser, uint256[] memory collateralsToTreasury); + + /** + * @notice approximate amount of OT to mint given collateral to spend. Cost refers to the total amount of collateral required. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * @return otDelta best approximated amount of OT to mint + * @return collateralFromUser expected amount of collateral required from user, PLEASE read DbC below. + * @dev Interface's Design by Contract(DbC) MUST be followed: Given no other factors between approx and actual swap, + * collateralFromUser returned must match the collateralFromUser returned by `calMintCostByOtDelta` called during actual swap. + */ + function calOtDeltaByMintCost(address market, uint256 tokenId, uint256 collateralDelta, bytes calldata dataGuess) + external + view + returns (uint256 otDelta, uint256 collateralFromUser); + + /** + * @notice approximate amount of OT to redeem given collateral to receive. Value refers to the total amount of collateral the OT is worth. Term is similar, but not the same as cost. + * @return otDelta best approximated amount of OT to redem + * @return collateralToUser expected amount of collateral given to user, PLEASE read DbC below. + * @dev Interface's Design by Contract(DbC) MUST be followed: Given no other factors between approx and actual swap, + * collateralToUser returned must match the collateralToUser returned by `calRedeemValueByOtDelta` called during actual swap. + */ + function calOtDeltaByRedeemValue(address market, uint256 tokenId, uint256 collateralDelta, bytes calldata dataGuess) + external + view + returns (uint256 otDelta, uint256 collateralToUser); + + /** + * @notice Exposes the curve's underlying cost function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simCost(uint256 otSupply) external view returns (uint256 cost); + + /** + * @notice Exposes the curve's underlying cost function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simCost(address market, uint256 tokenId, uint256 otSupply) external view returns (uint256 cost); + + /** + * @notice Exposes the curve's underlying marginal price function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simMarginalPrice(uint256 otSupply) external view returns (uint256 price); + + /** + * @notice Exposes the curve's underlying marginal price function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simMarginalPrice(address market, uint256 tokenId, uint256 otSupply) external view returns (uint256 price); + + /** + * @notice Exposes the curve's underlying seed logic, so that it is possible to estimate costs without a market + * @return collateralFromUserTotal total amount of collateral required, given in collateral decimals + * @return collateralToTreasuryTotal total amount of fees to treasury, given in collateral decimals + * @dev Interface's Design by Contract(DbC) MUST be followed: Given to other factors between simSeed and seed, + * collateralFromUserTotal must be sum of collateralsFromUser in calSeedCostByOtDeltas. collateralToTreasuryTotal must be sum of collateralsToTreasury in calSeedCostByOtDeltas. + */ + function simSeed(uint256[] calldata tokenIds, uint256[] calldata otDeltas, uint8 collateralDecimals, uint80 feeRate) + external + view + returns (uint256 collateralFromUserTotal, uint256 collateralToTreasuryTotal); + + /** + * @notice There are a lot of factors involved in the curve, so this is a rather inaccurate function that attempts to "approximately" value an OT. + * Calling this when all other factors are not aligned results in an invalid number. + * Additionally, even when called properly there is no meaning to the number other than for frontend displays. + * @dev DO NOT RELY ON THIS FOR ONCHAIN LOGIC + * @return collateralFromUser collateral required from user when minting from otFrom, assuming all factors aligned + * @return collateralToTreasury collateral given to treasury, assuming all factors aligned + * @dev collateralFromUser + collateralToTreasury = total approximated value of the position-ish + */ + function extrapolateMintForOffchainOnly(address market, uint256 tokenId, uint256 otFrom, uint256 otDelta) + external + view + returns (uint256 collateralFromUser, uint256 collateralToTreasury); + + /** + * @notice There are a lot of factors involved in the curve, so this is a rather inaccurate function that attempts to "approximately" value an OT. + * Calling this when all other factors are not aligned results in an invalid number. + * Additionally, even when called properly there is no meaning to the number other than for frontend displays. + * @dev DO NOT RELY ON THIS FOR ONCHAIN LOGIC + * @return collateralToUser collateral given to user when redeeming from otFrom, assuming all factors aligned + * @return collateralToTreasury collateral given to treasury, assuming all factors aligned + * @dev collateralToUser + collateralToTreasury = total approximated value of the position-ish + */ + function extrapolateRedeemForOffchainOnly(address market, uint256 tokenId, uint256 otFrom, uint256 otDelta) + external + view + returns (uint256 collateralToUser, uint256 collateralToTreasury); +} diff --git a/curve/src/interfaces/IWTFMarket.sol b/curve/src/interfaces/IWTFMarket.sol new file mode 100644 index 0000000..f3b96f2 --- /dev/null +++ b/curve/src/interfaces/IWTFMarket.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +import {MarketDeployParams, MarketState} from "@wtf/lib/Market.sol"; +import {IERC6909TokenSupply, IERC6909Metadata} from "@openzeppelin/contracts/interfaces/IERC6909.sol"; + +interface IWTFMarket is IERC6909Metadata, IERC6909TokenSupply { + function mintCollateralToExactOt( + address receiver, + uint256 tokenId, + uint256 otDeltaOut, + bytes calldata dataSwap, + bytes calldata dataCallback + ) external returns (uint256 collateralIn); + + function redeemExactOtToCollateral(address receiver, uint256 tokenId, uint256 otDeltaIn, bytes calldata dataSwap) + external + returns (uint256 collateralOut); + + function seed(uint256 tokenId, uint256 otSeed, bytes calldata dataSwap) external; + + function claim(address receiver, uint256[] memory tokenIds, uint256[] memory otToBurn) + external + returns (uint256 payout); + + function simPayout(uint256 answerSim, uint256 otUserWinning) external view returns (uint256 payout); + + function totalMarketCap() external view returns (uint256); + + function marketType() external view returns (string memory); + + function collateralDecimals() external view returns (uint8 decimal); + + function readState() external view returns (MarketState memory); + + function readMarketDeployParams() external view returns (MarketDeployParams memory); + + function registry() external view returns (address); + + function questionId() external view returns (bytes32); + + function timestampStart() external view returns (uint128); +} diff --git a/curve/src/libraries/Decoder.sol b/curve/src/libraries/Decoder.sol new file mode 100644 index 0000000..bc7be55 --- /dev/null +++ b/curve/src/libraries/Decoder.sol @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import {GuessParam} from "@wtf/src/curves/CurveBase.sol"; +import "@wtf/lib/Errors.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; + +library Decoder { + uint256 private constant GUESS_PARAM_LENGTH = 96; // 3 * 32 bytes + uint256 private constant DEFAULT_MAX_ITERATIONS = 50; + uint256 private constant DEFAULT_EPSILON = 1e15; // 0.1% + + function encodeGuessParam(GuessParam memory guess) internal pure returns (bytes memory) { + bytes memory data = new bytes(GUESS_PARAM_LENGTH); + + assembly { + let dataPtr := add(data, 32) // Skip length prefix + mstore(dataPtr, mload(add(guess, 64))) // guessOffchain + mstore(add(dataPtr, 32), mload(add(guess, 96))) // maxIterations (4th field) + mstore(add(dataPtr, 64), mload(add(guess, 128))) // eps (5th field) + } + + return data; + } + + // @dev returns a guess param with default params if no calldata exists, fails-fast if guess param doesn't make sense + function decodeGuessParam(bytes calldata data) internal pure returns (GuessParam memory) { + if (data.length == 0) { + return GuessParam({ + otGuessMin: 0, + otGuessMax: 0, + otDeltaGuessOffchain: 0, + maxIterations: DEFAULT_MAX_ITERATIONS, + eps: DEFAULT_EPSILON + }); + } + if (data.length != GUESS_PARAM_LENGTH) revert Errors.GuessInvalidDataLength(data.length, GUESS_PARAM_LENGTH); + + GuessParam memory guess; + assembly { + let dataOffset := data.offset + mstore(guess, 0) // guessMin = 0 + mstore(add(guess, 32), 0) // guessMax = 0 + mstore(add(guess, 64), calldataload(dataOffset)) // guessOffchain + mstore(add(guess, 96), calldataload(add(dataOffset, 32))) // maxIterations + mstore(add(guess, 128), calldataload(add(dataOffset, 64))) // eps + } + + if (guess.eps > WTFMath.WTF_ONE) revert Errors.GuessEpsAboveMax(); + if (guess.maxIterations == 0) revert Errors.GuessMaxIterationsZero(); // max iteration of 0 should swap via OT + + return guess; + } +} diff --git a/curve/src/libraries/Errors.sol b/curve/src/libraries/Errors.sol new file mode 100644 index 0000000..1729a59 --- /dev/null +++ b/curve/src/libraries/Errors.sol @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +library Errors { + error FactoryInvalidCurve(); + error FactoryInvalidCollateral(); + error FactoryInvalidSeedAmount(); + error FactoryUnsuccessfulMarketDeployment(); + error FactoryFeeRateExceedMaximumLimit(); + error FactoryCurveNotAllowed(); + error FactorySeedCostMismatch(); + error FactorySeedCallFailed(); + error FactoryNativeTokenNotAllowed(); + + error CurveInvalidCost(uint256 quantity); + error CurveOtDeltaNotOnTick(uint256 otDelta, uint256 tick); + error CurveInvalidStartEnd(); + error CurveInvalidParams(); + + error RegistryInsufficientOutcomesGiven(); + error RegistryExceedMaxNames(); + error RegistryAlreadyRegistered(); + error RegistryInvalidAddressPtr(); + error RegistryEndTimestampHasPassed(); + error RegistryEmptyTitle(); + error RegistryExceedMaxTitleLength(); + error RegistryExceedMaxDescriptionLength(); + error RegistryEmptyName(); + error RegistryExceedMaxNameLength(); + error RegistryDuplicateOutcome(); + error RegistryNotRegistered(); + error RegistryAlreadyFinalised(); + error RegistryEndTimestampBeforeExisting(); + error RegistryInvalidAnswer(); + error RegistrySameAnswer(); + error RegistryNotResolved(); + error RegistryAnswerDoesNotMatchCurrent(); + error Registry6909MustBeRegisteredMarket(); + error RegistryInvalidTokenIdAsCollateral(); + error RegistryTokenIdNotCreatedForMarket(); + error RegistryInvalidTreasuryAddress(); + error RegistryExceedMaxAncillaryDataUpdateLength(); + + error GuessInvalidDataLength(uint256 len, uint256 required); + error GuessMinGreaterThanMax(uint256 guessMin, uint256 guessMax); + error GuessMaxIterationsZero(); + error GuessEpsAboveMax(); + error GuessExceedMaxIterations(uint256 maxIterations); + error GuessExceedMaxInterpolationIterations(uint256 maxIterations); + error GuessTargetUnreachable(uint256 current, uint256 target); + + error MarketUnprocessableAnswer(uint256 answer); + error MarketPayoutPerOutcomeAlreadyCalculated(uint256 payoutPerOutcome); + error MarketNotFinalised(); + error MarketNotResolved(); + error MarketSwapAmountCannotBeZero(); + error MarketTooManyTotalSupplies(uint256 required); + error MarketTooManyOutcomes(); + error MarketNotStarted(); + error MarketEnded(); + error MarketResolved(); + error MarketUnauthorizedAccess(address account, address required); + error MarketZeroCostBasis(); + error MarketInvalidTokenId(uint256 tokenId); + error MarketSwapPriceInvalidated(uint256 collateralDelta, uint256 otDelta); + error MarketArrayLengthsMismatch(); + error MarketNoClaim(); + error MarketPaused(); + error MarketNotWhole(); + error MarketReceiverIsMarket(); + error MarketZeroAddress(); + + error MarketNoTokenIdsToSeed(); + + error RouterUnauthorized(); + error RouterDbCViolated(); + error RouterSlippage(); + error RouterUnsupportedSelector(); + error RouterArrayLengthsMismatch(); + error RouterNotClaimableYet(); + error RouterIntegratorFeeTooHigh(); + error RouterInvalidIntegrator(); + error RouterInvalidMarket(); + error RouterInvalidSwapAmount(); + + error RegistryUnauthorized(); + error RegistryFeeRateTooHigh(); + error RegistryQuestionNotFound(); + error RegistryQuestionAlreadyExists(); + error RegistryQuestionAlreadyFinalised(); + error RegistryQuestionNotResolved(); + error RegistryInvalidNumOutcomes(); + error RegistryInvalidTimestamp(); + error RegistrySeedTooLow(); + error RegistryCurveNotAllowed(); + error RegistryMarketDeploymentFailed(); + error RegistryCollateralNotWhitelisted(); + error RegistryPaused(); + error RegistryInvalidOracleAddress(); + error RegistryOnlyCreator(); + error RegistryOnlyOracle(); + error RegistryOnlyCreatorOrOracleOrAdmin(); + error RegistrySeedBelowMinimum(); + error RegistryManualFinaliseTooEarly(); + error RegistryAlreadyFlagged(); + error RegistryNotFlagged(); + error RegistryOutcomeImagesMismatch(); + error RegistryMarketNotFound(); + error RegistryMinSeedCannotBeZero(); + error RegistryInvalidCurve(); + error RegistryOutcomeLengthMismatch(); + error RegistryQuestionIsFlagged(); + + error AdaptorInvalidQuestion(); + error AdaptorSeedCostExceedsBudget(); + + error MarketInsufficientSeedCollateral(); + + error Safe6909TransferFailed(); + + error RouterStaticCallFailed(); + + error DRegistryQuestionNotResolved(); + error DRegistryQuestionAlreadyFinalised(); + error DRegistryLimitIsZero(); + error DRegistryInvalidQuestion(); + + error AdaptorMarketDoesNotMatchQuestionId(); + error AdaptorOtAmountsDoesNotMatch(); + + error AdaptorQuestionAlreadyLocked(); + error AdaptorMarketNotLocked(); + error AdaptorAccessControlUnauthorizedAccount(); + error AdaptorPrelockTimestampAlreadyPassed(); + error AdaptorCannotBeLocked(); + error AdaptorProposerOverridden(); + + // TODO: cleanup +} diff --git a/curve/src/libraries/LogExpMath.sol b/curve/src/libraries/LogExpMath.sol new file mode 100644 index 0000000..dcaacdf --- /dev/null +++ b/curve/src/libraries/LogExpMath.sol @@ -0,0 +1,510 @@ +// SPDX-License-Identifier: MIT +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +// Software. + +// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +pragma solidity ^0.8.0; + +/* solhint-disable */ + +/** + * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). + * + * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural + * exponentiation and logarithm (where the base is Euler's number). + * + * @author Fernando Martinelli - @fernandomartinelli + * @author Sergio Yuhjtman - @sergioyuhjtman + * @author Daniel Fernandez - @dmf7z + */ +library LogExpMath { + // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying + // two numbers, and multiply by ONE when dividing them. + + // All arguments and return values are 18 decimal fixed point numbers. + uint256 constant UONE_18 = 1e18; + int256 constant ONE_18 = 1e18; + + // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the + // case of ln36, 36 decimals. + int256 constant ONE_20 = 1e20; + int256 constant ONE_36 = 1e36; + + // The domain of natural exponentiation is bound by the word size and number of decimals used. + // + // Because internally the result will be stored using 20 decimals, the largest possible result is + // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. + // The smallest possible result is 10^(-18), which makes largest negative argument + // ln(10^(-18)) = -41.446531673892822312. + // We use 130.0 and -41.0 to have some safety margin. + int256 constant MAX_NATURAL_EXPONENT = 130e18; + int256 constant MIN_NATURAL_EXPONENT = -41e18; + + // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point + // 256 bit integer. + int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; + int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; + + uint256 constant MILD_EXPONENT_BOUND = 2 ** 254 / uint256(ONE_20); + + // 18 decimal constants + int256 constant x0 = 128000000000000000000; // 2ˆ7 + int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) + int256 constant x1 = 64000000000000000000; // 2ˆ6 + int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) + + // 20 decimal constants + int256 constant x2 = 3200000000000000000000; // 2ˆ5 + int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) + int256 constant x3 = 1600000000000000000000; // 2ˆ4 + int256 constant a3 = 888611052050787263676000000; // eˆ(x3) + int256 constant x4 = 800000000000000000000; // 2ˆ3 + int256 constant a4 = 298095798704172827474000; // eˆ(x4) + int256 constant x5 = 400000000000000000000; // 2ˆ2 + int256 constant a5 = 5459815003314423907810; // eˆ(x5) + int256 constant x6 = 200000000000000000000; // 2ˆ1 + int256 constant a6 = 738905609893065022723; // eˆ(x6) + int256 constant x7 = 100000000000000000000; // 2ˆ0 + int256 constant a7 = 271828182845904523536; // eˆ(x7) + int256 constant x8 = 50000000000000000000; // 2ˆ-1 + int256 constant a8 = 164872127070012814685; // eˆ(x8) + int256 constant x9 = 25000000000000000000; // 2ˆ-2 + int256 constant a9 = 128402541668774148407; // eˆ(x9) + int256 constant x10 = 12500000000000000000; // 2ˆ-3 + int256 constant a10 = 113314845306682631683; // eˆ(x10) + int256 constant x11 = 6250000000000000000; // 2ˆ-4 + int256 constant a11 = 106449445891785942956; // eˆ(x11) + + /** + * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. + * + * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. + */ + function pow(uint256 x, uint256 y) internal pure returns (uint256) { + if (y == 0) { + // We solve the 0^0 indetermination by making it equal one. + return uint256(ONE_18); + } + + if (x == 0) { + return 0; + } + + // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to + // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means + // x^y = exp(y * ln(x)). + + // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. + require(x >> 255 == 0, "x out of bounds"); + int256 x_int256 = int256(x); + + // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In + // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. + + // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. + require(y < MILD_EXPONENT_BOUND, "y out of bounds"); + int256 y_int256 = int256(y); + + int256 logx_times_y; + if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { + int256 ln_36_x = _ln_36(x_int256); + + // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just + // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal + // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the + // (downscaled) last 18 decimals. + logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); + } else { + logx_times_y = _ln(x_int256) * y_int256; + } + logx_times_y /= ONE_18; + + // Finally, we compute exp(y * ln(x)) to arrive at x^y + require(MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, "product out of bounds"); + + return uint256(exp(logx_times_y)); + } + + /** + * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. + * + * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. + */ + function exp(int256 x) internal pure returns (int256) { + require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "invalid exponent"); + + if (x < 0) { + // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it + // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). + // Fixed point division requires multiplying by ONE_18. + return ((ONE_18 * ONE_18) / exp(-x)); + } + + // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, + // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 + // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the + // decomposition. + // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this + // decomposition, which will be lower than the smallest x_n. + // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. + // We mutate x by subtracting x_n, making it the remainder of the decomposition. + + // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause + // intermediate overflows. Instead we store them as plain integers, with 0 decimals. + // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the + // decomposition. + + // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct + // it and compute the accumulated product. + + int256 firstAN; + if (x >= x0) { + x -= x0; + firstAN = a0; + } else if (x >= x1) { + x -= x1; + firstAN = a1; + } else { + firstAN = 1; // One with no decimal places + } + + // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the + // smaller terms. + x *= 100; + + // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point + // one. Recall that fixed point multiplication requires dividing by ONE_20. + int256 product = ONE_20; + + if (x >= x2) { + x -= x2; + product = (product * a2) / ONE_20; + } + if (x >= x3) { + x -= x3; + product = (product * a3) / ONE_20; + } + if (x >= x4) { + x -= x4; + product = (product * a4) / ONE_20; + } + if (x >= x5) { + x -= x5; + product = (product * a5) / ONE_20; + } + if (x >= x6) { + x -= x6; + product = (product * a6) / ONE_20; + } + if (x >= x7) { + x -= x7; + product = (product * a7) / ONE_20; + } + if (x >= x8) { + x -= x8; + product = (product * a8) / ONE_20; + } + if (x >= x9) { + x -= x9; + product = (product * a9) / ONE_20; + } + + // x10 and x11 are unnecessary here since we have high enough precision already. + + // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series + // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). + + int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. + int256 term; // Each term in the sum, where the nth term is (x^n / n!). + + // The first term is simply x. + term = x; + seriesSum += term; + + // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, + // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. + + term = ((term * x) / ONE_20) / 2; + seriesSum += term; + + term = ((term * x) / ONE_20) / 3; + seriesSum += term; + + term = ((term * x) / ONE_20) / 4; + seriesSum += term; + + term = ((term * x) / ONE_20) / 5; + seriesSum += term; + + term = ((term * x) / ONE_20) / 6; + seriesSum += term; + + term = ((term * x) / ONE_20) / 7; + seriesSum += term; + + term = ((term * x) / ONE_20) / 8; + seriesSum += term; + + term = ((term * x) / ONE_20) / 9; + seriesSum += term; + + term = ((term * x) / ONE_20) / 10; + seriesSum += term; + + term = ((term * x) / ONE_20) / 11; + seriesSum += term; + + term = ((term * x) / ONE_20) / 12; + seriesSum += term; + + // 12 Taylor terms are sufficient for 18 decimal precision. + + // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor + // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply + // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), + // and then drop two digits to return an 18 decimal value. + + return (((product * seriesSum) / ONE_20) * firstAN) / 100; + } + + /** + * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. + */ + function log(int256 arg, int256 base) internal pure returns (int256) { + // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). + + // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by + // upscaling. + + int256 logBase; + if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { + logBase = _ln_36(base); + } else { + logBase = _ln(base) * ONE_18; + } + + int256 logArg; + if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { + logArg = _ln_36(arg); + } else { + logArg = _ln(arg) * ONE_18; + } + + // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places + return (logArg * ONE_18) / logBase; + } + + /** + * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. + */ + function ln(int256 a) internal pure returns (int256) { + // The real natural logarithm is not defined for negative numbers or zero. + require(a > 0, "out of bounds"); + if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { + return _ln_36(a) / ONE_18; + } else { + return _ln(a); + } + } + + /** + * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. + */ + function _ln(int256 a) private pure returns (int256) { + if (a < ONE_18) { + // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less + // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. + // Fixed point division requires multiplying by ONE_18. + return (-_ln((ONE_18 * ONE_18) / a)); + } + + // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which + // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, + // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot + // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. + // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this + // decomposition, which will be lower than the smallest a_n. + // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. + // We mutate a by subtracting a_n, making it the remainder of the decomposition. + + // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point + // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by + // ONE_18 to convert them to fixed point. + // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide + // by it and compute the accumulated sum. + + int256 sum = 0; + if (a >= a0 * ONE_18) { + a /= a0; // Integer, not fixed point division + sum += x0; + } + + if (a >= a1 * ONE_18) { + a /= a1; // Integer, not fixed point division + sum += x1; + } + + // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. + sum *= 100; + a *= 100; + + // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. + + if (a >= a2) { + a = (a * ONE_20) / a2; + sum += x2; + } + + if (a >= a3) { + a = (a * ONE_20) / a3; + sum += x3; + } + + if (a >= a4) { + a = (a * ONE_20) / a4; + sum += x4; + } + + if (a >= a5) { + a = (a * ONE_20) / a5; + sum += x5; + } + + if (a >= a6) { + a = (a * ONE_20) / a6; + sum += x6; + } + + if (a >= a7) { + a = (a * ONE_20) / a7; + sum += x7; + } + + if (a >= a8) { + a = (a * ONE_20) / a8; + sum += x8; + } + + if (a >= a9) { + a = (a * ONE_20) / a9; + sum += x9; + } + + if (a >= a10) { + a = (a * ONE_20) / a10; + sum += x10; + } + + if (a >= a11) { + a = (a * ONE_20) / a11; + sum += x11; + } + + // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series + // that converges rapidly for values of `a` close to one - the same one used in ln_36. + // Let z = (a - 1) / (a + 1). + // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) + + // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires + // division by ONE_20. + int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); + int256 z_squared = (z * z) / ONE_20; + + // num is the numerator of the series: the z^(2 * n + 1) term + int256 num = z; + + // seriesSum holds the accumulated sum of each term in the series, starting with the initial z + int256 seriesSum = num; + + // In each step, the numerator is multiplied by z^2 + num = (num * z_squared) / ONE_20; + seriesSum += num / 3; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 5; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 7; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 9; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 11; + + // 6 Taylor terms are sufficient for 36 decimal precision. + + // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) + seriesSum *= 2; + + // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both + // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal + // value. + + return (sum + seriesSum) / 100; + } + + /** + * @dev Internal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, + * for x close to one. + * + * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. + */ + function _ln_36(int256 x) private pure returns (int256) { + // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits + // worthwhile. + + // First, we transform x to a 36 digit fixed point value. + x *= ONE_18; + + // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). + // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) + + // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires + // division by ONE_36. + int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); + int256 z_squared = (z * z) / ONE_36; + + // num is the numerator of the series: the z^(2 * n + 1) term + int256 num = z; + + // seriesSum holds the accumulated sum of each term in the series, starting with the initial z + int256 seriesSum = num; + + // In each step, the numerator is multiplied by z^2 + num = (num * z_squared) / ONE_36; + seriesSum += num / 3; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 5; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 7; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 9; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 11; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 13; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 15; + + // 8 Taylor terms are sufficient for 36 decimal precision. + + // All that remains is multiplying by 2 (non fixed point). + return seriesSum * 2; + } +} diff --git a/curve/src/libraries/Market.sol b/curve/src/libraries/Market.sol new file mode 100644 index 0000000..f59c80f --- /dev/null +++ b/curve/src/libraries/Market.sol @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import "@wtf/lib/Errors.sol"; +import "@solady/utils/FixedPointMathLib.sol"; +import "@wtf/lib/WTFMath.sol"; +import "@wtf/lib/RedeemMath.sol"; +import {IWTFCurve} from "@wtf/src/interfaces/IWTFCurve.sol"; + +struct MarketDeployParams { + address collateral; + uint256 parentTokenId; + bytes32 questionId; + address curve; + uint128 timestampStart; +} + +struct SwapParams { + bool isMint; // collateral -> outcome + uint256 amount; + bool isExactIn; + uint256 minOutOrMaxIn; // exactIn = min output, exactOut = max input +} + +struct MarketState { + // immutable + address market; + IWTFCurve curve; + uint128 timestampStart; + // mutable, market related + uint256 totalMarketCap; + // mutable, question related + address treasury; + uint256 numOutcomes; + uint128 timestampEnd; + uint256 answer; + bool isFinalised; +} + +library Market { + using FixedPointMathLib for uint256; + + function isValidTokenId(uint256 tokenId) internal pure returns (bool) { + // 0 is null token id + if (tokenId == 0) return false; + + // power of 2 + if ((tokenId) & (tokenId - 1) != 0) { + return false; + } + + return true; + } + + /** + * @notice TokenId works in powers of 2 from 0th index. + * While the brain works with counts, most things are however 0-th indexed + * @dev You are STRONGLY recommended to use this to avoid off-by-index errors + */ + function toTokenId(uint256 indexOutcomeFromZero) internal pure returns (uint256) { + // 1st outcome -> 2**(1-1) = tokenId 1 + // 2nd outcome -> 2**(2-1) = tokenId 2 + // 3rd outcome -> 2**(3-1) = tokenId 4 + + return 2 ** indexOutcomeFromZero; + } + + /** + * @notice Reverse of toTokenId + * @dev Almost everything should be done in terms of token id, especially core logic to avoid off-by-index errors + * Try not to convert ids back and forth + */ + function fromTokenId(uint256 tokenId) internal pure returns (uint256) { + // tokenId 1 -> log2(1) = index 0 + // tokenId 2 -> log2(2) = index 1 + // tokenId 4 -> log2(4) = index 2 + if (!isValidTokenId(tokenId)) revert Errors.MarketInvalidTokenId(tokenId); + + uint256 index = 0; + uint256 temp = tokenId >> 1; + while (temp > 0) { + temp >>= 1; + index++; + } + return index; + } + + /** + * ** + * @return winner boolean value indicating whether tokenId is a winning OT + * @dev Check via bitwise & operator. Refer to truth table: + * ┌───┬───┬─────┬─────┬─────┐ + * │ A │ B │ AND │ OR │ XOR │ + * ├───┼───┼─────┼─────┼─────┤ + * │ 0 │ 0 │ 0 │ 0 │ 0 │ + * │ 0 │ 1 │ 0 │ 1 │ 1 │ + * │ 1 │ 0 │ 0 │ 1 │ 1 │ + * │ 1 │ 1 │ 1 │ 1 │ 0 │ + * └───┴───┴─────┴─────┴─────┘ + */ + function isWinner(uint256 answer, uint256 tokenId) internal pure returns (bool) { + // answer: 0b101 + // tokenId 1: 0b001 -> 0b101 & 0b001 is a winner + // tokenId 2: 0b010 -> 0b101 & 0b010 is NOT a winner + // tokenId 4: 0b100 -> 0b101 & 0b100 is a winner + + return (answer & tokenId) != 0; + } + + /** + * @dev invariant must be followed: mint more => pay more & mint more => price higher + */ + function mintCollateralToOt(MarketState memory self, uint256 tokenId, uint256 otDeltaOut, bytes memory data) + internal + returns (uint256 collateralDeltaIn, uint256 collateralToTreasury) + { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (otDeltaOut == 0) revert Errors.MarketSwapAmountCannotBeZero(); + if (!isValidTokenId(tokenId) || tokenId > toTokenId(self.numOutcomes - 1)) { + revert Errors.MarketInvalidTokenId(tokenId); + } + + /// ------------------------------------------------------------ + /// MATH + /// ------------------------------------------------------------ + (collateralDeltaIn, collateralToTreasury) = + self.curve.calMintCostByOtDelta(self.market, tokenId, otDeltaOut, data); + + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (collateralDeltaIn == 0) revert Errors.MarketZeroCostBasis(); + if (collateralDeltaIn < collateralToTreasury) revert Errors.MarketNotWhole(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.totalMarketCap += collateralDeltaIn - collateralToTreasury; + } + + /** + * @dev invariant must be followed: redeem more => price lower + */ + function redeemOtToCollateral(MarketState memory self, uint256 tokenId, uint256 otDeltaIn, bytes memory data) + internal + returns (uint256 collateralToUser, uint256 collateralToTreasury) + { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (otDeltaIn == 0) revert Errors.MarketSwapAmountCannotBeZero(); + if (!isValidTokenId(tokenId) || tokenId > toTokenId(self.numOutcomes - 1)) { + revert Errors.MarketInvalidTokenId(tokenId); + } + + /// ------------------------------------------------------------ + /// MATH + /// ------------------------------------------------------------ + (collateralToUser, collateralToTreasury) = + self.curve.calRedeemValueByOtDelta(self.market, tokenId, otDeltaIn, data); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.totalMarketCap -= collateralToUser + collateralToTreasury; + } + + function claim( + MarketState memory self, + uint256[] memory tokenIds, + uint256[] memory otToBurn, + uint256 otSupplyWinning + ) internal pure returns (uint256 payout, uint256 excess, uint256 otUserWinning) { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (tokenIds.length != otToBurn.length) revert Errors.MarketArrayLengthsMismatch(); + if (tokenIds.length == 0) revert Errors.MarketNoClaim(); + + // very awkward edge case: somehow no one holds the winners -> send to treasury and think about how to redistribute + if (otSupplyWinning == 0) { + excess = self.totalMarketCap; + self.totalMarketCap = 0; + // payout = 0, otUserWinning = 0 + return (payout, excess, otUserWinning); + } + + /// ------------------------------------------------------------ + /// MATH + /// ------------------------------------------------------------ + uint256 len = tokenIds.length; + for (uint256 i = 0; i < len; ++i) { + uint256 tokenId = tokenIds[i]; + uint256 otBurned = otToBurn[i]; + if (Market.isWinner(self.answer, tokenId)) { + otUserWinning += otBurned; + } + } + + if (otSupplyWinning == otUserWinning) { + payout = self.totalMarketCap; + } else { + payout = self.totalMarketCap.fullMulDiv(otUserWinning, otSupplyWinning); + } + // excess = 0 here + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.totalMarketCap -= payout; + } +} diff --git a/curve/src/libraries/RedeemMath.sol b/curve/src/libraries/RedeemMath.sol new file mode 100644 index 0000000..653f28d --- /dev/null +++ b/curve/src/libraries/RedeemMath.sol @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import "@solady/utils/FixedPointMathLib.sol"; +import "@wtf/lib/WTFMath.sol"; +import "@wtf/lib/LogExpMath.sol"; + +library RedeemMath { + struct RedeemParams { + // time factor params + uint256 timeFromStartToEnd; + uint256 timeFromStartToRedeem; + uint256 timeKink; + uint256 timeExponent; + // growth factor params + uint256 growthC1; + uint256 growthC2; + } + + using FixedPointMathLib for uint256; + using LogExpMath for uint256; + using LogExpMath for int256; + using RedeemMath for RedeemParams; + using WTFMath for *; + + uint256 public constant MINIMUM_TAX_RATE = WTFMath.WTF_ONE / 1_000; // 10 bip or 0.1% + uint256 public constant MAXIMUM_TAX_RATE = WTFMath.WTF_ONE * 9 / 10; // 90% + uint256 public constant MINIMUM_OT_PROPORTION = WTFMath.WTF_ONE / 100_000_000; // 1 bip of 1 bip + + uint256 private constant ONE_MILLION = 1e6 * WTFMath.WTF_ONE; + uint256 private constant TEN_MILLION = 1e7 * WTFMath.WTF_ONE; + + uint256 private constant ONE_POINT_TWO_FIVE = WTFMath.WTF_ONE * 125 / 100; + uint256 private constant ONE_POINT_FIVE = WTFMath.WTF_ONE * 15 / 10; + + function calGrowthFactor(RedeemParams memory self, uint256 otSupply, uint256 otDelta) + internal + pure + returns (uint256) + { + // X = otDelta/otSupply + // growthfactor = c1*e^(c2*X) + uint256 otProportion = otDelta.fullMulDivUp(WTFMath.WTF_ONE, otSupply); + if (otProportion < MINIMUM_OT_PROPORTION) { + otProportion = MINIMUM_OT_PROPORTION; + } + int256 exponent = self.growthC2.fullMulDivUp(otProportion, WTFMath.WTF_ONE).toInt256(); + uint256 result = self.growthC1.fullMulDivUp(exponent.exp().toUint256(), WTFMath.WTF_ONE); + + return result; + } + + function calSupplyFactor(uint256 otSupply) internal pure returns (uint256) { + // supply factor is a piecewise function + uint256 supplyFactor; + if (otSupply <= ONE_MILLION) { + supplyFactor = WTFMath.WTF_ONE; + } else if (otSupply <= TEN_MILLION) { + supplyFactor = ONE_POINT_TWO_FIVE; + } else { + supplyFactor = ONE_POINT_FIVE; + } + + return supplyFactor; + } + + function calTimeFactor(RedeemParams memory self) internal pure returns (uint256) { + // timefactor = (1+max(0,t-kink))^growth, t=%time passed + uint256 timePassed = self.timeFromStartToRedeem.fullMulDivUp(WTFMath.WTF_ONE, self.timeFromStartToEnd); + uint256 baseScale = WTFMath.WTF_ONE; + if (timePassed > self.timeKink) { + baseScale += timePassed - self.timeKink; + } + uint256 result = baseScale.pow(self.timeExponent); + return result; + } + + function calRedeemTaxRate(RedeemParams memory self, uint256 otSupply, uint256 otDelta) + internal + pure + returns (uint256) + { + //r = min(1,growthfactor*supplyfactor*timefactor) + uint256 growthFactor = self.calGrowthFactor(otSupply, otDelta); + uint256 supplyFactor = calSupplyFactor(otSupply); + uint256 timeFactor = self.calTimeFactor(); + uint256 rate = growthFactor.fullMulDivUp(supplyFactor, WTFMath.WTF_ONE).fullMulDivUp(timeFactor, WTFMath.WTF_ONE); + + return WTFMath.clamp(rate, MINIMUM_TAX_RATE, MAXIMUM_TAX_RATE); + } + + function newRedeemParams( + uint128 timestampStart, + uint128 timestampEnd, + uint128 timestampCurrent, + uint256 timeKink, + uint256 timeExponent, + uint256 growthC1, + uint256 growthC2 + ) internal pure returns (RedeemParams memory) { + uint256 timeFromStartToEnd; + uint256 timeFromStartToRedeem; + if (timestampEnd <= timestampStart) { + timeFromStartToEnd = 1; + timeFromStartToRedeem = 1; + } else { + timeFromStartToEnd = timestampEnd - timestampStart; + if (timestampStart < timestampCurrent) { + timeFromStartToRedeem = timestampCurrent - timestampStart; + if (timeFromStartToRedeem > timeFromStartToEnd) { + timeFromStartToRedeem = timeFromStartToEnd; // clamp to 100% to avoid reverts + } + } + } + + return RedeemParams({ + timeFromStartToEnd: timeFromStartToEnd, + timeFromStartToRedeem: timeFromStartToRedeem, + timeKink: timeKink, + timeExponent: timeExponent, + growthC1: growthC1, + growthC2: growthC2 + }); + } +} diff --git a/curve/src/libraries/RedeemMathV2.sol b/curve/src/libraries/RedeemMathV2.sol new file mode 100644 index 0000000..b0d66c0 --- /dev/null +++ b/curve/src/libraries/RedeemMathV2.sol @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import {FixedPointMathLib} from "@solady/utils/FixedPointMathLib.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {LogExpMath} from "@wtf/lib/LogExpMath.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; + +/** + * @notice Second version of RedeemMath + * - Easier to fine-tune tax dynamics both pre-kink and post-kink + * - Preserve the original fundamentals of redeems -> redeem tax still revolves around the kink + * - Value of redeem tax is still primarily dependent on: + * 1. time + * 2. trade size + */ +library RedeemMathV2 { + struct RedeemParams { + uint256 timeFromStartToEnd; + uint256 timeFromStartToRedeem; + + uint256 timeKinkStart; + uint256 timeKinkEnd; + + uint256 rateBaseMin; // minimum rate BEFORE LS + uint256 rateBaseMax; // maximum rate BEFORE LS + + uint256 remapExp; + + // liquidity-sensitivity - higher root increases effective slippage during redeems + uint256 lsRoot; + } + + using FixedPointMathLib for uint256; + using LogExpMath for uint256; + using LogExpMath for int256; + using RedeemMathV2 for RedeemParams; + using WTFMath for *; + + uint256 public constant MINIMUM_TAX_RATE = WTFMath.WTF_ONE / 1_000; // 10 bip or 0.1% + uint256 public constant MAXIMUM_TAX_RATE = WTFMath.WTF_ONE * 9 / 10; // 90% + uint256 public constant MINIMUM_OT_PROPORTION = WTFMath.WTF_ONE / 100_000_000; // 1 bip of 1 bip + + /** + * @notice base rate is dependent on time and starts to exponentially increase after kink's start + * @notice when time passed (t) is between kink start and kink end, base rate exponentially remaps between min and max rate. + * Else, base rate pre-kink start maps to min rate and post-kink end maps to max rate + */ + function calBaseRate(RedeemParams memory self) internal pure returns (uint256) { + // baseRate = {pre-start: rateMin, during: exp_remap(rateMin,rateMax,timePassed), post-end: rateMax} + uint256 timePassed = self.timeFromStartToRedeem.fullMulDivUp(WTFMath.WTF_ONE, self.timeFromStartToEnd); + if (timePassed <= self.timeKinkStart) { + return self.rateBaseMin; + } else if (timePassed >= self.timeKinkEnd) { + return self.rateBaseMax; + } + + uint256 kinkProgress = + (timePassed - self.timeKinkStart).fullMulDivUp(WTFMath.WTF_ONE, self.timeKinkEnd - self.timeKinkStart); + + // remapExp should be variable - it is derived from rateBaseMax and rateBaseMin for exponential remap + int256 exponent = self.remapExp.fullMulDivUp(kinkProgress, WTFMath.WTF_ONE).toInt256(); + uint256 result = self.rateBaseMin.fullMulDivUp(exponent.exp().toUint256(), WTFMath.WTF_ONE); + + return result; + } + + function calLSMultiplier(RedeemParams memory self, uint256 otSupply, uint256 otDelta) + internal + pure + returns (uint256) + { + // X = otDelta/otSupply + // LS = e^(lsRoot*X) + uint256 otProportion = otDelta.fullMulDivUp(WTFMath.WTF_ONE, otSupply); + if (otProportion < MINIMUM_OT_PROPORTION) otProportion = MINIMUM_OT_PROPORTION; + if (otProportion > WTFMath.WTF_ONE) otProportion = WTFMath.WTF_ONE; + int256 exponent = self.lsRoot.fullMulDivUp(otProportion, WTFMath.WTF_ONE).toInt256(); + + return exponent.exp().toUint256(); + } + + function calRedeemTaxRate(RedeemParams memory self, uint256 otSupply, uint256 otDelta) + internal + pure + returns (uint256) + { + // r = clamp(baseRate * LS, min, max) + uint256 rateBase = self.calBaseRate(); + uint256 multiplier = self.calLSMultiplier(otSupply, otDelta); + uint256 rate = rateBase.fullMulDivUp(multiplier, WTFMath.WTF_ONE); + + return WTFMath.clamp(rate, MINIMUM_TAX_RATE, MAXIMUM_TAX_RATE); + } + + function newRedeemParams( + uint128 timestampStart, + uint128 timestampEnd, + uint128 timestampCurrent, + uint256 timeKinkStart, + uint256 timeKinkEnd, + uint256 rateBaseMin, + uint256 rateBaseMax, + uint256 lsRoot + ) internal pure returns (RedeemParams memory) { + if (timeKinkEnd <= timeKinkStart) revert Errors.CurveInvalidStartEnd(); + if (rateBaseMin == 0) revert Errors.CurveInvalidParams(); + if (rateBaseMax <= rateBaseMin) revert Errors.CurveInvalidParams(); + + int256 lnMax = int256(rateBaseMax).ln(); + int256 lnMin = int256(rateBaseMin).ln(); + uint256 remapExp = (lnMax - lnMin).toUint256(); + + uint256 timeFromStartToEnd; + uint256 timeFromStartToRedeem; + if (timestampEnd <= timestampStart) { + timeFromStartToEnd = 1; + timeFromStartToRedeem = 1; + } else { + timeFromStartToEnd = timestampEnd - timestampStart; + if (timestampStart < timestampCurrent) { + timeFromStartToRedeem = timestampCurrent - timestampStart; + if (timeFromStartToRedeem > timeFromStartToEnd) { + timeFromStartToRedeem = timeFromStartToEnd; // clamp to 100% to avoid reverts + } + } // else timeFromStartToRedeem = 0 + } + + return RedeemParams({ + timeFromStartToEnd: timeFromStartToEnd, + timeFromStartToRedeem: timeFromStartToRedeem, + timeKinkStart: timeKinkStart, + timeKinkEnd: timeKinkEnd, + rateBaseMin: rateBaseMin, + rateBaseMax: rateBaseMax, + remapExp: remapExp, + lsRoot: lsRoot + }); + } +} diff --git a/curve/src/libraries/WTFMath.sol b/curve/src/libraries/WTFMath.sol new file mode 100644 index 0000000..9caf394 --- /dev/null +++ b/curve/src/libraries/WTFMath.sol @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import "@solady/utils/FixedPointMathLib.sol"; + +library WTFMath { + error SafeCastOverflow(); + error ClampIncorrectBounds(); + + using FixedPointMathLib for uint256; + + // All multiplications and divisions are inlined. This means we need to: + // divide by ONE when multiplying and multiply by ONE when dividing + uint256 internal constant WTF_ONE = 1e18; // 1 = 18 decimal places + int256 internal constant WTF_IONE = 1e18; // 1 = 18 decimal places + uint8 internal constant WTF_DECIMALS = 18; // keep it aligned with LogExpMath & FixedPointMathLib pls + + function min(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } + + function max(uint256 a, uint256 b) internal pure returns (uint256) { + return a > b ? a : b; + } + + function min128(uint128 a, uint128 b) internal pure returns (uint128) { + return a < b ? a : b; + } + + function max128(uint128 a, uint128 b) internal pure returns (uint128) { + return a > b ? a : b; + } + + function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { + return a <= b && a >= FixedPointMathLib.fullMulDivUp(b, WTF_ONE - eps, WTF_ONE); + } + + function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { + return a >= b && a <= FixedPointMathLib.fullMulDiv(b, WTF_ONE + eps, WTF_ONE); + } + + function clamp(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256 res) { + if (lower > upper) revert ClampIncorrectBounds(); + res = x; + if (x < lower) res = lower; + else if (x > upper) res = upper; + } + + /*/////////////////////////////////////////////////////////////// + SAFE CASTS + //////////////////////////////////////////////////////////////*/ + /// @dev forked from uniswap V4 but without custom reverts + function toUint256(int256 x) internal pure returns (uint256 y) { + if (x < 0) revert SafeCastOverflow(); + y = uint256(x); + } + + function toUint96(uint256 x) internal pure returns (uint96 y) { + y = uint96(x); + if (x != y) revert SafeCastOverflow(); + } + + /// @dev forked from uniswap V4 but without custom reverts + function toUint128(uint256 x) internal pure returns (uint128 y) { + y = uint128(x); + if (x != y) revert SafeCastOverflow(); + } + + /// @dev forked from uniswap V4 but without custom reverts + function toInt256(uint256 x) internal pure returns (int256 y) { + y = int256(x); + if (y < 0) revert SafeCastOverflow(); + } + + /// @dev this is just int256(uint128(x)), which will always pass. We use this so that the compiler will yell at us if we edit the type of x + function to128Int256(uint128 x) internal pure returns (int256 y) { + assembly ("memory-safe") { + y := x + } + } + + function to128Uint96(uint128 x) internal pure returns (uint96 y) { + y = uint96(x); + if (x != y) revert SafeCastOverflow(); + } + + /// @dev this is just uint128(uint96(x)), which will always pass. We use this so that the compiler will yell at us if we edit the type of x + function to96Uint128(uint96 x) internal pure returns (uint128 y) { + assembly ("memory-safe") { + y := x + } + } +} diff --git a/main/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol b/main/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol new file mode 100644 index 0000000..2c9ab71 --- /dev/null +++ b/main/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.6.0) (access/AccessControl.sol) + +pragma solidity ^0.8.20; + +import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; +import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; +import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol"; +import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; + +/** + * @dev Contract module that allows children to implement role-based access + * control mechanisms. This is a lightweight version that doesn't allow enumerating role + * members except through off-chain means by accessing the contract event logs. Some + * applications may benefit from on-chain enumerability, for those cases see + * {AccessControlEnumerable}. + * + * Roles are referred to by their `bytes32` identifier. These should be exposed + * in the external API and be unique. The best way to achieve this is by + * using `public constant` hash digests: + * + * ```solidity + * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); + * ``` + * + * Roles can be used to represent a set of permissions. To restrict access to a + * function call, use {hasRole}: + * + * ```solidity + * function foo() public { + * require(hasRole(MY_ROLE, msg.sender)); + * ... + * } + * ``` + * + * Roles can be granted and revoked dynamically via the {grantRole} and + * {revokeRole} functions. Each role has an associated admin role, and only + * accounts that have a role's admin role can call {grantRole} and {revokeRole}. + * + * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means + * that only accounts with this role will be able to grant or revoke other + * roles. More complex role relationships can be created by using + * {_setRoleAdmin}. + * + * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to + * grant and revoke this role. Extra precautions should be taken to secure + * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} + * to enforce additional security measures for this role. + */ +abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable { + struct RoleData { + mapping(address account => bool) hasRole; + bytes32 adminRole; + } + + bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; + + + /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl + struct AccessControlStorage { + mapping(bytes32 role => RoleData) _roles; + } + + // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff)) + bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800; + + function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) { + assembly { + $.slot := AccessControlStorageLocation + } + } + + /** + * @dev Modifier that checks that an account has a specific role. Reverts + * with an {AccessControlUnauthorizedAccount} error including the required role. + */ + modifier onlyRole(bytes32 role) { + _checkRole(role); + _; + } + + function __AccessControl_init() internal onlyInitializing { + } + + function __AccessControl_init_unchained() internal onlyInitializing { + } + /// @inheritdoc ERC165Upgradeable + function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { + return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); + } + + /** + * @dev Returns `true` if `account` has been granted `role`. + */ + function hasRole(bytes32 role, address account) public view virtual returns (bool) { + AccessControlStorage storage $ = _getAccessControlStorage(); + return $._roles[role].hasRole[account]; + } + + /** + * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()` + * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier. + */ + function _checkRole(bytes32 role) internal view virtual { + _checkRole(role, _msgSender()); + } + + /** + * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account` + * is missing `role`. + */ + function _checkRole(bytes32 role, address account) internal view virtual { + if (!hasRole(role, account)) { + revert AccessControlUnauthorizedAccount(account, role); + } + } + + /** + * @dev Returns the admin role that controls `role`. See {grantRole} and + * {revokeRole}. + * + * To change a role's admin, use {_setRoleAdmin}. + */ + function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) { + AccessControlStorage storage $ = _getAccessControlStorage(); + return $._roles[role].adminRole; + } + + /** + * @dev Grants `role` to `account`. + * + * If `account` had not been already granted `role`, emits a {RoleGranted} + * event. + * + * Requirements: + * + * - the caller must have ``role``'s admin role. + * + * May emit a {RoleGranted} event. + */ + function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { + _grantRole(role, account); + } + + /** + * @dev Revokes `role` from `account`. + * + * If `account` had been granted `role`, emits a {RoleRevoked} event. + * + * Requirements: + * + * - the caller must have ``role``'s admin role. + * + * May emit a {RoleRevoked} event. + */ + function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { + _revokeRole(role, account); + } + + /** + * @dev Revokes `role` from the calling account. + * + * Roles are often managed via {grantRole} and {revokeRole}: this function's + * purpose is to provide a mechanism for accounts to lose their privileges + * if they are compromised (such as when a trusted device is misplaced). + * + * If the calling account had been revoked `role`, emits a {RoleRevoked} + * event. + * + * Requirements: + * + * - the caller must be `callerConfirmation`. + * + * May emit a {RoleRevoked} event. + */ + function renounceRole(bytes32 role, address callerConfirmation) public virtual { + if (callerConfirmation != _msgSender()) { + revert AccessControlBadConfirmation(); + } + + _revokeRole(role, callerConfirmation); + } + + /** + * @dev Sets `adminRole` as ``role``'s admin role. + * + * Emits a {RoleAdminChanged} event. + */ + function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { + AccessControlStorage storage $ = _getAccessControlStorage(); + bytes32 previousAdminRole = getRoleAdmin(role); + $._roles[role].adminRole = adminRole; + emit RoleAdminChanged(role, previousAdminRole, adminRole); + } + + /** + * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted. + * + * Internal function without access restriction. + * + * May emit a {RoleGranted} event. + */ + function _grantRole(bytes32 role, address account) internal virtual returns (bool) { + AccessControlStorage storage $ = _getAccessControlStorage(); + if (!hasRole(role, account)) { + $._roles[role].hasRole[account] = true; + emit RoleGranted(role, account, _msgSender()); + return true; + } else { + return false; + } + } + + /** + * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked. + * + * Internal function without access restriction. + * + * May emit a {RoleRevoked} event. + */ + function _revokeRole(bytes32 role, address account) internal virtual returns (bool) { + AccessControlStorage storage $ = _getAccessControlStorage(); + if (hasRole(role, account)) { + $._roles[role].hasRole[account] = false; + emit RoleRevoked(role, account, _msgSender()); + return true; + } else { + return false; + } + } +} + diff --git a/main/lib/openzeppelin-contracts-upgradeable/contracts/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol b/main/lib/openzeppelin-contracts-upgradeable/contracts/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol new file mode 100644 index 0000000..d281a08 --- /dev/null +++ b/main/lib/openzeppelin-contracts-upgradeable/contracts/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol @@ -0,0 +1,402 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.6.0) (access/extensions/AccessControlDefaultAdminRules.sol) + +pragma solidity ^0.8.20; + +import {IAccessControlDefaultAdminRules} from "@openzeppelin/contracts/access/extensions/IAccessControlDefaultAdminRules.sol"; +import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol"; +import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; +import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; +import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; +import {IERC5313} from "@openzeppelin/contracts/interfaces/IERC5313.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; + +/** + * @dev Extension of {AccessControl} that allows specifying special rules to manage + * the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions + * over other roles that may potentially have privileged rights in the system. + * + * If a specific role doesn't have an admin role assigned, the holder of the + * `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it. + * + * This contract implements the following risk mitigations on top of {AccessControl}: + * + * * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced. + * * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account. + * * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted. + * * The delay can be changed by scheduling, see {changeDefaultAdminDelay}. + * * Role transfers must wait at least one block after scheduling before it can be accepted. + * * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`. + * + * Example usage: + * + * ```solidity + * contract MyToken is AccessControlDefaultAdminRules { + * constructor() AccessControlDefaultAdminRules( + * 3 days, + * msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder + * ) {} + * } + * ``` + */ +abstract contract AccessControlDefaultAdminRulesUpgradeable is Initializable, IAccessControlDefaultAdminRules, IERC5313, AccessControlUpgradeable { + /// @custom:storage-location erc7201:openzeppelin.storage.AccessControlDefaultAdminRules + struct AccessControlDefaultAdminRulesStorage { + // pending admin pair read/written together frequently + address _pendingDefaultAdmin; + uint48 _pendingDefaultAdminSchedule; // 0 == unset + + uint48 _currentDelay; + address _currentDefaultAdmin; + + // pending delay pair read/written together frequently + uint48 _pendingDelay; + uint48 _pendingDelaySchedule; // 0 == unset + } + + // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlDefaultAdminRules")) - 1)) & ~bytes32(uint256(0xff)) + bytes32 private constant AccessControlDefaultAdminRulesStorageLocation = 0xeef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698400; + + function _getAccessControlDefaultAdminRulesStorage() private pure returns (AccessControlDefaultAdminRulesStorage storage $) { + assembly { + $.slot := AccessControlDefaultAdminRulesStorageLocation + } + } + + /** + * @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address. + */ + function __AccessControlDefaultAdminRules_init(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing { + __AccessControlDefaultAdminRules_init_unchained(initialDelay, initialDefaultAdmin); + } + + function __AccessControlDefaultAdminRules_init_unchained(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + if (initialDefaultAdmin == address(0)) { + revert AccessControlInvalidDefaultAdmin(address(0)); + } + $._currentDelay = initialDelay; + _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin); + } + + /// @inheritdoc IERC165 + function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { + return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId); + } + + /// @inheritdoc IERC5313 + function owner() public view virtual returns (address) { + return defaultAdmin(); + } + + /// + /// Override AccessControl role management + /// + + /** + * @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`. + */ + function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) { + if (role == DEFAULT_ADMIN_ROLE) { + revert AccessControlEnforcedDefaultAdminRules(); + } + super.grantRole(role, account); + } + + /** + * @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`. + */ + function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) { + if (role == DEFAULT_ADMIN_ROLE) { + revert AccessControlEnforcedDefaultAdminRules(); + } + super.revokeRole(role, account); + } + + /** + * @dev See {AccessControl-renounceRole}. + * + * For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling + * {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule + * has also passed when calling this function. + * + * After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions. + * + * NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin}, + * thereby disabling any functionality that is only available for it, and the possibility of reassigning a + * non-administrated role. + */ + function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { + (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin(); + if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { + revert AccessControlEnforcedDefaultAdminDelay(schedule); + } + delete $._pendingDefaultAdminSchedule; + } + super.renounceRole(role, account); + } + + /** + * @dev See {AccessControl-_grantRole}. + * + * For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the + * role has been previously renounced. + * + * NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE` + * assignable again. Make sure to guarantee this is the expected behavior in your implementation. + */ + function _grantRole(bytes32 role, address account) internal virtual override returns (bool) { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + if (role == DEFAULT_ADMIN_ROLE) { + if (defaultAdmin() != address(0)) { + revert AccessControlEnforcedDefaultAdminRules(); + } + $._currentDefaultAdmin = account; + } + return super._grantRole(role, account); + } + + /// @inheritdoc AccessControlUpgradeable + function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { + delete $._currentDefaultAdmin; + } + return super._revokeRole(role, account); + } + + /** + * @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`. + */ + function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override { + if (role == DEFAULT_ADMIN_ROLE) { + revert AccessControlEnforcedDefaultAdminRules(); + } + super._setRoleAdmin(role, adminRole); + } + + /// + /// AccessControlDefaultAdminRules accessors + /// + + /// @inheritdoc IAccessControlDefaultAdminRules + function defaultAdmin() public view virtual returns (address) { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + return $._currentDefaultAdmin; + } + + /// @inheritdoc IAccessControlDefaultAdminRules + function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + return ($._pendingDefaultAdmin, $._pendingDefaultAdminSchedule); + } + + /// @inheritdoc IAccessControlDefaultAdminRules + function defaultAdminDelay() public view virtual returns (uint48) { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + uint48 schedule = $._pendingDelaySchedule; + return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? $._pendingDelay : $._currentDelay; + } + + /// @inheritdoc IAccessControlDefaultAdminRules + function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + schedule = $._pendingDelaySchedule; + return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? ($._pendingDelay, schedule) : (0, 0); + } + + /// @inheritdoc IAccessControlDefaultAdminRules + function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) { + return 5 days; + } + + /// + /// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin + /// + + /// @inheritdoc IAccessControlDefaultAdminRules + function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) { + _beginDefaultAdminTransfer(newAdmin); + } + + /** + * @dev See {beginDefaultAdminTransfer}. + * + * Internal function without access restriction. + */ + function _beginDefaultAdminTransfer(address newAdmin) internal virtual { + uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay(); + _setPendingDefaultAdmin(newAdmin, newSchedule); + emit DefaultAdminTransferScheduled(newAdmin, newSchedule); + } + + /// @inheritdoc IAccessControlDefaultAdminRules + function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { + _cancelDefaultAdminTransfer(); + } + + /** + * @dev See {cancelDefaultAdminTransfer}. + * + * Internal function without access restriction. + */ + function _cancelDefaultAdminTransfer() internal virtual { + _setPendingDefaultAdmin(address(0), 0); + } + + /// @inheritdoc IAccessControlDefaultAdminRules + function acceptDefaultAdminTransfer() public virtual { + (address newDefaultAdmin, ) = pendingDefaultAdmin(); + if (_msgSender() != newDefaultAdmin) { + // Enforce newDefaultAdmin explicit acceptance. + revert AccessControlInvalidDefaultAdmin(_msgSender()); + } + _acceptDefaultAdminTransfer(); + } + + /** + * @dev See {acceptDefaultAdminTransfer}. + * + * Internal function without access restriction. + */ + function _acceptDefaultAdminTransfer() internal virtual { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + (address newAdmin, uint48 schedule) = pendingDefaultAdmin(); + if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { + revert AccessControlEnforcedDefaultAdminDelay(schedule); + } + _revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin()); + _grantRole(DEFAULT_ADMIN_ROLE, newAdmin); + delete $._pendingDefaultAdmin; + delete $._pendingDefaultAdminSchedule; + } + + /// + /// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay + /// + + /// @inheritdoc IAccessControlDefaultAdminRules + function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) { + _changeDefaultAdminDelay(newDelay); + } + + /** + * @dev See {changeDefaultAdminDelay}. + * + * Internal function without access restriction. + */ + function _changeDefaultAdminDelay(uint48 newDelay) internal virtual { + uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay); + _setPendingDelay(newDelay, newSchedule); + emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule); + } + + /// @inheritdoc IAccessControlDefaultAdminRules + function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { + _rollbackDefaultAdminDelay(); + } + + /** + * @dev See {rollbackDefaultAdminDelay}. + * + * Internal function without access restriction. + */ + function _rollbackDefaultAdminDelay() internal virtual { + _setPendingDelay(0, 0); + } + + /** + * @dev Returns the amount of seconds to wait after the `newDelay` will + * become the new {defaultAdminDelay}. + * + * The value returned guarantees that if the delay is reduced, it will go into effect + * after a wait that honors the previously set delay. + * + * See {defaultAdminDelayIncreaseWait}. + */ + function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) { + uint48 currentDelay = defaultAdminDelay(); + + // When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up + // to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day + // to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new + // delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like + // using milliseconds instead of seconds. + // + // When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees + // that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled. + // For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days. + return + newDelay > currentDelay + ? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48 + : currentDelay - newDelay; + } + + /// + /// Private setters + /// + + /** + * @dev Setter of the tuple for pending admin and its schedule. + * + * May emit a {DefaultAdminTransferCanceled} event. + */ + function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + (, uint48 oldSchedule) = pendingDefaultAdmin(); + + $._pendingDefaultAdmin = newAdmin; + $._pendingDefaultAdminSchedule = newSchedule; + + // An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted. + if (_isScheduleSet(oldSchedule)) { + // Emit for implicit cancellations when another default admin was scheduled. + emit DefaultAdminTransferCanceled(); + } + } + + /** + * @dev Setter of the tuple for pending delay and its schedule. + * + * May emit a {DefaultAdminDelayChangeCanceled} event. + */ + function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private { + AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); + uint48 oldSchedule = $._pendingDelaySchedule; + + if (_isScheduleSet(oldSchedule)) { + if (_hasSchedulePassed(oldSchedule)) { + // Materialize a virtual delay + $._currentDelay = $._pendingDelay; + } else { + // Emit for implicit cancellations when another delay was scheduled. + emit DefaultAdminDelayChangeCanceled(); + } + } + + $._pendingDelay = newDelay; + $._pendingDelaySchedule = newSchedule; + } + + /// + /// Private helpers + /// + + /** + * @dev Defines if a `schedule` is considered set. For consistency purposes. + */ + function _isScheduleSet(uint48 schedule) private pure returns (bool) { + return schedule != 0; + } + + /** + * @dev Defines if a `schedule` is considered passed. For consistency purposes. + */ + function _hasSchedulePassed(uint48 schedule) private view returns (bool) { + return schedule < block.timestamp; + } +} + diff --git a/main/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol b/main/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol new file mode 100644 index 0000000..b4bcbd9 --- /dev/null +++ b/main/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; + diff --git a/main/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol b/main/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol new file mode 100644 index 0000000..39a540f --- /dev/null +++ b/main/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) + +pragma solidity ^0.8.20; +import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; + +/** + * @dev Provides information about the current execution context, including the + * sender of the transaction and its data. While these are generally available + * via msg.sender and msg.data, they should not be accessed in such a direct + * manner, since when dealing with meta-transactions the account sending and + * paying for execution may not be the actual sender (as far as an application + * is concerned). + * + * This contract is only required for intermediate, library-like contracts. + */ +abstract contract ContextUpgradeable is Initializable { + function __Context_init() internal onlyInitializing { + } + + function __Context_init_unchained() internal onlyInitializing { + } + function _msgSender() internal view virtual returns (address) { + return msg.sender; + } + + function _msgData() internal view virtual returns (bytes calldata) { + return msg.data; + } + + function _contextSuffixLength() internal view virtual returns (uint256) { + return 0; + } +} + diff --git a/main/lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol b/main/lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol new file mode 100644 index 0000000..8854fc8 --- /dev/null +++ b/main/lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol) + +pragma solidity ^0.8.20; + +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; + +/** + * @dev Implementation of the {IERC165} interface. + * + * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check + * for the additional interface id that will be supported. For example: + * + * ```solidity + * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { + * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); + * } + * ``` + */ +abstract contract ERC165Upgradeable is Initializable, IERC165 { + function __ERC165_init() internal onlyInitializing { + } + + function __ERC165_init_unchained() internal onlyInitializing { + } + /// @inheritdoc IERC165 + function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { + return interfaceId == type(IERC165).interfaceId; + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol b/main/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol new file mode 100644 index 0000000..534d329 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol) + +pragma solidity >=0.8.4; + +/** + * @dev External interface of AccessControl declared to support ERC-165 detection. + */ +interface IAccessControl { + /** + * @dev The `account` is missing a role. + */ + error AccessControlUnauthorizedAccount(address account, bytes32 neededRole); + + /** + * @dev The caller of a function is not the expected one. + * + * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}. + */ + error AccessControlBadConfirmation(); + + /** + * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` + * + * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite + * {RoleAdminChanged} not being emitted to signal this. + */ + event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); + + /** + * @dev Emitted when `account` is granted `role`. + * + * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role). + * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}. + */ + event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); + + /** + * @dev Emitted when `account` is revoked `role`. + * + * `sender` is the account that originated the contract call: + * - if using `revokeRole`, it is the admin role bearer + * - if using `renounceRole`, it is the role bearer (i.e. `account`) + */ + event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); + + /** + * @dev Returns `true` if `account` has been granted `role`. + */ + function hasRole(bytes32 role, address account) external view returns (bool); + + /** + * @dev Returns the admin role that controls `role`. See {grantRole} and + * {revokeRole}. + * + * To change a role's admin, use {AccessControl-_setRoleAdmin}. + */ + function getRoleAdmin(bytes32 role) external view returns (bytes32); + + /** + * @dev Grants `role` to `account`. + * + * If `account` had not been already granted `role`, emits a {RoleGranted} + * event. + * + * Requirements: + * + * - the caller must have ``role``'s admin role. + */ + function grantRole(bytes32 role, address account) external; + + /** + * @dev Revokes `role` from `account`. + * + * If `account` had been granted `role`, emits a {RoleRevoked} event. + * + * Requirements: + * + * - the caller must have ``role``'s admin role. + */ + function revokeRole(bytes32 role, address account) external; + + /** + * @dev Revokes `role` from the calling account. + * + * Roles are often managed via {grantRole} and {revokeRole}: this function's + * purpose is to provide a mechanism for accounts to lose their privileges + * if they are compromised (such as when a trusted device is misplaced). + * + * If the calling account had been granted `role`, emits a {RoleRevoked} + * event. + * + * Requirements: + * + * - the caller must be `callerConfirmation`. + */ + function renounceRole(bytes32 role, address callerConfirmation) external; +} + diff --git a/main/lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlDefaultAdminRules.sol b/main/lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlDefaultAdminRules.sol new file mode 100644 index 0000000..2d73403 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlDefaultAdminRules.sol @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (access/extensions/IAccessControlDefaultAdminRules.sol) + +pragma solidity >=0.8.4; + +import {IAccessControl} from "../IAccessControl.sol"; + +/** + * @dev External interface of AccessControlDefaultAdminRules declared to support ERC-165 detection. + */ +interface IAccessControlDefaultAdminRules is IAccessControl { + /** + * @dev The new default admin is not a valid default admin. + */ + error AccessControlInvalidDefaultAdmin(address defaultAdmin); + + /** + * @dev At least one of the following rules was violated: + * + * - The `DEFAULT_ADMIN_ROLE` must only be managed by itself. + * - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time. + * - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps. + */ + error AccessControlEnforcedDefaultAdminRules(); + + /** + * @dev The delay for transferring the default admin delay is enforced and + * the operation must wait until `schedule`. + * + * NOTE: `schedule` can be 0 indicating there's no transfer scheduled. + */ + error AccessControlEnforcedDefaultAdminDelay(uint48 schedule); + + /** + * @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next + * address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule` + * passes. + */ + event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule); + + /** + * @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule. + */ + event DefaultAdminTransferCanceled(); + + /** + * @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next + * delay to be applied between default admin transfer after `effectSchedule` has passed. + */ + event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule); + + /** + * @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass. + */ + event DefaultAdminDelayChangeCanceled(); + + /** + * @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder. + */ + function defaultAdmin() external view returns (address); + + /** + * @dev Returns a tuple of a `newAdmin` and an accept schedule. + * + * After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role + * by calling {acceptDefaultAdminTransfer}, completing the role transfer. + * + * A zero value only in `acceptSchedule` indicates no pending admin transfer. + * + * NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced. + */ + function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule); + + /** + * @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started. + * + * This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set + * the acceptance schedule. + * + * NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this + * function returns the new delay. See {changeDefaultAdminDelay}. + */ + function defaultAdminDelay() external view returns (uint48); + + /** + * @dev Returns a tuple of `newDelay` and an effect schedule. + * + * After the `schedule` passes, the `newDelay` will get into effect immediately for every + * new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}. + * + * A zero value only in `effectSchedule` indicates no pending delay change. + * + * NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay} + * will be zero after the effect schedule. + */ + function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule); + + /** + * @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance + * after the current timestamp plus a {defaultAdminDelay}. + * + * Requirements: + * + * - Only can be called by the current {defaultAdmin}. + * + * Emits a DefaultAdminRoleChangeStarted event. + */ + function beginDefaultAdminTransfer(address newAdmin) external; + + /** + * @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}. + * + * A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function. + * + * Requirements: + * + * - Only can be called by the current {defaultAdmin}. + * + * May emit a DefaultAdminTransferCanceled event. + */ + function cancelDefaultAdminTransfer() external; + + /** + * @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}. + * + * After calling the function: + * + * - `DEFAULT_ADMIN_ROLE` should be granted to the caller. + * - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder. + * - {pendingDefaultAdmin} should be reset to zero values. + * + * Requirements: + * + * - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`. + * - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed. + */ + function acceptDefaultAdminTransfer() external; + + /** + * @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting + * into effect after the current timestamp plus a {defaultAdminDelay}. + * + * This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this + * method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay} + * set before calling. + * + * The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then + * calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin} + * complete transfer (including acceptance). + * + * The schedule is designed for two scenarios: + * + * - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by + * {defaultAdminDelayIncreaseWait}. + * - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`. + * + * A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change. + * + * Requirements: + * + * - Only can be called by the current {defaultAdmin}. + * + * Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event. + */ + function changeDefaultAdminDelay(uint48 newDelay) external; + + /** + * @dev Cancels a scheduled {defaultAdminDelay} change. + * + * Requirements: + * + * - Only can be called by the current {defaultAdmin}. + * + * May emit a DefaultAdminDelayChangeCanceled event. + */ + function rollbackDefaultAdminDelay() external; + + /** + * @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay}) + * to take effect. Default to 5 days. + * + * When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with + * the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds) + * that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can + * be overridden for a custom {defaultAdminDelay} increase scheduling. + * + * IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise, + * there's a risk of setting a high new delay that goes into effect almost immediately without the + * possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds). + */ + function defaultAdminDelayIncreaseWait() external view returns (uint48); +} + diff --git a/main/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol new file mode 100644 index 0000000..05fe516 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol @@ -0,0 +1,87 @@ +// 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); +} + diff --git a/main/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol new file mode 100644 index 0000000..1e85c20 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol @@ -0,0 +1,7 @@ +// 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"; + diff --git a/main/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol new file mode 100644 index 0000000..170c159 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol @@ -0,0 +1,7 @@ +// 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"; + diff --git a/main/lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol new file mode 100644 index 0000000..f4820bf --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol) + +pragma solidity >=0.6.2; + +import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol"; + diff --git a/main/lib/openzeppelin-contracts/contracts/interfaces/IERC5313.sol b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC5313.sol new file mode 100644 index 0000000..fdd76d0 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC5313.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5313.sol) + +pragma solidity >=0.4.16; + +/** + * @dev Interface for the Light Contract Ownership Standard. + * + * A standardized minimal interface required to identify an account that controls a contract + */ +interface IERC5313 { + /** + * @dev Gets the address of the owner. + */ + function owner() external view returns (address); +} + diff --git a/main/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol new file mode 100644 index 0000000..a0fedbb --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/interfaces/IERC6909.sol @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/IERC6909.sol) + +pragma solidity >=0.6.2; + +import {IERC165} from "../utils/introspection/IERC165.sol"; + +/** + * @dev Required interface of an ERC-6909 compliant contract, as defined in the + * https://eips.ethereum.org/EIPS/eip-6909[ERC]. + */ +interface IERC6909 is IERC165 { + /** + * @dev Emitted when the allowance of a `spender` for an `owner` is set for a token of type `id`. + * The new allowance is `amount`. + */ + event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount); + + /** + * @dev Emitted when `owner` grants or revokes operator status for a `spender`. + */ + event OperatorSet(address indexed owner, address indexed spender, bool approved); + + /** + * @dev Emitted when `amount` tokens of type `id` are moved from `sender` to `receiver` initiated by `caller`. + */ + event Transfer( + address caller, + address indexed sender, + address indexed receiver, + uint256 indexed id, + uint256 amount + ); + + /** + * @dev Returns the amount of tokens of type `id` owned by `owner`. + */ + function balanceOf(address owner, uint256 id) external view returns (uint256); + + /** + * @dev Returns the amount of tokens of type `id` that `spender` is allowed to spend on behalf of `owner`. + * + * NOTE: Does not include operator allowances. + */ + function allowance(address owner, address spender, uint256 id) external view returns (uint256); + + /** + * @dev Returns true if `spender` is set as an operator for `owner`. + */ + function isOperator(address owner, address spender) external view returns (bool); + + /** + * @dev Sets an approval to `spender` for `amount` of tokens of type `id` from the caller's tokens. An `amount` of + * `type(uint256).max` signifies an unlimited approval. + * + * Must return true. + */ + function approve(address spender, uint256 id, uint256 amount) external returns (bool); + + /** + * @dev Grants or revokes unlimited transfer permission of any token id to `spender` for the caller's tokens. + * + * Must return true. + */ + function setOperator(address spender, bool approved) external returns (bool); + + /** + * @dev Transfers `amount` of token type `id` from the caller's account to `receiver`. + * + * Must return true. + */ + function transfer(address receiver, uint256 id, uint256 amount) external returns (bool); + + /** + * @dev Transfers `amount` of token type `id` from `sender` to `receiver`. + * + * Must return true. + */ + function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool); +} + +/** + * @dev Optional extension of {IERC6909} that adds metadata functions. + */ +interface IERC6909Metadata is IERC6909 { + /** + * @dev Returns the name of the token of type `id`. + */ + function name(uint256 id) external view returns (string memory); + + /** + * @dev Returns the ticker symbol of the token of type `id`. + */ + function symbol(uint256 id) external view returns (string memory); + + /** + * @dev Returns the number of decimals for the token of type `id`. + */ + function decimals(uint256 id) external view returns (uint8); +} + +/** + * @dev Optional extension of {IERC6909} that adds content URI functions. + */ +interface IERC6909ContentURI is IERC6909 { + /** + * @dev Returns URI for the contract. + */ + function contractURI() external view returns (string memory); + + /** + * @dev Returns the URI for the token of type `id`. + */ + function tokenURI(uint256 id) external view returns (string memory); +} + +/** + * @dev Optional extension of {IERC6909} that adds a token supply function. + */ +interface IERC6909TokenSupply is IERC6909 { + /** + * @dev Returns the total supply of the token of type `id`. + */ + function totalSupply(uint256 id) external view returns (uint256); +} + diff --git a/main/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol b/main/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol new file mode 100644 index 0000000..0c691de --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol) + +pragma solidity ^0.8.20; + +/** + * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed + * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an + * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer + * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. + * + * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be + * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in + * case an upgrade adds a module that needs to be initialized. + * + * For example: + * + * [.hljs-theme-light.nopadding] + * ```solidity + * contract MyToken is ERC20Upgradeable { + * function initialize() initializer public { + * __ERC20_init("MyToken", "MTK"); + * } + * } + * + * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { + * function initializeV2() reinitializer(2) public { + * __ERC20Permit_init("MyToken"); + * } + * } + * ``` + * + * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as + * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. + * + * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure + * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. + * + * [CAUTION] + * ==== + * Avoid leaving a contract uninitialized. + * + * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation + * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke + * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: + * + * [.hljs-theme-light.nopadding] + * ``` + * /// @custom:oz-upgrades-unsafe-allow constructor + * constructor() { + * _disableInitializers(); + * } + * ``` + * ==== + */ +abstract contract Initializable { + /** + * @dev Storage of the initializable contract. + * + * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions + * when using with upgradeable contracts. + * + * @custom:storage-location erc7201:openzeppelin.storage.Initializable + */ + struct InitializableStorage { + /** + * @dev Indicates that the contract has been initialized. + */ + uint64 _initialized; + /** + * @dev Indicates that the contract is in the process of being initialized. + */ + bool _initializing; + } + + // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff)) + bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00; + + /** + * @dev The contract is already initialized. + */ + error InvalidInitialization(); + + /** + * @dev The contract is not initializing. + */ + error NotInitializing(); + + /** + * @dev Triggered when the contract has been initialized or reinitialized. + */ + event Initialized(uint64 version); + + /** + * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, + * `onlyInitializing` functions can be used to initialize parent contracts. + * + * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any + * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in + * production. + * + * Emits an {Initialized} event. + */ + modifier initializer() { + // solhint-disable-next-line var-name-mixedcase + InitializableStorage storage $ = _getInitializableStorage(); + + // Cache values to avoid duplicated sloads + bool isTopLevelCall = !$._initializing; + uint64 initialized = $._initialized; + + // Allowed calls: + // - initialSetup: the contract is not in the initializing state and no previous version was + // initialized + // - construction: the contract is initialized at version 1 (no reinitialization) and the + // current contract is just being deployed + bool initialSetup = initialized == 0 && isTopLevelCall; + bool construction = initialized == 1 && address(this).code.length == 0; + + if (!initialSetup && !construction) { + revert InvalidInitialization(); + } + $._initialized = 1; + if (isTopLevelCall) { + $._initializing = true; + } + _; + if (isTopLevelCall) { + $._initializing = false; + emit Initialized(1); + } + } + + /** + * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the + * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be + * used to initialize parent contracts. + * + * A reinitializer may be used after the original initialization step. This is essential to configure modules that + * are added through upgrades and that require initialization. + * + * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` + * cannot be nested. If one is invoked in the context of another, execution will revert. + * + * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in + * a contract, executing them in the right order is up to the developer or operator. + * + * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization. + * + * Emits an {Initialized} event. + */ + modifier reinitializer(uint64 version) { + // solhint-disable-next-line var-name-mixedcase + InitializableStorage storage $ = _getInitializableStorage(); + + if ($._initializing || $._initialized >= version) { + revert InvalidInitialization(); + } + $._initialized = version; + $._initializing = true; + _; + $._initializing = false; + emit Initialized(version); + } + + /** + * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the + * {initializer} and {reinitializer} modifiers, directly or indirectly. + */ + modifier onlyInitializing() { + _checkInitializing(); + _; + } + + /** + * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}. + */ + function _checkInitializing() internal view virtual { + if (!_isInitializing()) { + revert NotInitializing(); + } + } + + /** + * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. + * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized + * to any version. It is recommended to use this to lock implementation contracts that are designed to be called + * through proxies. + * + * Emits an {Initialized} event the first time it is successfully executed. + */ + function _disableInitializers() internal virtual { + // solhint-disable-next-line var-name-mixedcase + InitializableStorage storage $ = _getInitializableStorage(); + + if ($._initializing) { + revert InvalidInitialization(); + } + if ($._initialized != type(uint64).max) { + $._initialized = type(uint64).max; + emit Initialized(type(uint64).max); + } + } + + /** + * @dev Returns the highest version that has been initialized. See {reinitializer}. + */ + function _getInitializedVersion() internal view returns (uint64) { + return _getInitializableStorage()._initialized; + } + + /** + * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. + */ + function _isInitializing() internal view returns (bool) { + return _getInitializableStorage()._initializing; + } + + /** + * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location. + * + * NOTE: Consider following the ERC-7201 formula to derive storage locations. + */ + function _initializableStorageSlot() internal pure virtual returns (bytes32) { + return INITIALIZABLE_STORAGE; + } + + /** + * @dev Returns a pointer to the storage namespace. + */ + // solhint-disable-next-line var-name-mixedcase + function _getInitializableStorage() private pure returns (InitializableStorage storage $) { + bytes32 slot = _initializableStorageSlot(); + assembly { + $.slot := slot + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol b/main/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol new file mode 100644 index 0000000..13d23ae --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol @@ -0,0 +1,80 @@ +// 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); +} + diff --git a/main/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol b/main/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol new file mode 100644 index 0000000..961ed4f --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol @@ -0,0 +1,27 @@ +// 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); +} + diff --git a/main/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol b/main/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol new file mode 100644 index 0000000..be091b9 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol) + +pragma solidity ^0.8.20; + +import {IERC20} from "../IERC20.sol"; +import {IERC1363} from "../../../interfaces/IERC1363.sol"; + +/** + * @title SafeERC20 + * @dev Wrappers around ERC-20 operations that throw on failure (when the token + * contract returns false). Tokens that return no value (and instead revert or + * throw on failure) are also supported, non-reverting calls are assumed to be + * successful. + * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + /** + * @dev An operation with an ERC-20 token failed. + */ + error SafeERC20FailedOperation(address token); + + /** + * @dev Indicates a failed `decreaseAllowance` request. + */ + error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); + + /** + * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, + * non-reverting calls are assumed to be successful. + */ + function safeTransfer(IERC20 token, address to, uint256 value) internal { + if (!_safeTransfer(token, to, value, true)) { + revert SafeERC20FailedOperation(address(token)); + } + } + + /** + * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the + * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. + */ + function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { + if (!_safeTransferFrom(token, from, to, value, true)) { + revert SafeERC20FailedOperation(address(token)); + } + } + + /** + * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful. + */ + function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) { + return _safeTransfer(token, to, value, false); + } + + /** + * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful. + */ + function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) { + return _safeTransferFrom(token, from, to, value, false); + } + + /** + * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, + * non-reverting calls are assumed to be successful. + * + * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" + * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using + * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract + * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. + */ + function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { + uint256 oldAllowance = token.allowance(address(this), spender); + forceApprove(token, spender, oldAllowance + value); + } + + /** + * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no + * value, non-reverting calls are assumed to be successful. + * + * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" + * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using + * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract + * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. + */ + function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { + unchecked { + uint256 currentAllowance = token.allowance(address(this), spender); + if (currentAllowance < requestedDecrease) { + revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); + } + forceApprove(token, spender, currentAllowance - requestedDecrease); + } + } + + /** + * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, + * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval + * to be set to zero before setting it to a non-zero value, such as USDT. + * + * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function + * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being + * set here. + */ + function forceApprove(IERC20 token, address spender, uint256 value) internal { + if (!_safeApprove(token, spender, value, false)) { + if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token)); + if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token)); + } + } + + /** + * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no + * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when + * targeting contracts. + * + * Reverts if the returned value is other than `true`. + */ + function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { + if (to.code.length == 0) { + safeTransfer(token, to, value); + } else if (!token.transferAndCall(to, value, data)) { + revert SafeERC20FailedOperation(address(token)); + } + } + + /** + * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target + * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when + * targeting contracts. + * + * Reverts if the returned value is other than `true`. + */ + function transferFromAndCallRelaxed( + IERC1363 token, + address from, + address to, + uint256 value, + bytes memory data + ) internal { + if (to.code.length == 0) { + safeTransferFrom(token, from, to, value); + } else if (!token.transferFromAndCall(from, to, value, data)) { + revert SafeERC20FailedOperation(address(token)); + } + } + + /** + * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no + * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when + * targeting contracts. + * + * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}. + * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall} + * once without retrying, and relies on the returned value to be true. + * + * Reverts if the returned value is other than `true`. + */ + function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { + if (to.code.length == 0) { + forceApprove(token, to, value); + } else if (!token.approveAndCall(to, value, data)) { + revert SafeERC20FailedOperation(address(token)); + } + } + + /** + * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the + * return value is optional (but if data is returned, it must not be false). + * + * @param token The token targeted by the call. + * @param to The recipient of the tokens + * @param value The amount of token to transfer + * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean. + */ + function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) { + bytes4 selector = IERC20.transfer.selector; + + assembly ("memory-safe") { + let fmp := mload(0x40) + mstore(0x00, selector) + mstore(0x04, and(to, shr(96, not(0)))) + mstore(0x24, value) + success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20) + // if call success and return is true, all is good. + // otherwise (not success or return is not true), we need to perform further checks + if iszero(and(success, eq(mload(0x00), 1))) { + // if the call was a failure and bubble is enabled, bubble the error + if and(iszero(success), bubble) { + returndatacopy(fmp, 0x00, returndatasize()) + revert(fmp, returndatasize()) + } + // if the return value is not true, then the call is only successful if: + // - the token address has code + // - the returndata is empty + success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0))) + } + mstore(0x40, fmp) + } + } + + /** + * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return + * value: the return value is optional (but if data is returned, it must not be false). + * + * @param token The token targeted by the call. + * @param from The sender of the tokens + * @param to The recipient of the tokens + * @param value The amount of token to transfer + * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean. + */ + function _safeTransferFrom( + IERC20 token, + address from, + address to, + uint256 value, + bool bubble + ) private returns (bool success) { + bytes4 selector = IERC20.transferFrom.selector; + + assembly ("memory-safe") { + let fmp := mload(0x40) + mstore(0x00, selector) + mstore(0x04, and(from, shr(96, not(0)))) + mstore(0x24, and(to, shr(96, not(0)))) + mstore(0x44, value) + success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20) + // if call success and return is true, all is good. + // otherwise (not success or return is not true), we need to perform further checks + if iszero(and(success, eq(mload(0x00), 1))) { + // if the call was a failure and bubble is enabled, bubble the error + if and(iszero(success), bubble) { + returndatacopy(fmp, 0x00, returndatasize()) + revert(fmp, returndatasize()) + } + // if the return value is not true, then the call is only successful if: + // - the token address has code + // - the returndata is empty + success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0))) + } + mstore(0x40, fmp) + mstore(0x60, 0) + } + } + + /** + * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value: + * the return value is optional (but if data is returned, it must not be false). + * + * @param token The token targeted by the call. + * @param spender The spender of the tokens + * @param value The amount of token to transfer + * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean. + */ + function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) { + bytes4 selector = IERC20.approve.selector; + + assembly ("memory-safe") { + let fmp := mload(0x40) + mstore(0x00, selector) + mstore(0x04, and(spender, shr(96, not(0)))) + mstore(0x24, value) + success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20) + // if call success and return is true, all is good. + // otherwise (not success or return is not true), we need to perform further checks + if iszero(and(success, eq(mload(0x00), 1))) { + // if the call was a failure and bubble is enabled, bubble the error + if and(iszero(success), bubble) { + returndatacopy(fmp, 0x00, returndatasize()) + revert(fmp, returndatasize()) + } + // if the return value is not true, then the call is only successful if: + // - the token address has code + // - the returndata is empty + success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0))) + } + mstore(0x40, fmp) + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/Arrays.sol b/main/lib/openzeppelin-contracts/contracts/utils/Arrays.sol new file mode 100644 index 0000000..48a44d0 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/Arrays.sol @@ -0,0 +1,736 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (utils/Arrays.sol) +// This file was procedurally generated from scripts/generate/templates/Arrays.js. + +pragma solidity ^0.8.24; + +import {Comparators} from "./Comparators.sol"; +import {SlotDerivation} from "./SlotDerivation.sol"; +import {StorageSlot} from "./StorageSlot.sol"; +import {Math} from "./math/Math.sol"; + +/** + * @dev Collection of functions related to array types. + */ +library Arrays { + using SlotDerivation for bytes32; + using StorageSlot for bytes32; + + /** + * @dev Sort an array of uint256 (in memory) following the provided comparator function. + * + * This function does the sorting "in place", meaning that it overrides the input. The object is returned for + * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array. + * + * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the + * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful + * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may + * consume more gas than is available in a block, leading to potential DoS. + * + * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way. + */ + function sort( + uint256[] memory array, + function(uint256, uint256) pure returns (bool) comp + ) internal pure returns (uint256[] memory) { + _quickSort(_begin(array), _end(array), comp); + return array; + } + + /** + * @dev Variant of {sort} that sorts an array of uint256 in increasing order. + */ + function sort(uint256[] memory array) internal pure returns (uint256[] memory) { + sort(array, Comparators.lt); + return array; + } + + /** + * @dev Sort an array of address (in memory) following the provided comparator function. + * + * This function does the sorting "in place", meaning that it overrides the input. The object is returned for + * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array. + * + * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the + * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful + * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may + * consume more gas than is available in a block, leading to potential DoS. + * + * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way. + */ + function sort( + address[] memory array, + function(address, address) pure returns (bool) comp + ) internal pure returns (address[] memory) { + sort(_castToUint256Array(array), _castToUint256Comp(comp)); + return array; + } + + /** + * @dev Variant of {sort} that sorts an array of address in increasing order. + */ + function sort(address[] memory array) internal pure returns (address[] memory) { + sort(_castToUint256Array(array), Comparators.lt); + return array; + } + + /** + * @dev Sort an array of bytes32 (in memory) following the provided comparator function. + * + * This function does the sorting "in place", meaning that it overrides the input. The object is returned for + * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array. + * + * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the + * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful + * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may + * consume more gas than is available in a block, leading to potential DoS. + * + * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way. + */ + function sort( + bytes32[] memory array, + function(bytes32, bytes32) pure returns (bool) comp + ) internal pure returns (bytes32[] memory) { + sort(_castToUint256Array(array), _castToUint256Comp(comp)); + return array; + } + + /** + * @dev Variant of {sort} that sorts an array of bytes32 in increasing order. + */ + function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) { + sort(_castToUint256Array(array), Comparators.lt); + return array; + } + + /** + * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops + * at end (exclusive). Sorting follows the `comp` comparator. + * + * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls. + * + * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should + * be used only if the limits are within a memory array. + */ + function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure { + unchecked { + if (end - begin < 0x40) return; + + // Use first element as pivot + uint256 pivot = _mload(begin); + // Position where the pivot should be at the end of the loop + uint256 pos = begin; + + for (uint256 it = begin + 0x20; it < end; it += 0x20) { + if (comp(_mload(it), pivot)) { + // If the value stored at the iterator's position comes before the pivot, we increment the + // position of the pivot and move the value there. + pos += 0x20; + _swap(pos, it); + } + } + + _swap(begin, pos); // Swap pivot into place + _quickSort(begin, pos, comp); // Sort the left side of the pivot + _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot + } + } + + /** + * @dev Pointer to the memory location of the first element of `array`. + */ + function _begin(uint256[] memory array) private pure returns (uint256 ptr) { + assembly ("memory-safe") { + ptr := add(array, 0x20) + } + } + + /** + * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word + * that comes just after the last element of the array. + */ + function _end(uint256[] memory array) private pure returns (uint256 ptr) { + unchecked { + return _begin(array) + array.length * 0x20; + } + } + + /** + * @dev Load memory word (as a uint256) at location `ptr`. + */ + function _mload(uint256 ptr) private pure returns (uint256 value) { + assembly { + value := mload(ptr) + } + } + + /** + * @dev Swaps the elements memory location `ptr1` and `ptr2`. + */ + function _swap(uint256 ptr1, uint256 ptr2) private pure { + assembly { + let value1 := mload(ptr1) + let value2 := mload(ptr2) + mstore(ptr1, value2) + mstore(ptr2, value1) + } + } + + /// @dev Helper: low level cast address memory array to uint256 memory array + function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) { + assembly { + output := input + } + } + + /// @dev Helper: low level cast bytes32 memory array to uint256 memory array + function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) { + assembly { + output := input + } + } + + /// @dev Helper: low level cast address comp function to uint256 comp function + function _castToUint256Comp( + function(address, address) pure returns (bool) input + ) private pure returns (function(uint256, uint256) pure returns (bool) output) { + assembly { + output := input + } + } + + /// @dev Helper: low level cast bytes32 comp function to uint256 comp function + function _castToUint256Comp( + function(bytes32, bytes32) pure returns (bool) input + ) private pure returns (function(uint256, uint256) pure returns (bool) output) { + assembly { + output := input + } + } + + /** + * @dev Searches a sorted `array` and returns the first index that contains + * a value greater or equal to `element`. If no such index exists (i.e. all + * values in the array are strictly less than `element`), the array length is + * returned. Time complexity O(log n). + * + * NOTE: The `array` is expected to be sorted in ascending order, and to + * contain no repeated elements. + * + * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks + * support for repeated elements in the array. The {lowerBound} function should + * be used instead. + */ + function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { + uint256 low = 0; + uint256 high = array.length; + + if (high == 0) { + return 0; + } + + while (low < high) { + uint256 mid = Math.average(low, high); + + // Note that mid will always be strictly less than high (i.e. it will be a valid array index) + // because Math.average rounds towards zero (it does integer division with truncation). + if (unsafeAccess(array, mid).value > element) { + high = mid; + } else { + low = mid + 1; + } + } + + // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. + if (low > 0 && unsafeAccess(array, low - 1).value == element) { + return low - 1; + } else { + return low; + } + } + + /** + * @dev Searches an `array` sorted in ascending order and returns the first + * index that contains a value greater or equal than `element`. If no such index + * exists (i.e. all values in the array are strictly less than `element`), the array + * length is returned. Time complexity O(log n). + * + * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound]. + */ + function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) { + uint256 low = 0; + uint256 high = array.length; + + if (high == 0) { + return 0; + } + + while (low < high) { + uint256 mid = Math.average(low, high); + + // Note that mid will always be strictly less than high (i.e. it will be a valid array index) + // because Math.average rounds towards zero (it does integer division with truncation). + if (unsafeAccess(array, mid).value < element) { + // this cannot overflow because mid < high + unchecked { + low = mid + 1; + } + } else { + high = mid; + } + } + + return low; + } + + /** + * @dev Searches an `array` sorted in ascending order and returns the first + * index that contains a value strictly greater than `element`. If no such index + * exists (i.e. all values in the array are strictly less than `element`), the array + * length is returned. Time complexity O(log n). + * + * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound]. + */ + function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { + uint256 low = 0; + uint256 high = array.length; + + if (high == 0) { + return 0; + } + + while (low < high) { + uint256 mid = Math.average(low, high); + + // Note that mid will always be strictly less than high (i.e. it will be a valid array index) + // because Math.average rounds towards zero (it does integer division with truncation). + if (unsafeAccess(array, mid).value > element) { + high = mid; + } else { + // this cannot overflow because mid < high + unchecked { + low = mid + 1; + } + } + } + + return low; + } + + /** + * @dev Same as {lowerBound}, but with an array in memory. + */ + function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) { + uint256 low = 0; + uint256 high = array.length; + + if (high == 0) { + return 0; + } + + while (low < high) { + uint256 mid = Math.average(low, high); + + // Note that mid will always be strictly less than high (i.e. it will be a valid array index) + // because Math.average rounds towards zero (it does integer division with truncation). + if (unsafeMemoryAccess(array, mid) < element) { + // this cannot overflow because mid < high + unchecked { + low = mid + 1; + } + } else { + high = mid; + } + } + + return low; + } + + /** + * @dev Same as {upperBound}, but with an array in memory. + */ + function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) { + uint256 low = 0; + uint256 high = array.length; + + if (high == 0) { + return 0; + } + + while (low < high) { + uint256 mid = Math.average(low, high); + + // Note that mid will always be strictly less than high (i.e. it will be a valid array index) + // because Math.average rounds towards zero (it does integer division with truncation). + if (unsafeMemoryAccess(array, mid) > element) { + high = mid; + } else { + // this cannot overflow because mid < high + unchecked { + low = mid + 1; + } + } + } + + return low; + } + + /** + * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new address array in + * memory. + * + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`] + */ + function slice(address[] memory array, uint256 start) internal pure returns (address[] memory) { + return slice(array, start, array.length); + } + + /** + * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new address array in + * memory. The `end` argument is truncated to the length of the `array`. + * + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`] + */ + function slice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) { + // sanitize + end = Math.min(end, array.length); + start = Math.min(start, end); + + // allocate and copy + address[] memory result = new address[](end - start); + assembly ("memory-safe") { + mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20)) + } + + return result; + } + + /** + * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new bytes32 array in + * memory. + * + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`] + */ + function slice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) { + return slice(array, start, array.length); + } + + /** + * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new bytes32 array in + * memory. The `end` argument is truncated to the length of the `array`. + * + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`] + */ + function slice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) { + // sanitize + end = Math.min(end, array.length); + start = Math.min(start, end); + + // allocate and copy + bytes32[] memory result = new bytes32[](end - start); + assembly ("memory-safe") { + mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20)) + } + + return result; + } + + /** + * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new uint256 array in + * memory. + * + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`] + */ + function slice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) { + return slice(array, start, array.length); + } + + /** + * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new uint256 array in + * memory. The `end` argument is truncated to the length of the `array`. + * + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`] + */ + function slice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) { + // sanitize + end = Math.min(end, array.length); + start = Math.min(start, end); + + // allocate and copy + uint256[] memory result = new uint256[](end - start); + assembly ("memory-safe") { + mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20)) + } + + return result; + } + + /** + * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array. + * + * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead. + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`] + */ + function splice(address[] memory array, uint256 start) internal pure returns (address[] memory) { + return splice(array, start, array.length); + } + + /** + * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The + * `end` argument is truncated to the length of the `array`. + * + * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead. + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`] + */ + function splice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) { + // sanitize + end = Math.min(end, array.length); + start = Math.min(start, end); + + // move and resize + assembly ("memory-safe") { + mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20)) + mstore(array, sub(end, start)) + } + + return array; + } + + /** + * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array. + * + * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead. + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`] + */ + function splice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) { + return splice(array, start, array.length); + } + + /** + * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The + * `end` argument is truncated to the length of the `array`. + * + * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead. + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`] + */ + function splice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) { + // sanitize + end = Math.min(end, array.length); + start = Math.min(start, end); + + // move and resize + assembly ("memory-safe") { + mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20)) + mstore(array, sub(end, start)) + } + + return array; + } + + /** + * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array. + * + * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead. + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`] + */ + function splice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) { + return splice(array, start, array.length); + } + + /** + * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The + * `end` argument is truncated to the length of the `array`. + * + * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead. + * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`] + */ + function splice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) { + // sanitize + end = Math.min(end, array.length); + start = Math.min(start, end); + + // move and resize + assembly ("memory-safe") { + mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20)) + mstore(array, sub(end, start)) + } + + return array; + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) { + bytes32 slot; + assembly ("memory-safe") { + slot := arr.slot + } + return slot.deriveArray().offset(pos).getAddressSlot(); + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) { + bytes32 slot; + assembly ("memory-safe") { + slot := arr.slot + } + return slot.deriveArray().offset(pos).getBytes32Slot(); + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) { + bytes32 slot; + assembly ("memory-safe") { + slot := arr.slot + } + return slot.deriveArray().offset(pos).getUint256Slot(); + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) { + bytes32 slot; + assembly ("memory-safe") { + slot := arr.slot + } + return slot.deriveArray().offset(pos).getBytesSlot(); + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) { + bytes32 slot; + assembly ("memory-safe") { + slot := arr.slot + } + return slot.deriveArray().offset(pos).getStringSlot(); + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) { + assembly { + res := mload(add(add(arr, 0x20), mul(pos, 0x20))) + } + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) { + assembly { + res := mload(add(add(arr, 0x20), mul(pos, 0x20))) + } + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) { + assembly { + res := mload(add(add(arr, 0x20), mul(pos, 0x20))) + } + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) { + assembly { + res := mload(add(add(arr, 0x20), mul(pos, 0x20))) + } + } + + /** + * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. + * + * WARNING: Only use if you are certain `pos` is lower than the array length. + */ + function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) { + assembly { + res := mload(add(add(arr, 0x20), mul(pos, 0x20))) + } + } + + /** + * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden. + * + * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. + */ + function unsafeSetLength(address[] storage array, uint256 len) internal { + assembly ("memory-safe") { + sstore(array.slot, len) + } + } + + /** + * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden. + * + * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. + */ + function unsafeSetLength(bytes32[] storage array, uint256 len) internal { + assembly ("memory-safe") { + sstore(array.slot, len) + } + } + + /** + * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden. + * + * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. + */ + function unsafeSetLength(uint256[] storage array, uint256 len) internal { + assembly ("memory-safe") { + sstore(array.slot, len) + } + } + + /** + * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden. + * + * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. + */ + function unsafeSetLength(bytes[] storage array, uint256 len) internal { + assembly ("memory-safe") { + sstore(array.slot, len) + } + } + + /** + * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden. + * + * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. + */ + function unsafeSetLength(string[] storage array, uint256 len) internal { + assembly ("memory-safe") { + sstore(array.slot, len) + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/Comparators.sol b/main/lib/openzeppelin-contracts/contracts/utils/Comparators.sol new file mode 100644 index 0000000..e2ca22a --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/Comparators.sol @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol) + +pragma solidity ^0.8.20; + +/** + * @dev Provides a set of functions to compare values. + * + * _Available since v5.1._ + */ +library Comparators { + function lt(uint256 a, uint256 b) internal pure returns (bool) { + return a < b; + } + + function gt(uint256 a, uint256 b) internal pure returns (bool) { + return a > b; + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/Panic.sol b/main/lib/openzeppelin-contracts/contracts/utils/Panic.sol new file mode 100644 index 0000000..fb88869 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/Panic.sol @@ -0,0 +1,58 @@ +// 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) + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol b/main/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol new file mode 100644 index 0000000..19a9778 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol) + +pragma solidity ^0.8.24; + +import {TransientSlot} from "./TransientSlot.sol"; + +/** + * @dev Variant of {ReentrancyGuard} that uses transient storage. + * + * NOTE: This variant only works on networks where EIP-1153 is available. + * + * _Available since v5.1._ + * + * @custom:stateless + */ +abstract contract ReentrancyGuardTransient { + using TransientSlot for *; + + // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff)) + bytes32 private constant REENTRANCY_GUARD_STORAGE = + 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00; + + /** + * @dev Unauthorized reentrant call. + */ + error ReentrancyGuardReentrantCall(); + + /** + * @dev Prevents a contract from calling itself, directly or indirectly. + * Calling a `nonReentrant` function from another `nonReentrant` + * function is not supported. It is possible to prevent this from happening + * by making the `nonReentrant` function external, and making it call a + * `private` function that does the actual work. + */ + modifier nonReentrant() { + _nonReentrantBefore(); + _; + _nonReentrantAfter(); + } + + /** + * @dev A `view` only version of {nonReentrant}. Use to block view functions + * from being called, preventing reading from inconsistent contract state. + * + * CAUTION: This is a "view" modifier and does not change the reentrancy + * status. Use it only on view functions. For payable or non-payable functions, + * use the standard {nonReentrant} modifier instead. + */ + modifier nonReentrantView() { + _nonReentrantBeforeView(); + _; + } + + function _nonReentrantBeforeView() private view { + if (_reentrancyGuardEntered()) { + revert ReentrancyGuardReentrantCall(); + } + } + + function _nonReentrantBefore() private { + // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false + _nonReentrantBeforeView(); + + // Any calls to nonReentrant after this point will fail + _reentrancyGuardStorageSlot().asBoolean().tstore(true); + } + + function _nonReentrantAfter() private { + _reentrancyGuardStorageSlot().asBoolean().tstore(false); + } + + /** + * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a + * `nonReentrant` function in the call stack. + */ + function _reentrancyGuardEntered() internal view returns (bool) { + return _reentrancyGuardStorageSlot().asBoolean().tload(); + } + + function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) { + return REENTRANCY_GUARD_STORAGE; + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol b/main/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol new file mode 100644 index 0000000..1aa0317 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (utils/SlotDerivation.sol) +// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js. + +pragma solidity ^0.8.20; + +/** + * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots + * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by + * the solidity language / compiler. + * + * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.]. + * + * Example usage: + * ```solidity + * contract Example { + * // Add the library methods + * using StorageSlot for bytes32; + * using SlotDerivation for *; + * + * // Declare a namespace + * string private constant _NAMESPACE = ""; // eg. OpenZeppelin.Slot + * + * function setValueInNamespace(uint256 key, address newValue) internal { + * _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue; + * } + * + * function getValueInNamespace(uint256 key) internal view returns (address) { + * return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value; + * } + * } + * ``` + * + * TIP: Consider using this library along with {StorageSlot}. + * + * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking + * upgrade safety will ignore the slots accessed through this library. + * + * _Available since v5.1._ + */ +library SlotDerivation { + /** + * @dev Derive an ERC-7201 slot from a string (namespace). + */ + function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) { + assembly ("memory-safe") { + mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1)) + slot := and(keccak256(0x00, 0x20), not(0xff)) + } + } + + /** + * @dev Add an offset to a slot to get the n-th element of a structure or an array. + */ + function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) { + unchecked { + return bytes32(uint256(slot) + pos); + } + } + + /** + * @dev Derive the location of the first element in an array from the slot where the length is stored. + */ + function deriveArray(bytes32 slot) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + mstore(0x00, slot) + result := keccak256(0x00, 0x20) + } + } + + /** + * @dev Derive the location of a mapping element from the key. + */ + function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + mstore(0x00, and(key, shr(96, not(0)))) + mstore(0x20, slot) + result := keccak256(0x00, 0x40) + } + } + + /** + * @dev Derive the location of a mapping element from the key. + */ + function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + mstore(0x00, iszero(iszero(key))) + mstore(0x20, slot) + result := keccak256(0x00, 0x40) + } + } + + /** + * @dev Derive the location of a mapping element from the key. + */ + function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + mstore(0x00, key) + mstore(0x20, slot) + result := keccak256(0x00, 0x40) + } + } + + /** + * @dev Derive the location of a mapping element from the key. + */ + function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + mstore(0x00, key) + mstore(0x20, slot) + result := keccak256(0x00, 0x40) + } + } + + /** + * @dev Derive the location of a mapping element from the key. + */ + function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + mstore(0x00, key) + mstore(0x20, slot) + result := keccak256(0x00, 0x40) + } + } + + /** + * @dev Derive the location of a mapping element from the key. + */ + function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + let length := mload(key) + let begin := add(key, 0x20) + let end := add(begin, length) + let cache := mload(end) + mstore(end, slot) + result := keccak256(begin, add(length, 0x20)) + mstore(end, cache) + } + } + + /** + * @dev Derive the location of a mapping element from the key. + */ + function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) { + assembly ("memory-safe") { + let length := mload(key) + let begin := add(key, 0x20) + let end := add(begin, length) + let cache := mload(end) + mstore(end, slot) + result := keccak256(begin, add(length, 0x20)) + mstore(end, cache) + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol b/main/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol new file mode 100644 index 0000000..676c5ef --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol) +// This file was procedurally generated from scripts/generate/templates/StorageSlot.js. + +pragma solidity ^0.8.20; + +/** + * @dev Library for reading and writing primitive types to specific storage slots. + * + * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. + * This library helps with reading and writing to such slots without the need for inline assembly. + * + * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. + * + * Example usage to set ERC-1967 implementation slot: + * ```solidity + * contract ERC1967 { + * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot. + * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; + * + * function _getImplementation() internal view returns (address) { + * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; + * } + * + * function _setImplementation(address newImplementation) internal { + * require(newImplementation.code.length > 0); + * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; + * } + * } + * ``` + * + * TIP: Consider using this library along with {SlotDerivation}. + */ +library StorageSlot { + struct AddressSlot { + address value; + } + + struct BooleanSlot { + bool value; + } + + struct Bytes32Slot { + bytes32 value; + } + + struct Uint256Slot { + uint256 value; + } + + struct Int256Slot { + int256 value; + } + + struct StringSlot { + string value; + } + + struct BytesSlot { + bytes value; + } + + /** + * @dev Returns an `AddressSlot` with member `value` located at `slot`. + */ + function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { + assembly ("memory-safe") { + r.slot := slot + } + } + + /** + * @dev Returns a `BooleanSlot` with member `value` located at `slot`. + */ + function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { + assembly ("memory-safe") { + r.slot := slot + } + } + + /** + * @dev Returns a `Bytes32Slot` with member `value` located at `slot`. + */ + function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { + assembly ("memory-safe") { + r.slot := slot + } + } + + /** + * @dev Returns a `Uint256Slot` with member `value` located at `slot`. + */ + function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { + assembly ("memory-safe") { + r.slot := slot + } + } + + /** + * @dev Returns a `Int256Slot` with member `value` located at `slot`. + */ + function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) { + assembly ("memory-safe") { + r.slot := slot + } + } + + /** + * @dev Returns a `StringSlot` with member `value` located at `slot`. + */ + function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { + assembly ("memory-safe") { + r.slot := slot + } + } + + /** + * @dev Returns an `StringSlot` representation of the string storage pointer `store`. + */ + function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { + assembly ("memory-safe") { + r.slot := store.slot + } + } + + /** + * @dev Returns a `BytesSlot` with member `value` located at `slot`. + */ + function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { + assembly ("memory-safe") { + r.slot := slot + } + } + + /** + * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. + */ + function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { + assembly ("memory-safe") { + r.slot := store.slot + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol b/main/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol new file mode 100644 index 0000000..8bb4df7 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol) +// This file was procedurally generated from scripts/generate/templates/TransientSlot.js. + +pragma solidity ^0.8.24; + +/** + * @dev Library for reading and writing value-types to specific transient storage slots. + * + * Transient slots are often used to store temporary values that are removed after the current transaction. + * This library helps with reading and writing to such slots without the need for inline assembly. + * + * * Example reading and writing values using transient storage: + * ```solidity + * contract Lock { + * using TransientSlot for *; + * + * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot. + * bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542; + * + * modifier locked() { + * require(!_LOCK_SLOT.asBoolean().tload()); + * + * _LOCK_SLOT.asBoolean().tstore(true); + * _; + * _LOCK_SLOT.asBoolean().tstore(false); + * } + * } + * ``` + * + * TIP: Consider using this library along with {SlotDerivation}. + */ +library TransientSlot { + /** + * @dev UDVT that represents a slot holding an address. + */ + type AddressSlot is bytes32; + + /** + * @dev Cast an arbitrary slot to a AddressSlot. + */ + function asAddress(bytes32 slot) internal pure returns (AddressSlot) { + return AddressSlot.wrap(slot); + } + + /** + * @dev UDVT that represents a slot holding a bool. + */ + type BooleanSlot is bytes32; + + /** + * @dev Cast an arbitrary slot to a BooleanSlot. + */ + function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) { + return BooleanSlot.wrap(slot); + } + + /** + * @dev UDVT that represents a slot holding a bytes32. + */ + type Bytes32Slot is bytes32; + + /** + * @dev Cast an arbitrary slot to a Bytes32Slot. + */ + function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) { + return Bytes32Slot.wrap(slot); + } + + /** + * @dev UDVT that represents a slot holding a uint256. + */ + type Uint256Slot is bytes32; + + /** + * @dev Cast an arbitrary slot to a Uint256Slot. + */ + function asUint256(bytes32 slot) internal pure returns (Uint256Slot) { + return Uint256Slot.wrap(slot); + } + + /** + * @dev UDVT that represents a slot holding a int256. + */ + type Int256Slot is bytes32; + + /** + * @dev Cast an arbitrary slot to a Int256Slot. + */ + function asInt256(bytes32 slot) internal pure returns (Int256Slot) { + return Int256Slot.wrap(slot); + } + + /** + * @dev Load the value held at location `slot` in transient storage. + */ + function tload(AddressSlot slot) internal view returns (address value) { + assembly ("memory-safe") { + value := tload(slot) + } + } + + /** + * @dev Store `value` at location `slot` in transient storage. + */ + function tstore(AddressSlot slot, address value) internal { + assembly ("memory-safe") { + tstore(slot, value) + } + } + + /** + * @dev Load the value held at location `slot` in transient storage. + */ + function tload(BooleanSlot slot) internal view returns (bool value) { + assembly ("memory-safe") { + value := tload(slot) + } + } + + /** + * @dev Store `value` at location `slot` in transient storage. + */ + function tstore(BooleanSlot slot, bool value) internal { + assembly ("memory-safe") { + tstore(slot, value) + } + } + + /** + * @dev Load the value held at location `slot` in transient storage. + */ + function tload(Bytes32Slot slot) internal view returns (bytes32 value) { + assembly ("memory-safe") { + value := tload(slot) + } + } + + /** + * @dev Store `value` at location `slot` in transient storage. + */ + function tstore(Bytes32Slot slot, bytes32 value) internal { + assembly ("memory-safe") { + tstore(slot, value) + } + } + + /** + * @dev Load the value held at location `slot` in transient storage. + */ + function tload(Uint256Slot slot) internal view returns (uint256 value) { + assembly ("memory-safe") { + value := tload(slot) + } + } + + /** + * @dev Store `value` at location `slot` in transient storage. + */ + function tstore(Uint256Slot slot, uint256 value) internal { + assembly ("memory-safe") { + tstore(slot, value) + } + } + + /** + * @dev Load the value held at location `slot` in transient storage. + */ + function tload(Int256Slot slot) internal view returns (int256 value) { + assembly ("memory-safe") { + value := tload(slot) + } + } + + /** + * @dev Store `value` at location `slot` in transient storage. + */ + function tstore(Int256Slot slot, int256 value) internal { + assembly ("memory-safe") { + tstore(slot, value) + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol b/main/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol new file mode 100644 index 0000000..31400b9 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol @@ -0,0 +1,26 @@ +// 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; + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol b/main/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol new file mode 100644 index 0000000..0325938 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol @@ -0,0 +1,26 @@ +// 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); +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/math/Math.sol b/main/lib/openzeppelin-contracts/contracts/utils/math/Math.sol new file mode 100644 index 0000000..e5ada61 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/math/Math.sol @@ -0,0 +1,757 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.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 `condition ? a : b`. 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. `condition ? a : b`) 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; + } + + /** + * @dev Counts the number of leading zero bits in a uint256. + */ + function clz(uint256 x) internal pure returns (uint256) { + return ternary(x == 0, 256, 255 - log2(x)); + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol b/main/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol new file mode 100644 index 0000000..978f79b --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol @@ -0,0 +1,1163 @@ +// 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)) + } + } +} + diff --git a/main/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol b/main/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol new file mode 100644 index 0000000..31c4ad3 --- /dev/null +++ b/main/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol @@ -0,0 +1,793 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.5.0) (utils/structs/EnumerableSet.sol) +// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. + +pragma solidity ^0.8.24; + +import {Arrays} from "../Arrays.sol"; +import {Math} from "../math/Math.sol"; + +/** + * @dev Library for managing + * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive + * types. + * + * Sets have the following properties: + * + * - Elements are added, removed, and checked for existence in constant time + * (O(1)). + * - Elements are enumerated in O(n). No guarantees are made on the ordering. + * - Set can be cleared (all elements removed) in O(n). + * + * ```solidity + * contract Example { + * // Add the library methods + * using EnumerableSet for EnumerableSet.AddressSet; + * + * // Declare a set state variable + * EnumerableSet.AddressSet private mySet; + * } + * ``` + * + * The following types are supported: + * + * - `bytes32` (`Bytes32Set`) since v3.3.0 + * - `address` (`AddressSet`) since v3.3.0 + * - `uint256` (`UintSet`) since v3.3.0 + * - `string` (`StringSet`) since v5.4.0 + * - `bytes` (`BytesSet`) since v5.4.0 + * + * [WARNING] + * ==== + * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure + * unusable. + * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. + * + * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an + * array of EnumerableSet. + * ==== + */ +library EnumerableSet { + // To implement this library for multiple types with as little code + // repetition as possible, we write it in terms of a generic Set type with + // bytes32 values. + // The Set implementation uses private functions, and user-facing + // implementations (such as AddressSet) are just wrappers around the + // underlying Set. + // This means that we can only create new EnumerableSets for types that fit + // in bytes32. + + struct Set { + // Storage of set values + bytes32[] _values; + // Position is the index of the value in the `values` array plus 1. + // Position 0 is used to mean a value is not in the set. + mapping(bytes32 value => uint256) _positions; + } + + /** + * @dev Add a value to a set. O(1). + * + * Returns true if the value was added to the set, that is if it was not + * already present. + */ + function _add(Set storage set, bytes32 value) private returns (bool) { + if (!_contains(set, value)) { + set._values.push(value); + // The value is stored at length-1, but we add 1 to all indexes + // and use 0 as a sentinel value + set._positions[value] = set._values.length; + return true; + } else { + return false; + } + } + + /** + * @dev Removes a value from a set. O(1). + * + * Returns true if the value was removed from the set, that is if it was + * present. + */ + function _remove(Set storage set, bytes32 value) private returns (bool) { + // We cache the value's position to prevent multiple reads from the same storage slot + uint256 position = set._positions[value]; + + if (position != 0) { + // Equivalent to contains(set, value) + // To delete an element from the _values array in O(1), we swap the element to delete with the last one in + // the array, and then remove the last element (sometimes called as 'swap and pop'). + // This modifies the order of the array, as noted in {at}. + + uint256 valueIndex = position - 1; + uint256 lastIndex = set._values.length - 1; + + if (valueIndex != lastIndex) { + bytes32 lastValue = set._values[lastIndex]; + + // Move the lastValue to the index where the value to delete is + set._values[valueIndex] = lastValue; + // Update the tracked position of the lastValue (that was just moved) + set._positions[lastValue] = position; + } + + // Delete the slot where the moved value was stored + set._values.pop(); + + // Delete the tracked position for the deleted slot + delete set._positions[value]; + + return true; + } else { + return false; + } + } + + /** + * @dev Removes all the values from a set. O(n). + * + * WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that + * using it may render the function uncallable if the set grows to the point where clearing it consumes too much + * gas to fit in a block. + */ + function _clear(Set storage set) private { + uint256 len = _length(set); + for (uint256 i = 0; i < len; ++i) { + delete set._positions[set._values[i]]; + } + Arrays.unsafeSetLength(set._values, 0); + } + + /** + * @dev Returns true if the value is in the set. O(1). + */ + function _contains(Set storage set, bytes32 value) private view returns (bool) { + return set._positions[value] != 0; + } + + /** + * @dev Returns the number of values on the set. O(1). + */ + function _length(Set storage set) private view returns (uint256) { + return set._values.length; + } + + /** + * @dev Returns the value stored at position `index` in the set. O(1). + * + * Note that there are no guarantees on the ordering of values inside the + * array, and it may change when more values are added or removed. + * + * Requirements: + * + * - `index` must be strictly less than {length}. + */ + function _at(Set storage set, uint256 index) private view returns (bytes32) { + return set._values[index]; + } + + /** + * @dev Return the entire set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function _values(Set storage set) private view returns (bytes32[] memory) { + return set._values; + } + + /** + * @dev Return a slice of the set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function _values(Set storage set, uint256 start, uint256 end) private view returns (bytes32[] memory) { + unchecked { + end = Math.min(end, _length(set)); + start = Math.min(start, end); + + uint256 len = end - start; + bytes32[] memory result = new bytes32[](len); + for (uint256 i = 0; i < len; ++i) { + result[i] = Arrays.unsafeAccess(set._values, start + i).value; + } + return result; + } + } + + // Bytes32Set + + struct Bytes32Set { + Set _inner; + } + + /** + * @dev Add a value to a set. O(1). + * + * Returns true if the value was added to the set, that is if it was not + * already present. + */ + function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { + return _add(set._inner, value); + } + + /** + * @dev Removes a value from a set. O(1). + * + * Returns true if the value was removed from the set, that is if it was + * present. + */ + function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { + return _remove(set._inner, value); + } + + /** + * @dev Removes all the values from a set. O(n). + * + * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the + * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block. + */ + function clear(Bytes32Set storage set) internal { + _clear(set._inner); + } + + /** + * @dev Returns true if the value is in the set. O(1). + */ + function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { + return _contains(set._inner, value); + } + + /** + * @dev Returns the number of values in the set. O(1). + */ + function length(Bytes32Set storage set) internal view returns (uint256) { + return _length(set._inner); + } + + /** + * @dev Returns the value stored at position `index` in the set. O(1). + * + * Note that there are no guarantees on the ordering of values inside the + * array, and it may change when more values are added or removed. + * + * Requirements: + * + * - `index` must be strictly less than {length}. + */ + function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { + return _at(set._inner, index); + } + + /** + * @dev Return the entire set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { + bytes32[] memory store = _values(set._inner); + bytes32[] memory result; + + assembly ("memory-safe") { + result := store + } + + return result; + } + + /** + * @dev Return a slice of the set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(Bytes32Set storage set, uint256 start, uint256 end) internal view returns (bytes32[] memory) { + bytes32[] memory store = _values(set._inner, start, end); + bytes32[] memory result; + + assembly ("memory-safe") { + result := store + } + + return result; + } + + // AddressSet + + struct AddressSet { + Set _inner; + } + + /** + * @dev Add a value to a set. O(1). + * + * Returns true if the value was added to the set, that is if it was not + * already present. + */ + function add(AddressSet storage set, address value) internal returns (bool) { + return _add(set._inner, bytes32(uint256(uint160(value)))); + } + + /** + * @dev Removes a value from a set. O(1). + * + * Returns true if the value was removed from the set, that is if it was + * present. + */ + function remove(AddressSet storage set, address value) internal returns (bool) { + return _remove(set._inner, bytes32(uint256(uint160(value)))); + } + + /** + * @dev Removes all the values from a set. O(n). + * + * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the + * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block. + */ + function clear(AddressSet storage set) internal { + _clear(set._inner); + } + + /** + * @dev Returns true if the value is in the set. O(1). + */ + function contains(AddressSet storage set, address value) internal view returns (bool) { + return _contains(set._inner, bytes32(uint256(uint160(value)))); + } + + /** + * @dev Returns the number of values in the set. O(1). + */ + function length(AddressSet storage set) internal view returns (uint256) { + return _length(set._inner); + } + + /** + * @dev Returns the value stored at position `index` in the set. O(1). + * + * Note that there are no guarantees on the ordering of values inside the + * array, and it may change when more values are added or removed. + * + * Requirements: + * + * - `index` must be strictly less than {length}. + */ + function at(AddressSet storage set, uint256 index) internal view returns (address) { + return address(uint160(uint256(_at(set._inner, index)))); + } + + /** + * @dev Return the entire set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(AddressSet storage set) internal view returns (address[] memory) { + bytes32[] memory store = _values(set._inner); + address[] memory result; + + assembly ("memory-safe") { + result := store + } + + return result; + } + + /** + * @dev Return a slice of the set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(AddressSet storage set, uint256 start, uint256 end) internal view returns (address[] memory) { + bytes32[] memory store = _values(set._inner, start, end); + address[] memory result; + + assembly ("memory-safe") { + result := store + } + + return result; + } + + // UintSet + + struct UintSet { + Set _inner; + } + + /** + * @dev Add a value to a set. O(1). + * + * Returns true if the value was added to the set, that is if it was not + * already present. + */ + function add(UintSet storage set, uint256 value) internal returns (bool) { + return _add(set._inner, bytes32(value)); + } + + /** + * @dev Removes a value from a set. O(1). + * + * Returns true if the value was removed from the set, that is if it was + * present. + */ + function remove(UintSet storage set, uint256 value) internal returns (bool) { + return _remove(set._inner, bytes32(value)); + } + + /** + * @dev Removes all the values from a set. O(n). + * + * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the + * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block. + */ + function clear(UintSet storage set) internal { + _clear(set._inner); + } + + /** + * @dev Returns true if the value is in the set. O(1). + */ + function contains(UintSet storage set, uint256 value) internal view returns (bool) { + return _contains(set._inner, bytes32(value)); + } + + /** + * @dev Returns the number of values in the set. O(1). + */ + function length(UintSet storage set) internal view returns (uint256) { + return _length(set._inner); + } + + /** + * @dev Returns the value stored at position `index` in the set. O(1). + * + * Note that there are no guarantees on the ordering of values inside the + * array, and it may change when more values are added or removed. + * + * Requirements: + * + * - `index` must be strictly less than {length}. + */ + function at(UintSet storage set, uint256 index) internal view returns (uint256) { + return uint256(_at(set._inner, index)); + } + + /** + * @dev Return the entire set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(UintSet storage set) internal view returns (uint256[] memory) { + bytes32[] memory store = _values(set._inner); + uint256[] memory result; + + assembly ("memory-safe") { + result := store + } + + return result; + } + + /** + * @dev Return a slice of the set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(UintSet storage set, uint256 start, uint256 end) internal view returns (uint256[] memory) { + bytes32[] memory store = _values(set._inner, start, end); + uint256[] memory result; + + assembly ("memory-safe") { + result := store + } + + return result; + } + + struct StringSet { + // Storage of set values + string[] _values; + // Position is the index of the value in the `values` array plus 1. + // Position 0 is used to mean a value is not in the set. + mapping(string value => uint256) _positions; + } + + /** + * @dev Add a value to a set. O(1). + * + * Returns true if the value was added to the set, that is if it was not + * already present. + */ + function add(StringSet storage set, string memory value) internal returns (bool) { + if (!contains(set, value)) { + set._values.push(value); + // The value is stored at length-1, but we add 1 to all indexes + // and use 0 as a sentinel value + set._positions[value] = set._values.length; + return true; + } else { + return false; + } + } + + /** + * @dev Removes a value from a set. O(1). + * + * Returns true if the value was removed from the set, that is if it was + * present. + */ + function remove(StringSet storage set, string memory value) internal returns (bool) { + // We cache the value's position to prevent multiple reads from the same storage slot + uint256 position = set._positions[value]; + + if (position != 0) { + // Equivalent to contains(set, value) + // To delete an element from the _values array in O(1), we swap the element to delete with the last one in + // the array, and then remove the last element (sometimes called as 'swap and pop'). + // This modifies the order of the array, as noted in {at}. + + uint256 valueIndex = position - 1; + uint256 lastIndex = set._values.length - 1; + + if (valueIndex != lastIndex) { + string memory lastValue = set._values[lastIndex]; + + // Move the lastValue to the index where the value to delete is + set._values[valueIndex] = lastValue; + // Update the tracked position of the lastValue (that was just moved) + set._positions[lastValue] = position; + } + + // Delete the slot where the moved value was stored + set._values.pop(); + + // Delete the tracked position for the deleted slot + delete set._positions[value]; + + return true; + } else { + return false; + } + } + + /** + * @dev Removes all the values from a set. O(n). + * + * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the + * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block. + */ + function clear(StringSet storage set) internal { + uint256 len = length(set); + for (uint256 i = 0; i < len; ++i) { + delete set._positions[set._values[i]]; + } + Arrays.unsafeSetLength(set._values, 0); + } + + /** + * @dev Returns true if the value is in the set. O(1). + */ + function contains(StringSet storage set, string memory value) internal view returns (bool) { + return set._positions[value] != 0; + } + + /** + * @dev Returns the number of values on the set. O(1). + */ + function length(StringSet storage set) internal view returns (uint256) { + return set._values.length; + } + + /** + * @dev Returns the value stored at position `index` in the set. O(1). + * + * Note that there are no guarantees on the ordering of values inside the + * array, and it may change when more values are added or removed. + * + * Requirements: + * + * - `index` must be strictly less than {length}. + */ + function at(StringSet storage set, uint256 index) internal view returns (string memory) { + return set._values[index]; + } + + /** + * @dev Return the entire set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(StringSet storage set) internal view returns (string[] memory) { + return set._values; + } + + /** + * @dev Return a slice of the set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) { + unchecked { + end = Math.min(end, length(set)); + start = Math.min(start, end); + + uint256 len = end - start; + string[] memory result = new string[](len); + for (uint256 i = 0; i < len; ++i) { + result[i] = Arrays.unsafeAccess(set._values, start + i).value; + } + return result; + } + } + + struct BytesSet { + // Storage of set values + bytes[] _values; + // Position is the index of the value in the `values` array plus 1. + // Position 0 is used to mean a value is not in the set. + mapping(bytes value => uint256) _positions; + } + + /** + * @dev Add a value to a set. O(1). + * + * Returns true if the value was added to the set, that is if it was not + * already present. + */ + function add(BytesSet storage set, bytes memory value) internal returns (bool) { + if (!contains(set, value)) { + set._values.push(value); + // The value is stored at length-1, but we add 1 to all indexes + // and use 0 as a sentinel value + set._positions[value] = set._values.length; + return true; + } else { + return false; + } + } + + /** + * @dev Removes a value from a set. O(1). + * + * Returns true if the value was removed from the set, that is if it was + * present. + */ + function remove(BytesSet storage set, bytes memory value) internal returns (bool) { + // We cache the value's position to prevent multiple reads from the same storage slot + uint256 position = set._positions[value]; + + if (position != 0) { + // Equivalent to contains(set, value) + // To delete an element from the _values array in O(1), we swap the element to delete with the last one in + // the array, and then remove the last element (sometimes called as 'swap and pop'). + // This modifies the order of the array, as noted in {at}. + + uint256 valueIndex = position - 1; + uint256 lastIndex = set._values.length - 1; + + if (valueIndex != lastIndex) { + bytes memory lastValue = set._values[lastIndex]; + + // Move the lastValue to the index where the value to delete is + set._values[valueIndex] = lastValue; + // Update the tracked position of the lastValue (that was just moved) + set._positions[lastValue] = position; + } + + // Delete the slot where the moved value was stored + set._values.pop(); + + // Delete the tracked position for the deleted slot + delete set._positions[value]; + + return true; + } else { + return false; + } + } + + /** + * @dev Removes all the values from a set. O(n). + * + * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the + * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block. + */ + function clear(BytesSet storage set) internal { + uint256 len = length(set); + for (uint256 i = 0; i < len; ++i) { + delete set._positions[set._values[i]]; + } + Arrays.unsafeSetLength(set._values, 0); + } + + /** + * @dev Returns true if the value is in the set. O(1). + */ + function contains(BytesSet storage set, bytes memory value) internal view returns (bool) { + return set._positions[value] != 0; + } + + /** + * @dev Returns the number of values on the set. O(1). + */ + function length(BytesSet storage set) internal view returns (uint256) { + return set._values.length; + } + + /** + * @dev Returns the value stored at position `index` in the set. O(1). + * + * Note that there are no guarantees on the ordering of values inside the + * array, and it may change when more values are added or removed. + * + * Requirements: + * + * - `index` must be strictly less than {length}. + */ + function at(BytesSet storage set, uint256 index) internal view returns (bytes memory) { + return set._values[index]; + } + + /** + * @dev Return the entire set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(BytesSet storage set) internal view returns (bytes[] memory) { + return set._values; + } + + /** + * @dev Return a slice of the set in an array + * + * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed + * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that + * this function has an unbounded cost, and using it as part of a state-changing function may render the function + * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. + */ + function values(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) { + unchecked { + end = Math.min(end, length(set)); + start = Math.min(start, end); + + uint256 len = end - start; + bytes[] memory result = new bytes[](len); + for (uint256 i = 0; i < len; ++i) { + result[i] = Arrays.unsafeAccess(set._values, start + i).value; + } + return result; + } + } +} + diff --git a/main/lib/solady/src/utils/FixedPointMathLib.sol b/main/lib/solady/src/utils/FixedPointMathLib.sol new file mode 100644 index 0000000..575e2ee --- /dev/null +++ b/main/lib/solady/src/utils/FixedPointMathLib.sol @@ -0,0 +1,1313 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.4; + +/// @notice Arithmetic library with operations for fixed-point numbers. +/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol) +/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) +library FixedPointMathLib { + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* CUSTOM ERRORS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev The operation failed, as the output exceeds the maximum value of uint256. + error ExpOverflow(); + + /// @dev The operation failed, as the output exceeds the maximum value of uint256. + error FactorialOverflow(); + + /// @dev The operation failed, due to an overflow. + error RPowOverflow(); + + /// @dev The mantissa is too big to fit. + error MantissaOverflow(); + + /// @dev The operation failed, due to an multiplication overflow. + error MulWadFailed(); + + /// @dev The operation failed, due to an multiplication overflow. + error SMulWadFailed(); + + /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. + error DivWadFailed(); + + /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. + error SDivWadFailed(); + + /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. + error MulDivFailed(); + + /// @dev The division failed, as the denominator is zero. + error DivFailed(); + + /// @dev The full precision multiply-divide operation failed, either due + /// to the result being larger than 256 bits, or a division by a zero. + error FullMulDivFailed(); + + /// @dev The output is undefined, as the input is less-than-or-equal to zero. + error LnWadUndefined(); + + /// @dev The input outside the acceptable domain. + error OutOfDomain(); + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* CONSTANTS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev The scalar of ETH and most ERC20s. + uint256 internal constant WAD = 1e18; + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* SIMPLIFIED FIXED POINT OPERATIONS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Equivalent to `(x * y) / WAD` rounded down. + function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. + if gt(x, div(not(0), y)) { + if y { + mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. + revert(0x1c, 0x04) + } + } + z := div(mul(x, y), WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded down. + function sMulWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`. + if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) { + mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`. + revert(0x1c, 0x04) + } + z := sdiv(z, WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. + function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := div(mul(x, y), WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. + function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := sdiv(mul(x, y), WAD) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded up. + function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. + if iszero(eq(div(z, y), x)) { + if y { + mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. + revert(0x1c, 0x04) + } + } + z := add(iszero(iszero(mod(z, WAD))), div(z, WAD)) + } + } + + /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks. + function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD)) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down. + function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. + if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { + mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. + revert(0x1c, 0x04) + } + z := div(mul(x, WAD), y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down. + function sDivWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, WAD) + // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`. + if iszero(mul(y, eq(sdiv(z, WAD), x))) { + mstore(0x00, 0x5c43740d) // `SDivWadFailed()`. + revert(0x1c, 0x04) + } + z := sdiv(z, y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. + function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := div(mul(x, WAD), y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. + function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := sdiv(mul(x, WAD), y) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded up. + function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. + if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { + mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. + revert(0x1c, 0x04) + } + z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) + } + } + + /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks. + function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) + } + } + + /// @dev Equivalent to `x` to the power of `y`. + /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`. + /// Note: This function is an approximation. + function powWad(int256 x, int256 y) internal pure returns (int256) { + // Using `ln(x)` means `x` must be greater than 0. + return expWad((lnWad(x) * y) / int256(WAD)); + } + + /// @dev Returns `exp(x)`, denominated in `WAD`. + /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln + /// Note: This function is an approximation. Monotonically increasing. + function expWad(int256 x) internal pure returns (int256 r) { + unchecked { + // When the result is less than 0.5 we return zero. + // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`. + if (x <= -41446531673892822313) return r; + + /// @solidity memory-safe-assembly + assembly { + // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as + // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`. + if iszero(slt(x, 135305999368893231589)) { + mstore(0x00, 0xa37bfec9) // `ExpOverflow()`. + revert(0x1c, 0x04) + } + } + + // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96` + // for more intermediate precision and a binary basis. This base conversion + // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78. + x = (x << 78) / 5 ** 18; + + // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers + // of two such that exp(x) = exp(x') * 2**k, where k is an integer. + // Solving this gives k = round(x / log(2)) and x' = x - k * log(2). + int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96; + x = x - k * 54916777467707473351141471128; + + // `k` is in the range `[-61, 195]`. + + // Evaluate using a (6, 7)-term rational approximation. + // `p` is made monic, we'll multiply by a scale factor later. + int256 y = x + 1346386616545796478920950773328; + y = ((y * x) >> 96) + 57155421227552351082224309758442; + int256 p = y + x - 94201549194550492254356042504812; + p = ((p * y) >> 96) + 28719021644029726153956944680412240; + p = p * x + (4385272521454847904659076985693276 << 96); + + // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. + int256 q = x - 2855989394907223263936484059900; + q = ((q * x) >> 96) + 50020603652535783019961831881945; + q = ((q * x) >> 96) - 533845033583426703283633433725380; + q = ((q * x) >> 96) + 3604857256930695427073651918091429; + q = ((q * x) >> 96) - 14423608567350463180887372962807573; + q = ((q * x) >> 96) + 26449188498355588339934803723976023; + + /// @solidity memory-safe-assembly + assembly { + // Div in assembly because solidity adds a zero check despite the unchecked. + // The q polynomial won't have zeros in the domain as all its roots are complex. + // No scaling is necessary because p is already `2**96` too large. + r := sdiv(p, q) + } + + // r should be in the range `(0.09, 0.25) * 2**96`. + + // We now need to multiply r by: + // - The scale factor `s ≈ 6.031367120`. + // - The `2**k` factor from the range reduction. + // - The `1e18 / 2**96` factor for base conversion. + // We do this all at once, with an intermediate result in `2**213` + // basis, so the final right shift is always by a positive amount. + r = int256( + (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k) + ); + } + } + + /// @dev Returns `ln(x)`, denominated in `WAD`. + /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln + /// Note: This function is an approximation. Monotonically increasing. + function lnWad(int256 x) internal pure returns (int256 r) { + /// @solidity memory-safe-assembly + assembly { + // We want to convert `x` from `10**18` fixed point to `2**96` fixed point. + // We do this by multiplying by `2**96 / 10**18`. But since + // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here + // and add `ln(2**96 / 10**18)` at the end. + + // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`. + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + // We place the check here for more optimal stack operations. + if iszero(sgt(x, 0)) { + mstore(0x00, 0x1615e638) // `LnWadUndefined()`. + revert(0x1c, 0x04) + } + // forgefmt: disable-next-item + r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), + 0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)) + + // Reduce range of x to (1, 2) * 2**96 + // ln(2^k * x) = k * ln(2) + ln(x) + x := shr(159, shl(r, x)) + + // Evaluate using a (8, 8)-term rational approximation. + // `p` is made monic, we will multiply by a scale factor later. + // forgefmt: disable-next-item + let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir. + sar(96, mul(add(43456485725739037958740375743393, + sar(96, mul(add(24828157081833163892658089445524, + sar(96, mul(add(3273285459638523848632254066296, + x), x))), x))), x)), 11111509109440967052023855526967) + p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857) + p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526) + p := sub(mul(p, x), shl(96, 795164235651350426258249787498)) + // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. + + // `q` is monic by convention. + let q := add(5573035233440673466300451813936, x) + q := add(71694874799317883764090561454958, sar(96, mul(x, q))) + q := add(283447036172924575727196451306956, sar(96, mul(x, q))) + q := add(401686690394027663651624208769553, sar(96, mul(x, q))) + q := add(204048457590392012362485061816622, sar(96, mul(x, q))) + q := add(31853899698501571402653359427138, sar(96, mul(x, q))) + q := add(909429971244387300277376558375, sar(96, mul(x, q))) + + // `p / q` is in the range `(0, 0.125) * 2**96`. + + // Finalization, we need to: + // - Multiply by the scale factor `s = 5.549…`. + // - Add `ln(2**96 / 10**18)`. + // - Add `k * ln(2)`. + // - Multiply by `10**18 / 2**96 = 5**18 >> 78`. + + // The q polynomial is known not to have zeros in the domain. + // No scaling required because p is already `2**96` too large. + p := sdiv(p, q) + // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`. + p := mul(1677202110996718588342820967067443963516166, p) + // Add `ln(2) * k * 5**18 * 2**192`. + // forgefmt: disable-next-item + p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p) + // Add `ln(2**96 / 10**18) * 5**18 * 2**192`. + p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p) + // Base conversion: mul `2**18 / 2**192`. + r := sar(174, p) + } + } + + /// @dev Returns `W_0(x)`, denominated in `WAD`. + /// See: https://en.wikipedia.org/wiki/Lambert_W_function + /// a.k.a. Product log function. This is an approximation of the principal branch. + /// Note: This function is an approximation. Monotonically increasing. + function lambertW0Wad(int256 x) internal pure returns (int256 w) { + // forgefmt: disable-next-item + unchecked { + if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`. + (int256 wad, int256 p) = (int256(WAD), x); + uint256 c; // Whether we need to avoid catastrophic cancellation. + uint256 i = 4; // Number of iterations. + if (w <= 0x1ffffffffffff) { + if (-0x4000000000000 <= w) { + i = 1; // Inputs near zero only take one step to converge. + } else if (w <= -0x3ffffffffffffff) { + i = 32; // Inputs near `-1/e` take very long to converge. + } + } else if (uint256(w >> 63) == uint256(0)) { + /// @solidity memory-safe-assembly + assembly { + // Inline log2 for more performance, since the range is small. + let v := shr(49, w) + let l := shl(3, lt(0xff, v)) + l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)), + 0x0706060506020504060203020504030106050205030304010505030400000000)), 49) + w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13)) + c := gt(l, 60) + i := add(2, add(gt(l, 53), c)) + } + } else { + int256 ll = lnWad(w = lnWad(w)); + /// @solidity memory-safe-assembly + assembly { + // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`. + w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll)) + i := add(3, iszero(shr(68, x))) + c := iszero(shr(143, x)) + } + if (c == uint256(0)) { + do { // If `x` is big, use Newton's so that intermediate values won't overflow. + int256 e = expWad(w); + /// @solidity memory-safe-assembly + assembly { + let t := mul(w, div(e, wad)) + w := sub(w, sdiv(sub(t, x), div(add(e, t), wad))) + } + if (p <= w) break; + p = w; + } while (--i != uint256(0)); + /// @solidity memory-safe-assembly + assembly { + w := sub(w, sgt(w, 2)) + } + return w; + } + } + do { // Otherwise, use Halley's for faster convergence. + int256 e = expWad(w); + /// @solidity memory-safe-assembly + assembly { + let t := add(w, wad) + let s := sub(mul(w, e), mul(x, wad)) + w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t))))) + } + if (p <= w) break; + p = w; + } while (--i != c); + /// @solidity memory-safe-assembly + assembly { + w := sub(w, sgt(w, 2)) + } + // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of + // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation. + if (c == uint256(0)) return w; + int256 t = w | 1; + /// @solidity memory-safe-assembly + assembly { + x := sdiv(mul(x, wad), t) + } + x = (t * (wad + lnWad(x))); + /// @solidity memory-safe-assembly + assembly { + w := sdiv(x, add(wad, t)) + } + } + } + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* GENERAL NUMBER UTILITIES */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Returns `a * b == x * y`, with full precision. + function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y) + internal + pure + returns (bool result) + { + /// @solidity memory-safe-assembly + assembly { + result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0)))) + } + } + + /// @dev Calculates `floor(x * y / d)` with full precision. + /// Throws if result overflows a uint256 or when `d` is zero. + /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv + function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // 512-bit multiply `[p1 p0] = x * y`. + // Compute the product mod `2**256` and mod `2**256 - 1` + // then use the Chinese Remainder Theorem to reconstruct + // the 512 bit result. The result is stored in two 256 + // variables such that `product = p1 * 2**256 + p0`. + + // Temporarily use `z` as `p0` to save gas. + z := mul(x, y) // Lower 256 bits of `x * y`. + for {} 1 {} { + // If overflows. + if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { + let mm := mulmod(x, y, not(0)) + let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. + + /*------------------- 512 by 256 division --------------------*/ + + // Make division exact by subtracting the remainder from `[p1 p0]`. + let r := mulmod(x, y, d) // Compute remainder using mulmod. + let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`. + // Make sure `z` is less than `2**256`. Also prevents `d == 0`. + // Placing the check here seems to give more optimal stack operations. + if iszero(gt(d, p1)) { + mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. + revert(0x1c, 0x04) + } + d := div(d, t) // Divide `d` by `t`, which is a power of two. + // Invert `d mod 2**256` + // Now that `d` is an odd number, it has an inverse + // modulo `2**256` such that `d * inv = 1 mod 2**256`. + // Compute the inverse by starting with a seed that is correct + // correct for four bits. That is, `d * inv = 1 mod 2**4`. + let inv := xor(2, mul(3, d)) + // Now use 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. + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64 + inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128 + z := + mul( + // Divide [p1 p0] by the factors of two. + // Shift in bits from `p1` into `p0`. For this we need + // to flip `t` such that it is `2**256 / t`. + or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), + mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256 + ) + break + } + z := div(z, d) + break + } + } + } + + /// @dev Calculates `floor(x * y / d)` with full precision. + /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits. + /// Performs the full 512 bit calculation regardless. + function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d) + internal + pure + returns (uint256 z) + { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + let mm := mulmod(x, y, not(0)) + let p1 := sub(mm, add(z, lt(mm, z))) + let t := and(d, sub(0, d)) + let r := mulmod(x, y, d) + d := div(d, t) + let inv := xor(2, mul(3, d)) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + inv := mul(inv, sub(2, mul(d, inv))) + z := + mul( + or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), + mul(sub(2, mul(d, inv)), inv) + ) + } + } + + /// @dev Calculates `floor(x * y / d)` with full precision, rounded up. + /// Throws if result overflows a uint256 or when `d` is zero. + /// Credit to Uniswap-v3-core under MIT license: + /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol + function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + z = fullMulDiv(x, y, d); + /// @solidity memory-safe-assembly + assembly { + if mulmod(x, y, d) { + z := add(z, 1) + if iszero(z) { + mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. + revert(0x1c, 0x04) + } + } + } + } + + /// @dev Calculates `floor(x * y / 2 ** n)` with full precision. + /// Throws if result overflows a uint256. + /// Credit to Philogy under MIT license: + /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol + function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // Temporarily use `z` as `p0` to save gas. + z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`. + for {} 1 {} { + if iszero(or(iszero(x), eq(div(z, x), y))) { + let k := and(n, 0xff) // `n`, cleaned. + let mm := mulmod(x, y, not(0)) + let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. + // | p1 | z | + // Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 | + // Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 | + // Check that final `z` doesn't overflow by checking that p1_0 = 0. + if iszero(shr(k, p1)) { + z := add(shl(sub(256, k), p1), shr(k, z)) + break + } + mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. + revert(0x1c, 0x04) + } + z := shr(and(n, 0xff), z) + break + } + } + } + + /// @dev Returns `floor(x * y / d)`. + /// Reverts if `x * y` overflows, or `d` is zero. + function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. + if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { + mstore(0x00, 0xad251c27) // `MulDivFailed()`. + revert(0x1c, 0x04) + } + z := div(z, d) + } + } + + /// @dev Returns `ceil(x * y / d)`. + /// Reverts if `x * y` overflows, or `d` is zero. + function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(x, y) + // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. + if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { + mstore(0x00, 0xad251c27) // `MulDivFailed()`. + revert(0x1c, 0x04) + } + z := add(iszero(iszero(mod(z, d))), div(z, d)) + } + } + + /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`. + function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) { + /// @solidity memory-safe-assembly + assembly { + let g := n + let r := mod(a, n) + for { let y := 1 } 1 {} { + let q := div(g, r) + let t := g + g := r + r := sub(t, mul(r, q)) + let u := x + x := y + y := sub(u, mul(y, q)) + if iszero(r) { break } + } + x := mul(eq(g, 1), add(x, mul(slt(x, 0), n))) + } + } + + /// @dev Returns `ceil(x / d)`. + /// Reverts if `d` is zero. + function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + if iszero(d) { + mstore(0x00, 0x65244e4e) // `DivFailed()`. + revert(0x1c, 0x04) + } + z := add(iszero(iszero(mod(x, d))), div(x, d)) + } + } + + /// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`. + function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(gt(x, y), sub(x, y)) + } + } + + /// @dev Returns `max(0, x - y)`. + function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(gt(x, y), sub(x, y)) + } + } + + /// @dev Returns `min(2 ** 256 - 1, x + y)`. + function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(sub(0, lt(add(x, y), x)), add(x, y)) + } + } + + /// @dev Returns `min(2 ** 256 - 1, x * y)`. + function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y)) + } + } + + /// @dev Returns `condition ? x : y`, without branching. + function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), iszero(condition))) + } + } + + /// @dev Returns `condition ? x : y`, without branching. + function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), iszero(condition))) + } + } + + /// @dev Returns `condition ? x : y`, without branching. + function ternary(bool condition, address x, address y) internal pure returns (address z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), iszero(condition))) + } + } + + /// @dev Returns `x != 0 ? x : y`, without branching. + function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(x, mul(y, iszero(x))) + } + } + + /// @dev Returns `x != bytes32(0) ? x : y`, without branching. + function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) { + /// @solidity memory-safe-assembly + assembly { + z := or(x, mul(y, iszero(x))) + } + } + + /// @dev Returns `x != address(0) ? x : y`, without branching. + function coalesce(address x, address y) internal pure returns (address z) { + /// @solidity memory-safe-assembly + assembly { + z := or(x, mul(y, iszero(shl(96, x)))) + } + } + + /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`. + /// Reverts if the computation overflows. + function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`. + if x { + z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x` + let half := shr(1, b) // Divide `b` by 2. + // Divide `y` by 2 every iteration. + for { y := shr(1, y) } y { y := shr(1, y) } { + let xx := mul(x, x) // Store x squared. + let xxRound := add(xx, half) // Round to the nearest number. + // Revert if `xx + half` overflowed, or if `x ** 2` overflows. + if or(lt(xxRound, xx), shr(128, x)) { + mstore(0x00, 0x49f7642b) // `RPowOverflow()`. + revert(0x1c, 0x04) + } + x := div(xxRound, b) // Set `x` to scaled `xxRound`. + // If `y` is odd: + if and(y, 1) { + let zx := mul(z, x) // Compute `z * x`. + let zxRound := add(zx, half) // Round to the nearest number. + // If `z * x` overflowed or `zx + half` overflowed: + if or(xor(div(zx, x), z), lt(zxRound, zx)) { + // Revert if `x` is non-zero. + if x { + mstore(0x00, 0x49f7642b) // `RPowOverflow()`. + revert(0x1c, 0x04) + } + } + z := div(zxRound, b) // Return properly scaled `zxRound`. + } + } + } + } + } + + /// @dev Returns the square root of `x`, rounded down. + function sqrt(uint256 x) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`. + z := 181 // The "correct" value is 1, but this saves a multiplication later. + + // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad + // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. + + // Let `y = x / 2**r`. We check `y >= 2**(k + 8)` + // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`. + let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffffff, shr(r, x)))) + z := shl(shr(1, r), z) + + // Goal was to get `z*z*y` within a small factor of `x`. More iterations could + // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`. + // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small. + // That's not possible if `x < 256` but we can just verify those cases exhaustively. + + // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`. + // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`. + // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps. + + // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)` + // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`, + // with largest error when `s = 1` and when `s = 256` or `1/256`. + + // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`. + // Then we can estimate `sqrt(y)` using + // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`. + + // There is no overflow risk here since `y < 2**136` after the first branch above. + z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181. + + // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + z := shr(1, add(z, div(x, z))) + + // If `x+1` is a perfect square, the Babylonian method cycles between + // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor. + // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division + z := sub(z, lt(div(x, z), z)) + } + } + + /// @dev Returns the cube root of `x`, rounded down. + /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license: + /// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy + /// Formally verified by xuwinnie: + /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf + function cbrt(uint256 x) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + // Makeshift lookup table to nudge the approximate log2 result. + z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3))) + // Newton-Raphson's. + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + z := div(add(add(div(x, mul(z, z)), z), z), 3) + // Round down. + z := sub(z, lt(div(x, mul(z, z)), z)) + } + } + + /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down. + function sqrtWad(uint256 x) internal pure returns (uint256 z) { + unchecked { + if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18); + z = (1 + sqrt(x)) * 10 ** 9; + z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1; + } + /// @solidity memory-safe-assembly + assembly { + z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down. + } + } + + /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down. + /// Formally verified by xuwinnie: + /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf + function cbrtWad(uint256 x) internal pure returns (uint256 z) { + unchecked { + if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36); + z = (1 + cbrt(x)) * 10 ** 12; + z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3; + } + /// @solidity memory-safe-assembly + assembly { + let p := x + for {} 1 {} { + if iszero(shr(229, p)) { + if iszero(shr(199, p)) { + p := mul(p, 100000000000000000) // 10 ** 17. + break + } + p := mul(p, 100000000) // 10 ** 8. + break + } + if iszero(shr(249, p)) { p := mul(p, 100) } + break + } + let t := mulmod(mul(z, z), z, p) + z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down. + } + } + + /// @dev Returns `sqrt(x * y)`. Also called the geometric mean. + function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) { + if (x == y) return x; + uint256 p = rawMul(x, y); + if (y == rawDiv(p, x)) return sqrt(p); + for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) { + if ((p = fullMulDivUnchecked(x, y, z)) >= z) break; + } + } + + /// @dev Returns the factorial of `x`. + function factorial(uint256 x) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := 1 + if iszero(lt(x, 58)) { + mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`. + revert(0x1c, 0x04) + } + for {} x { x := sub(x, 1) } { z := mul(z, x) } + } + } + + /// @dev Returns the log2 of `x`. + /// Equivalent to computing the index of the most significant bit (MSB) of `x`. + /// Returns 0 if `x` is zero. + function log2(uint256 x) internal pure returns (uint256 r) { + /// @solidity memory-safe-assembly + assembly { + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + // forgefmt: disable-next-item + r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), + 0x0706060506020504060203020504030106050205030304010505030400000000)) + } + } + + /// @dev Returns the log2 of `x`, rounded up. + /// Returns 0 if `x` is zero. + function log2Up(uint256 x) internal pure returns (uint256 r) { + r = log2(x); + /// @solidity memory-safe-assembly + assembly { + r := add(r, lt(shl(r, 1), x)) + } + } + + /// @dev Returns the log10 of `x`. + /// Returns 0 if `x` is zero. + function log10(uint256 x) internal pure returns (uint256 r) { + /// @solidity memory-safe-assembly + assembly { + if iszero(lt(x, 100000000000000000000000000000000000000)) { + x := div(x, 100000000000000000000000000000000000000) + r := 38 + } + if iszero(lt(x, 100000000000000000000)) { + x := div(x, 100000000000000000000) + r := add(r, 20) + } + if iszero(lt(x, 10000000000)) { + x := div(x, 10000000000) + r := add(r, 10) + } + if iszero(lt(x, 100000)) { + x := div(x, 100000) + r := add(r, 5) + } + r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999))))) + } + } + + /// @dev Returns the log10 of `x`, rounded up. + /// Returns 0 if `x` is zero. + function log10Up(uint256 x) internal pure returns (uint256 r) { + r = log10(x); + /// @solidity memory-safe-assembly + assembly { + r := add(r, lt(exp(10, r), x)) + } + } + + /// @dev Returns the log256 of `x`. + /// Returns 0 if `x` is zero. + function log256(uint256 x) internal pure returns (uint256 r) { + /// @solidity memory-safe-assembly + assembly { + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(shr(3, r), lt(0xff, shr(r, x))) + } + } + + /// @dev Returns the log256 of `x`, rounded up. + /// Returns 0 if `x` is zero. + function log256Up(uint256 x) internal pure returns (uint256 r) { + r = log256(x); + /// @solidity memory-safe-assembly + assembly { + r := add(r, lt(shl(shl(3, r), 1), x)) + } + } + + /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`. + /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent). + function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) { + /// @solidity memory-safe-assembly + assembly { + mantissa := x + if mantissa { + if iszero(mod(mantissa, 1000000000000000000000000000000000)) { + mantissa := div(mantissa, 1000000000000000000000000000000000) + exponent := 33 + } + if iszero(mod(mantissa, 10000000000000000000)) { + mantissa := div(mantissa, 10000000000000000000) + exponent := add(exponent, 19) + } + if iszero(mod(mantissa, 1000000000000)) { + mantissa := div(mantissa, 1000000000000) + exponent := add(exponent, 12) + } + if iszero(mod(mantissa, 1000000)) { + mantissa := div(mantissa, 1000000) + exponent := add(exponent, 6) + } + if iszero(mod(mantissa, 10000)) { + mantissa := div(mantissa, 10000) + exponent := add(exponent, 4) + } + if iszero(mod(mantissa, 100)) { + mantissa := div(mantissa, 100) + exponent := add(exponent, 2) + } + if iszero(mod(mantissa, 10)) { + mantissa := div(mantissa, 10) + exponent := add(exponent, 1) + } + } + } + } + + /// @dev Convenience function for packing `x` into a smaller number using `sci`. + /// The `mantissa` will be in bits [7..255] (the upper 249 bits). + /// The `exponent` will be in bits [0..6] (the lower 7 bits). + /// Use `SafeCastLib` to safely ensure that the `packed` number is small + /// enough to fit in the desired unsigned integer type: + /// ``` + /// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether)); + /// ``` + function packSci(uint256 x) internal pure returns (uint256 packed) { + (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`. + /// @solidity memory-safe-assembly + assembly { + if shr(249, x) { + mstore(0x00, 0xce30380c) // `MantissaOverflow()`. + revert(0x1c, 0x04) + } + packed := or(shl(7, x), packed) + } + } + + /// @dev Convenience function for unpacking a packed number from `packSci`. + function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) { + unchecked { + unpacked = (packed >> 7) * 10 ** (packed & 0x7f); + } + } + + /// @dev Returns the average of `x` and `y`. Rounds towards zero. + function avg(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = (x & y) + ((x ^ y) >> 1); + } + } + + /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity. + function avg(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = (x >> 1) + (y >> 1) + (x & y & 1); + } + } + + /// @dev Returns the absolute value of `x`. + function abs(int256 x) internal pure returns (uint256 z) { + unchecked { + z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255); + } + } + + /// @dev Returns the absolute distance between `x` and `y`. + function dist(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y)) + } + } + + /// @dev Returns the absolute distance between `x` and `y`. + function dist(int256 x, int256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y)) + } + } + + /// @dev Returns the minimum of `x` and `y`. + function min(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), lt(y, x))) + } + } + + /// @dev Returns the minimum of `x` and `y`. + function min(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), slt(y, x))) + } + } + + /// @dev Returns the maximum of `x` and `y`. + function max(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), gt(y, x))) + } + } + + /// @dev Returns the maximum of `x` and `y`. + function max(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, y), sgt(y, x))) + } + } + + /// @dev Returns `x`, bounded to `minValue` and `maxValue`. + function clamp(uint256 x, uint256 minValue, uint256 maxValue) + internal + pure + returns (uint256 z) + { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, minValue), gt(minValue, x))) + z := xor(z, mul(xor(z, maxValue), lt(maxValue, z))) + } + } + + /// @dev Returns `x`, bounded to `minValue` and `maxValue`. + function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := xor(x, mul(xor(x, minValue), sgt(minValue, x))) + z := xor(z, mul(xor(z, maxValue), slt(maxValue, z))) + } + } + + /// @dev Returns greatest common divisor of `x` and `y`. + function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + for { z := x } y {} { + let t := y + y := mod(z, y) + z := t + } + } + } + + /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`, + /// with `t` clamped between `begin` and `end` (inclusive). + /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). + /// If `begins == end`, returns `t <= begin ? a : b`. + function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end) + internal + pure + returns (uint256) + { + if (begin > end) (t, begin, end) = (~t, ~begin, ~end); + if (t <= begin) return a; + if (t >= end) return b; + unchecked { + if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin); + return a - fullMulDiv(a - b, t - begin, end - begin); + } + } + + /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`. + /// with `t` clamped between `begin` and `end` (inclusive). + /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). + /// If `begins == end`, returns `t <= begin ? a : b`. + function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end) + internal + pure + returns (int256) + { + if (begin > end) (t, begin, end) = (~t, ~begin, ~end); + if (t <= begin) return a; + if (t >= end) return b; + // forgefmt: disable-next-item + unchecked { + if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a), + uint256(t - begin), uint256(end - begin))); + return int256(uint256(a) - fullMulDiv(uint256(a - b), + uint256(t - begin), uint256(end - begin))); + } + } + + /// @dev Returns if `x` is an even number. Some people may need this. + function isEven(uint256 x) internal pure returns (bool) { + return x & uint256(1) == uint256(0); + } + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* RAW NUMBER OPERATIONS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Returns `x + y`, without checking for overflow. + function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = x + y; + } + } + + /// @dev Returns `x + y`, without checking for overflow. + function rawAdd(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = x + y; + } + } + + /// @dev Returns `x - y`, without checking for underflow. + function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = x - y; + } + } + + /// @dev Returns `x - y`, without checking for underflow. + function rawSub(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = x - y; + } + } + + /// @dev Returns `x * y`, without checking for overflow. + function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) { + unchecked { + z = x * y; + } + } + + /// @dev Returns `x * y`, without checking for overflow. + function rawMul(int256 x, int256 y) internal pure returns (int256 z) { + unchecked { + z = x * y; + } + } + + /// @dev Returns `x / y`, returning 0 if `y` is zero. + function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := div(x, y) + } + } + + /// @dev Returns `x / y`, returning 0 if `y` is zero. + function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := sdiv(x, y) + } + } + + /// @dev Returns `x % y`, returning 0 if `y` is zero. + function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mod(x, y) + } + } + + /// @dev Returns `x % y`, returning 0 if `y` is zero. + function rawSMod(int256 x, int256 y) internal pure returns (int256 z) { + /// @solidity memory-safe-assembly + assembly { + z := smod(x, y) + } + } + + /// @dev Returns `(x + y) % d`, return 0 if `d` if zero. + function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := addmod(x, y, d) + } + } + + /// @dev Returns `(x * y) % d`, return 0 if `d` if zero. + function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { + /// @solidity memory-safe-assembly + assembly { + z := mulmod(x, y, d) + } + } +} + diff --git a/main/lib/solady/src/utils/SSTORE2.sol b/main/lib/solady/src/utils/SSTORE2.sol new file mode 100644 index 0000000..46621f3 --- /dev/null +++ b/main/lib/solady/src/utils/SSTORE2.sol @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.4; + +/// @notice Read and write to persistent storage at a fraction of the cost. +/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SSTORE2.sol) +/// @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie) +/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol) +/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol) +/// @author Modified from SSTORE3 (https://github.com/Philogy/sstore3) +library SSTORE2 { + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* CONSTANTS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev The proxy initialization code. + uint256 private constant _CREATE3_PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3; + + /// @dev Hash of the `_CREATE3_PROXY_INITCODE`. + /// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`. + bytes32 internal constant CREATE3_PROXY_INITCODE_HASH = + 0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f; + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* CUSTOM ERRORS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Unable to deploy the storage contract. + error DeploymentFailed(); + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* WRITE LOGIC */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Writes `data` into the bytecode of a storage contract and returns its address. + function write(bytes memory data) internal returns (address pointer) { + /// @solidity memory-safe-assembly + assembly { + let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode. + /** + * ---------------------------------------------------+ + * Opcode | Mnemonic | Stack | Memory | + * ---------------------------------------------------| + * 61 l | PUSH2 l | l | | + * 80 | DUP1 | l l | | + * 60 0xa | PUSH1 0xa | 0xa l l | | + * 3D | RETURNDATASIZE | 0 0xa l l | | + * 39 | CODECOPY | l | [0..l): code | + * 3D | RETURNDATASIZE | 0 l | [0..l): code | + * F3 | RETURN | | [0..l): code | + * 00 | STOP | | | + * ---------------------------------------------------+ + * @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called. + * Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16. + */ + // Do a out-of-gas revert if `n + 1` is more than 2 bytes. + mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n))) + // Deploy a new contract with the generated creation code. + pointer := create(0, add(data, 0x15), add(n, 0xb)) + if iszero(pointer) { + mstore(0x00, 0x30116425) // `DeploymentFailed()`. + revert(0x1c, 0x04) + } + mstore(data, n) // Restore the length of `data`. + } + } + + /// @dev Writes `data` into the bytecode of a storage contract with `salt` + /// and returns its normal CREATE2 deterministic address. + function writeCounterfactual(bytes memory data, bytes32 salt) + internal + returns (address pointer) + { + /// @solidity memory-safe-assembly + assembly { + let n := mload(data) + // Do a out-of-gas revert if `n + 1` is more than 2 bytes. + mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n))) + // Deploy a new contract with the generated creation code. + pointer := create2(0, add(data, 0x15), add(n, 0xb), salt) + if iszero(pointer) { + mstore(0x00, 0x30116425) // `DeploymentFailed()`. + revert(0x1c, 0x04) + } + mstore(data, n) // Restore the length of `data`. + } + } + + /// @dev Writes `data` into the bytecode of a storage contract and returns its address. + /// This uses the so-called "CREATE3" workflow, + /// which means that `pointer` is agnostic to `data, and only depends on `salt`. + function writeDeterministic(bytes memory data, bytes32 salt) + internal + returns (address pointer) + { + /// @solidity memory-safe-assembly + assembly { + let n := mload(data) + mstore(0x00, _CREATE3_PROXY_INITCODE) // Store the `_PROXY_INITCODE`. + let proxy := create2(0, 0x10, 0x10, salt) + if iszero(proxy) { + mstore(0x00, 0x30116425) // `DeploymentFailed()`. + revert(0x1c, 0x04) + } + mstore(0x14, proxy) // Store the proxy's address. + // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01). + // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex). + mstore(0x00, 0xd694) + mstore8(0x34, 0x01) // Nonce of the proxy contract (1). + pointer := keccak256(0x1e, 0x17) + + // Do a out-of-gas revert if `n + 1` is more than 2 bytes. + mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n))) + if iszero( + mul( // The arguments of `mul` are evaluated last to first. + extcodesize(pointer), + call(gas(), proxy, 0, add(data, 0x15), add(n, 0xb), codesize(), 0x00) + ) + ) { + mstore(0x00, 0x30116425) // `DeploymentFailed()`. + revert(0x1c, 0x04) + } + mstore(data, n) // Restore the length of `data`. + } + } + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* ADDRESS CALCULATIONS */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Returns the initialization code hash of the storage contract for `data`. + /// Used for mining vanity addresses with create2crunch. + function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) { + /// @solidity memory-safe-assembly + assembly { + let n := mload(data) + // Do a out-of-gas revert if `n + 1` is more than 2 bytes. + returndatacopy(returndatasize(), returndatasize(), gt(n, 0xfffe)) + mstore(data, add(0x61000180600a3d393df300, shl(0x40, n))) + hash := keccak256(add(data, 0x15), add(n, 0xb)) + mstore(data, n) // Restore the length of `data`. + } + } + + /// @dev Equivalent to `predictCounterfactualAddress(data, salt, address(this))` + function predictCounterfactualAddress(bytes memory data, bytes32 salt) + internal + view + returns (address pointer) + { + pointer = predictCounterfactualAddress(data, salt, address(this)); + } + + /// @dev Returns the CREATE2 address of the storage contract for `data` + /// deployed with `salt` by `deployer`. + /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. + function predictCounterfactualAddress(bytes memory data, bytes32 salt, address deployer) + internal + pure + returns (address predicted) + { + bytes32 hash = initCodeHash(data); + /// @solidity memory-safe-assembly + assembly { + // Compute and store the bytecode hash. + mstore8(0x00, 0xff) // Write the prefix. + mstore(0x35, hash) + mstore(0x01, shl(96, deployer)) + mstore(0x15, salt) + predicted := keccak256(0x00, 0x55) + // Restore the part of the free memory pointer that has been overwritten. + mstore(0x35, 0) + } + } + + /// @dev Equivalent to `predictDeterministicAddress(salt, address(this))`. + function predictDeterministicAddress(bytes32 salt) internal view returns (address pointer) { + pointer = predictDeterministicAddress(salt, address(this)); + } + + /// @dev Returns the "CREATE3" deterministic address for `salt` with `deployer`. + function predictDeterministicAddress(bytes32 salt, address deployer) + internal + pure + returns (address pointer) + { + /// @solidity memory-safe-assembly + assembly { + let m := mload(0x40) // Cache the free memory pointer. + mstore(0x00, deployer) // Store `deployer`. + mstore8(0x0b, 0xff) // Store the prefix. + mstore(0x20, salt) // Store the salt. + mstore(0x40, CREATE3_PROXY_INITCODE_HASH) // Store the bytecode hash. + + mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address. + mstore(0x40, m) // Restore the free memory pointer. + // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01). + // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex). + mstore(0x00, 0xd694) + mstore8(0x34, 0x01) // Nonce of the proxy contract (1). + pointer := keccak256(0x1e, 0x17) + } + } + + /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ + /* READ LOGIC */ + /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ + + /// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`. + function read(address pointer) internal view returns (bytes memory data) { + /// @solidity memory-safe-assembly + assembly { + data := mload(0x40) + let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01)) + extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21)) + mstore(data, n) // Store the length. + mstore(0x40, add(n, add(data, 0x40))) // Allocate memory. + } + } + + /// @dev Equivalent to `read(pointer, start, 2 ** 256 - 1)`. + function read(address pointer, uint256 start) internal view returns (bytes memory data) { + /// @solidity memory-safe-assembly + assembly { + data := mload(0x40) + let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01)) + let l := sub(n, and(0xffffff, mul(lt(start, n), start))) + extcodecopy(pointer, add(data, 0x1f), start, add(l, 0x21)) + mstore(data, mul(sub(n, start), lt(start, n))) // Store the length. + mstore(0x40, add(data, add(0x40, mload(data)))) // Allocate memory. + } + } + + /// @dev Returns a slice of the data on `pointer` from `start` to `end`. + /// `start` and `end` will be clamped to the range `[0, args.length]`. + /// The `pointer` MUST be deployed via the SSTORE2 write functions. + /// Otherwise, the behavior is undefined. + /// Out-of-gas reverts if `pointer` does not have any code. + function read(address pointer, uint256 start, uint256 end) + internal + view + returns (bytes memory data) + { + /// @solidity memory-safe-assembly + assembly { + data := mload(0x40) + if iszero(lt(end, 0xffff)) { end := 0xffff } + let d := mul(sub(end, start), lt(start, end)) + extcodecopy(pointer, add(data, 0x1f), start, add(d, 0x01)) + if iszero(and(0xff, mload(add(data, d)))) { + let n := sub(extcodesize(pointer), 0x01) + returndatacopy(returndatasize(), returndatasize(), shr(40, n)) + d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) + } + mstore(data, d) // Store the length. + mstore(add(add(data, 0x20), d), 0) // Zeroize the slot after the bytes. + mstore(0x40, add(add(data, 0x40), d)) // Allocate memory. + } + } +} + diff --git a/main/src/WTFERC6909.sol b/main/src/WTFERC6909.sol new file mode 100644 index 0000000..4e2c5df --- /dev/null +++ b/main/src/WTFERC6909.sol @@ -0,0 +1,308 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +import {IERC6909, IERC6909Metadata, IERC6909TokenSupply} from "@openzeppelin/contracts/interfaces/IERC6909.sol"; +import {ERC165, IERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol"; + +/** + * @dev WTF's ERC6909TokenSupply implementation, modified from @openzeppelin implementation + * Changes are: + * - support names per token for token metadata (ERC6909Metadata) + * - support symbol per token for token metadata (ERC6909Metadata) + * - support ONE decimal for ALL tokens (ERC6909Metadata) + * - allow decimals to be constructed + * - block self-transfer by default + * - remove Context + */ +contract WTFERC6909 is ERC165, IERC6909, IERC6909Metadata, IERC6909TokenSupply { + struct TokenMetadata { + string name; + string symbol; + } + + mapping(address owner => mapping(uint256 id => uint256)) private _balances; + + mapping(address owner => mapping(address operator => bool)) private _operatorApprovals; + + mapping(address owner => mapping(address spender => mapping(uint256 id => uint256))) private _allowances; + + mapping(uint256 id => TokenMetadata) public _tokenMetadata; + + mapping(uint256 id => uint256) private _totalSupplies; + + uint8 public immutable _decimals; + + error ERC6909InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 id); + error ERC6909InsufficientAllowance(address spender, uint256 allowance, uint256 needed, uint256 id); + error ERC6909SelfTransfer(address sender); + error ERC6909InvalidApprover(address approver); + error ERC6909InvalidReceiver(address receiver); + error ERC6909InvalidSender(address sender); + error ERC6909InvalidSpender(address spender); + + event ERC6909TokenUpdated(uint256 indexed id, string newName, string newSymbol); + + constructor(uint8 decimals_) { + _decimals = decimals_; + } + + /*////////////////////////////////////////////////////////////// + ERC165 LOGIC + //////////////////////////////////////////////////////////////*/ + + /// @inheritdoc IERC165 + function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { + return interfaceId == type(IERC6909).interfaceId || interfaceId == type(IERC6909TokenSupply).interfaceId + || interfaceId == type(IERC6909Metadata).interfaceId || super.supportsInterface(interfaceId); + } + + /*////////////////////////////////////////////////////////////// + ERC6909 LOGIC + //////////////////////////////////////////////////////////////*/ + + /// @inheritdoc IERC6909 + function balanceOf(address owner, uint256 id) public view virtual override returns (uint256) { + return _balances[owner][id]; + } + + /// @inheritdoc IERC6909 + function allowance(address owner, address spender, uint256 id) public view virtual override returns (uint256) { + return _allowances[owner][spender][id]; + } + + /// @inheritdoc IERC6909 + function isOperator(address owner, address spender) public view virtual override returns (bool) { + return _operatorApprovals[owner][spender]; + } + + /// @inheritdoc IERC6909 + function approve(address spender, uint256 id, uint256 amount) public virtual override returns (bool) { + _approve(msg.sender, spender, id, amount); + return true; + } + + /// @inheritdoc IERC6909 + function setOperator(address spender, bool approved) public virtual override returns (bool) { + _setOperator(msg.sender, spender, approved); + return true; + } + + /// @inheritdoc IERC6909 + function transfer(address receiver, uint256 id, uint256 amount) public virtual override returns (bool) { + _transfer(msg.sender, receiver, id, amount); + return true; + } + + /// @inheritdoc IERC6909 + function transferFrom(address sender, address receiver, uint256 id, uint256 amount) + public + virtual + override + returns (bool) + { + address caller = msg.sender; + if (sender != caller && !isOperator(sender, caller)) { + _spendAllowance(sender, caller, id, amount); + } + _transfer(sender, receiver, id, amount); + return true; + } + + /*////////////////////////////////////////////////////////////// + ERC6909 METADATA + //////////////////////////////////////////////////////////////*/ + + /// @inheritdoc IERC6909Metadata + function name(uint256 id) external view virtual override returns (string memory) { + return _tokenMetadata[id].name; + } + + /// @inheritdoc IERC6909Metadata + function symbol(uint256 id) external view virtual override returns (string memory) { + return _tokenMetadata[id].symbol; + } + + /// @inheritdoc IERC6909Metadata + function decimals( + uint256 /*id*/ + ) + external + view + virtual + override + returns (uint8) + { + return _decimals; + } + + /*////////////////////////////////////////////////////////////// + ERC6909 TOKENSUPPLY + //////////////////////////////////////////////////////////////*/ + + /// @inheritdoc IERC6909TokenSupply + function totalSupply(uint256 id) public view virtual override returns (uint256) { + return _totalSupplies[id]; + } + + /*////////////////////////////////////////////////////////////// + INTERNAL LOGIC + //////////////////////////////////////////////////////////////*/ + + /** + * @dev Creates `amount` of token `id` and assigns them to `account`, by transferring it from address(0). + * Relies on the `_update` mechanism. + * + * Emits a {Transfer} event with `from` set to the zero address. + * + * NOTE: This function is not virtual, {_update} should be overridden instead. + */ + function _mint(address to, uint256 id, uint256 amount) internal { + if (to == address(0)) revert ERC6909InvalidReceiver(address(0)); + if (to == address(this)) revert ERC6909InvalidReceiver(address(this)); + + _update(address(0), to, id, amount); + } + + /** + * @dev Moves `amount` of token `id` from `from` to `to` without checking for approvals. This function verifies + * that neither the sender nor the receiver are address(0), which means it cannot mint or burn tokens. + * Relies on the `_update` mechanism. + * + * Emits a {Transfer} event. + * + * NOTE: This function is not virtual, {_update} should be overridden instead. + */ + function _transfer(address from, address to, uint256 id, uint256 amount) internal virtual { + if (from == address(0)) revert ERC6909InvalidSender(address(0)); + if (to == address(0)) revert ERC6909InvalidReceiver(address(0)); + if (from == to) revert ERC6909SelfTransfer(from); + if (to == address(this)) revert ERC6909InvalidReceiver(to); + + _update(from, to, id, amount); + } + + /** + * @dev Destroys a `amount` of token `id` from `account`. + * Relies on the `_update` mechanism. + * + * Emits a {Transfer} event with `to` set to the zero address. + * + * NOTE: This function is not virtual, {_update} should be overridden instead + */ + function _burn(address from, uint256 id, uint256 amount) internal { + if (from == address(0)) revert ERC6909InvalidSender(address(0)); + + _update(from, address(0), id, amount); + } + + /** + * @dev Transfers `amount` of token `id` from `from` to `to`, or alternatively mints (or burns) if `from` + * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding + * this function. + * + * Emits a {Transfer} event. + */ + function _update(address from, address to, uint256 id, uint256 amount) internal virtual { + address caller = msg.sender; + + if (from != address(0)) { + uint256 fromBalance = _balances[from][id]; + if (fromBalance < amount) { + revert ERC6909InsufficientBalance(from, fromBalance, amount, id); + } + unchecked { + // Underflow not possible: amount <= fromBalance. + _balances[from][id] = fromBalance - amount; + } + } + if (to != address(0)) { + _balances[to][id] += amount; + } + + if (from == address(0)) { + _totalSupplies[id] += amount; + } + if (to == address(0)) { + unchecked { + // amount <= _balances[from][id] <= _totalSupplies[id] + _totalSupplies[id] -= amount; + } + } + + emit Transfer(caller, from, to, id, amount); + } + + /** + * @dev Sets `amount` as the allowance of `spender` over the `owner`'s `id` tokens. + * + * This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain + * subsystems, etc. + * + * Emits an {Approval} event. + * + * Requirements: + * + * - `owner` cannot be the zero address. + * - `spender` cannot be the zero address. + */ + function _approve(address owner, address spender, uint256 id, uint256 amount) internal virtual { + if (owner == address(0)) revert ERC6909InvalidApprover(address(0)); + if (spender == address(0)) revert ERC6909InvalidSpender(address(0)); + + _allowances[owner][spender][id] = amount; + emit Approval(owner, spender, id, amount); + } + + /** + * @dev Approve `spender` to operate on all of `owner`'s tokens + * + * This internal function is equivalent to `setOperator`, and can be used to e.g. set automatic allowances for + * certain subsystems, etc. + * + * Emits an {OperatorSet} event. + * + * Requirements: + * + * - `owner` cannot be the zero address. + * - `spender` cannot be the zero address. + */ + function _setOperator(address owner, address spender, bool approved) internal virtual { + if (owner == address(0)) revert ERC6909InvalidApprover(address(0)); + if (spender == address(0)) revert ERC6909InvalidSpender(address(0)); + + _operatorApprovals[owner][spender] = approved; + emit OperatorSet(owner, spender, approved); + } + + /** + * @dev Updates `owner`'s allowance for `spender` based on spent `amount`. + * + * Does not update the allowance value in case of infinite allowance. + * Revert if not enough allowance is available. + * + * Does not emit an {Approval} event. + */ + function _spendAllowance(address owner, address spender, uint256 id, uint256 amount) internal virtual { + uint256 currentAllowance = allowance(owner, spender, id); + if (currentAllowance < type(uint256).max) { + if (currentAllowance < amount) revert ERC6909InsufficientAllowance(spender, currentAllowance, amount, id); + + unchecked { + _allowances[owner][spender][id] = currentAllowance - amount; + } + } + } + + /** + * @dev Sets the `name` and `symbol` for a given token of type `id`. + * + * Emits an {ERC6909TokenUpdated} event. + */ + function _setMetadata(uint256 id, string memory newName, string memory newSymbol) internal virtual { + _tokenMetadata[id].name = newName; + _tokenMetadata[id].symbol = newSymbol; + + emit ERC6909TokenUpdated(id, newName, newSymbol); + } +} + diff --git a/main/src/WTFMarketV2.sol b/main/src/WTFMarketV2.sol new file mode 100644 index 0000000..12fd338 --- /dev/null +++ b/main/src/WTFMarketV2.sol @@ -0,0 +1,762 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol"; +import {IWTFCurve} from "@wtf/src/interfaces/IWTFCurve.sol"; + +import {FixedPointMathLib} from "@solady/utils/FixedPointMathLib.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {TokenHelper} from "@wtf/lib/TokenHelper.sol"; +import {WTFERC6909} from "@wtf/src/WTFERC6909.sol"; +import {IERC6909Metadata} from "@openzeppelin/contracts/interfaces/IERC6909.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {IRegistry} from "@wtf/src/interfaces/IRegistry.sol"; +import {IWTFMarketV2} from "@wtf/src/interfaces/IWTFMarketV2.sol"; +import {HasFTEvents} from "@wtf/lib/Event.sol"; +import {Market, MarketState, MarketDeployParams} from "@wtf/lib/Market.sol"; +import {StringLib} from "@wtf/lib/StringLib.sol"; +import {WTFControllerV2} from "@wtf/src/controllerv2/WTFControllerV2.sol"; + +/** + * Key differences from WTFMarketV1: + * - seed() is batch + push-based: collateral is pre-transferred, no per-outcome loop + * - seed() uses curve's calSeedCost (no fees, no time premium) + * - seed() returns collateral consumed for precise accounting + * - _transfer allows factory to transfer OTs to markets (nested market seeding) + * - remove dataCallback + * + * Unchanged from V1: mint, redeem, claim, skim, readState, readMarketDeployParams + */ +contract WTFMarketV2 is WTFERC6909, IWTFMarketV2, TokenHelper, ReentrancyGuardTransient, HasFTEvents { + using FixedPointMathLib for uint256; + using Market for MarketState; + using StringLib for string; + using StringLib for StringLib.slice; + + string private constant OT_PREFIX = "OT"; + + struct MarketStorage { + uint256 totalMarketCap; + } + + MarketStorage internal _storage; + mapping(uint256 id => uint256 marketCap) internal _marketCaps; + + // WTF: graduation state + bool public isGraduated; + uint256 public redeemValue; // frozen redeem value at graduation, WTF_ONE scaled (collateral per OT) + uint256[] internal _graduationProbs; // prob_i = P_i / sum(P_j), WTF_ONE scaled + + // WTF: refund state + bool public isRefunded; + uint256 public refundValue; // frozen refund value, WTF_ONE scaled (collateral per OT) + + address public immutable registry; + address public immutable factory; + + // MARKET DEPLOY PARAMS + address public immutable collateral; + uint256 public immutable parentTokenId; + bytes32 public immutable questionId; + address public immutable curve; + uint128 public immutable timestampStart; + + constructor( + address _registry, + address _factory, + address _collateral, + uint256 _parentTokenId, + bytes32 _questionId, + address _curve, + uint128 _timestampStart + ) WTFERC6909(WTFMath.WTF_DECIMALS) { + if (_registry == address(0) || _factory == address(0) || _collateral == address(0) || _curve == address(0)) { + revert Errors.MarketZeroAddress(); + } + + registry = _registry; + factory = _factory; + + // MARKET DEPLOY PARAMS + collateral = _collateral; + parentTokenId = _parentTokenId; + questionId = _questionId; + curve = _curve; + timestampStart = _timestampStart; + } + + modifier onlyFactory() { + if (msg.sender != factory) revert Errors.MarketUnauthorizedAccess(msg.sender, factory); + _; + } + + modifier whenUnpaused() { + if (IRegistry(registry).isPaused()) revert Errors.MarketPaused(); + _; + } + + /** + * @notice Markets have to be seeded by the market creator. Seed can be done before market starts. + * Seed can only mint and all seeded OT goes to treasury. + * @dev seed transactions do not trigger callbacks + * @param dataSwap bytes data to be consumed by IWTFCurve of the market + */ + function seed(uint256[] calldata tokenIds, uint256[] calldata otAmounts, bytes calldata dataSwap) + external + nonReentrant + whenUnpaused + onlyFactory + returns (uint256 collateralSeed) + { + if (tokenIds.length != otAmounts.length) revert Errors.MarketArrayLengthsMismatch(); + if (tokenIds.length == 0) revert Errors.MarketNoTokenIdsToSeed(); + + // note: seeding before market starts is allowed, as markets require a seed + MarketState memory market = readState(); + _onlyMarketTradeable(market); + + (uint256[] memory collateralsIn, uint256[] memory collateralsToTreasury) = + IWTFCurve(curve).calSeedCostByOtDeltas(address(this), tokenIds, otAmounts, dataSwap); + if (collateralsIn.length != collateralsToTreasury.length) revert Errors.MarketArrayLengthsMismatch(); + + uint256 collateralToTreasuryTotal; + for (uint256 i = 0; i < tokenIds.length; ++i) { + uint256 tokenId = tokenIds[i]; + uint256 otAmount = otAmounts[i]; + if (otAmount == 0) continue; + + if (!Market.isValidTokenId(tokenId) || tokenId > Market.toTokenId(market.numOutcomes - 1)) { + revert Errors.MarketInvalidTokenId(tokenId); + } + + uint256 collateralToPool = collateralsIn[i] - collateralsToTreasury[i]; + _marketCaps[tokenId] += collateralToPool; + market.totalMarketCap += collateralToPool; + + collateralSeed += collateralsIn[i]; + collateralToTreasuryTotal += collateralsToTreasury[i]; + + _mint(market.treasury, tokenId, otAmount); + + emit MintSwapV2( + msg.sender, + market.treasury, + tokenId, + collateralsIn[i] - collateralsToTreasury[i], + otAmount, + collateralsToTreasury[i] + ); + } + + if (collateralSeed == 0) revert Errors.MarketZeroCostBasis(); + + _writeState(market); + + _transferOut(collateral, parentTokenId, market.treasury, collateralToTreasuryTotal); + + if (_selfBalance(collateral, parentTokenId) < _storage.totalMarketCap) { + revert Errors.MarketInsufficientSeedCollateral(); + } + } + + /** + * @notice Markets allow swapping collateral -> OT (called mint). Markets support mint exact OT. Exact collateral is supported elsewhere. + * @dev Steps: + * 1. External input validation + * 2. Calculate swap amount via IWTFCurve + * 3. Transfer collateral from msg.sender & fee to treasury + * 4. Mint to receiver + * @dev Revert if not started, has ended or resolved. + * @param dataSwap bytes data to be consumed by IWTFCurve of the market + * @return collateralIn amount of collateral required from msg.sender + */ + function mintCollateralToExactOt(address receiver, uint256 tokenId, uint256 otDeltaOut, bytes calldata dataSwap) + external + nonReentrant + whenUnpaused + returns (uint256 collateralIn) + { + WTFControllerV2 controller = WTFControllerV2(factory); + if (controller.isMarket(receiver)) revert Errors.MarketReceiverIsMarket(); + + MarketState memory market = readState(); + _onlyMarketTradeable(market); + if (block.timestamp < market.timestampStart) revert Errors.MarketNotStarted(); + + collateralIn = _mintCollateralToOt(market, tokenId, otDeltaOut, dataSwap, receiver); + } + + /** + * @notice Markets allow swapping OT -> collateral (called redeem). Markets support redeem exact OT. Exact collateral is supported elsewhere. + * @dev Steps: + * 1. External input validation + * 2. Calculate swap amount via IWTFCurve + * 3. Burn from receiver (get what is due) + * 4. Transfer to receiver & fee to treasury + * @dev Revert if not started, has ended or resolved. + * @param dataSwap bytes data to be consumed by IWTFCurve of the market + * @return collateralOut amount of collateral given to receiver + */ + function redeemExactOtToCollateral(address receiver, uint256 tokenId, uint256 otDeltaIn, bytes calldata dataSwap) + external + nonReentrant + whenUnpaused + returns (uint256 collateralOut) + { + WTFControllerV2 controller = WTFControllerV2(factory); + if (controller.isMarket(receiver)) revert Errors.MarketReceiverIsMarket(); + + MarketState memory market = readState(); + _onlyMarketTradeable(market); + if (block.timestamp < market.timestampStart) revert Errors.MarketNotStarted(); + + collateralOut = _redeemOtToCollateral(market, tokenId, otDeltaIn, dataSwap, receiver); + } + + /** + * @notice After the market's question is finalised, all holders can claim their payout by burning their OTs. + * Only the OT of the winning outcome has a non-zero payout. + * @notice In the event no one holds the winning OT (winners exist yet no one is a winner), payout goes to treasury to redistribute. THIS IS NOT A FEE. + * @dev payout per OT = total market cap (at finalisation) / winning OTs (at finalisation) + * @dev Revert if not finalised + * @return payout amount of payout for claiming OTs specified + */ + function claim(address receiver, uint256[] memory tokenIds, uint256[] memory otToBurn) + external + nonReentrant + whenUnpaused + returns (uint256) + { + MarketState memory market = readState(); + WTFControllerV2 controller = WTFControllerV2(factory); + if (!market.isFinalised) revert Errors.MarketNotFinalised(); + if (market.answer == 0) revert Errors.MarketNotResolved(); + if (market.answer >= (1 << market.numOutcomes)) revert Errors.MarketTooManyOutcomes(); + // WTF: claim only opens after the 24h dispute window + if (!controller.isClaimable(questionId)) revert Errors.MarketClaimWindowNotPassed(); + if (controller.isMarket(receiver)) revert Errors.MarketReceiverIsMarket(); + + // WTF: refund path - everyone is paid refundValue * holdings + if (isRefunded) { + return _claimRefunded(tokenIds, otToBurn, receiver); + } + + uint256 otSupplyWinning = _calWinningOtSupply(market); + // NOTE: excess is NOT A FEE. It is used to handle the edge case of no winning total supply (divide by 0), excess should be transferred to treasury for redistribution + (uint256 payout, uint256 excess) = _claim(market, otSupplyWinning, tokenIds, otToBurn, receiver); + + _writeState(market); + + // NOTE: excess is NOT A FEE. It is used to handle the edge case of no winning total supply (divide by 0), excess should be transferred to treasury for redistribution + _transferOut(collateral, parentTokenId, market.treasury, excess); + _transferOut(collateral, parentTokenId, receiver, payout); + + return payout; + } + + /** + * @notice WTF: refund claim - burn OTs of ANY outcome and receive refundValue per OT. + */ + function _claimRefunded(uint256[] memory tokenIds, uint256[] memory otToBurn, address receiver) + internal + returns (uint256 payout) + { + if (tokenIds.length != otToBurn.length) revert Errors.MarketArrayLengthsMismatch(); + if (tokenIds.length == 0) revert Errors.MarketNoClaim(); + + uint256 len = tokenIds.length; + for (uint256 i = 0; i < len; ++i) { + uint256 tokenId = tokenIds[i]; + uint256 otBurned = otToBurn[i]; + if (otBurned == 0) continue; + + uint256 payoutProportional = refundValue.fullMulDiv(otBurned, WTFMath.WTF_ONE); + payout += payoutProportional; + + _burn(msg.sender, tokenId, otBurned); + emit ClaimPayout(msg.sender, receiver, tokenId, otBurned, payoutProportional); + } + + _transferOut(collateral, parentTokenId, receiver, payout); + } + + /** + * @notice Removes excess collateral to match internally accounted totalMarketCap + * @dev Only support market's collateral token, skim any token has too many edge cases. + * @dev Does not interfere with other functions, note the `external` modifier + */ + function skim() external nonReentrant { + MarketState memory market = readState(); + uint256 excess = _selfBalance(collateral, parentTokenId) - market.totalMarketCap; + _transferOut(collateral, parentTokenId, market.treasury, excess); + } + + /** + * @notice WTF: graduate market when threshold is met, freezing curve trading. + * @dev Anyone (keeper/user) can call once thresholds are met. + * @return redeemValue_ frozen redeem value (WTF_ONE scaled) + */ + function graduate() external nonReentrant whenUnpaused returns (uint256 redeemValue_) { + return _graduateInternal(false); + } + + /** + * @notice WTF: admin can force-graduate any market at ANY time regardless of threshold. + */ + function forceGraduate() external nonReentrant whenUnpaused returns (uint256 redeemValue_) { + WTFControllerV2 controller = WTFControllerV2(factory); + if (!controller.isAdmin(msg.sender)) { + address creator = IRegistry(registry).getCreator(questionId); + revert Errors.MarketUnauthorizedAccess(msg.sender, creator); + } + return _graduateInternal(true); + } + + function _graduateInternal(bool force) internal returns (uint256 redeemValue_) { + MarketState memory market = readState(); + if (isGraduated) revert Errors.MarketAlreadyGraduated(); + _onlyMarketTradeable(market); + if (block.timestamp < market.timestampStart) revert Errors.MarketNotStarted(); + + uint256 totalSupplyTotal; + uint256 maxSupplySingle; + for (uint256 i = 0; i < market.numOutcomes; ++i) { + uint256 supplyI = totalSupply(Market.toTokenId(i)); + totalSupplyTotal += supplyI; + if (supplyI > maxSupplySingle) maxSupplySingle = supplyI; + } + + if (!force) { + (uint256 thresholdMcap, uint256 thresholdMaxSupply,,,) = IRegistry(registry).getMarketConfig(address(this)); + // graduation is disabled until admin sets at least one threshold + if (thresholdMcap == 0 && thresholdMaxSupply == 0) revert Errors.MarketGraduationThresholdNotMet(); + + // a threshold of 0 disables that trigger path; either active path meeting its threshold graduates + bool mcapMet = thresholdMcap != 0 && market.totalMarketCap >= thresholdMcap; + bool supplyMet = thresholdMaxSupply != 0 && maxSupplySingle >= thresholdMaxSupply; + if (!mcapMet && !supplyMet) { + revert Errors.MarketGraduationThresholdNotMet(); + } + } + if (totalSupplyTotal == 0) revert Errors.MarketZeroTotalSupply(); + + // normalize prob_i = P_i / sum(P_j); sum(prob) == 1 by construction + uint256 sumPrice; + uint256[] memory prices = new uint256[](market.numOutcomes); + for (uint256 i = 0; i < market.numOutcomes; ++i) { + prices[i] = IWTFCurve(curve).calMarginalPrice(address(this), Market.toTokenId(i)); + sumPrice += prices[i]; + } + if (sumPrice == 0) revert Errors.MarketZeroSumPrice(); + + _graduationProbs = new uint256[](market.numOutcomes); + for (uint256 i = 0; i < market.numOutcomes; ++i) { + _graduationProbs[i] = prices[i].fullMulDiv(WTFMath.WTF_ONE, sumPrice); + } + + // freeze redeemValue = totalMarketCap / totalSupply; curve is now permanently closed + redeemValue_ = market.totalMarketCap.fullMulDiv(WTFMath.WTF_ONE, totalSupplyTotal); + redeemValue = redeemValue_; + isGraduated = true; + + emit GraduateMarket(address(this), market.totalMarketCap, totalSupplyTotal, redeemValue_, _graduationProbs); + } + + /** + * @notice WTF: creator or admin can refund ALL holders within the 24h dispute window after finalise. + * @dev refundValue = poolBalance / totalSupply (equal split of the pool). claim then pays + * refundValue * holdings to every holder. Not "return each bet" - fees are already taken & OTs traded. + */ + function refund() external nonReentrant whenUnpaused { + MarketState memory market = readState(); + if (isRefunded) revert Errors.MarketAlreadyRefunded(); + if (!market.isFinalised) revert Errors.MarketNotFinalised(); + + WTFControllerV2 controller = WTFControllerV2(factory); + if (!controller.isMarketWithinDisputeWindow(address(this))) revert Errors.MarketRefundWindowPassed(); + + address creator = IRegistry(registry).getCreator(questionId); + if (msg.sender != creator && !controller.isAdmin(msg.sender)) { + revert Errors.MarketUnauthorizedAccess(msg.sender, creator); + } + + uint256 totalSupplyTotal; + for (uint256 i = 0; i < market.numOutcomes; ++i) { + totalSupplyTotal += totalSupply(Market.toTokenId(i)); + } + if (totalSupplyTotal == 0) revert Errors.MarketZeroTotalSupply(); + + refundValue = _selfBalance(collateral, parentTokenId).fullMulDiv(WTFMath.WTF_ONE, totalSupplyTotal); + isRefunded = true; + + emit MarketRefunded(address(this), refundValue); + } + + /** + * @notice WTF: CLOB opening prices after graduation, q_i = prob_i * redeemValue. 0 if not graduated. + */ + function clobOpenPrices() external view returns (uint256[] memory prices) { + if (!isGraduated) return new uint256[](0); + prices = new uint256[](_graduationProbs.length); + for (uint256 i = 0; i < _graduationProbs.length; ++i) { + prices[i] = _graduationProbs[i].fullMulDiv(redeemValue, WTFMath.WTF_ONE); + } + } + + /** + * @notice WTF: read prob_i snapshot at graduation. + */ + function graduationProbs(uint256 index) external view returns (uint256) { + return index < _graduationProbs.length ? _graduationProbs[index] : 0; + } + + /** + * @notice WTF: split each fee in real-time: creatorShare% to creator, rest to centralWallet (admin withdrawable). + * Falls back to treasury if centralWallet is not configured yet. + */ + function _splitFee(MarketState memory market, uint256 collateralToTreasury) internal { + if (collateralToTreasury == 0) return; + + address creator = IRegistry(registry).getCreator(questionId); + uint80 creatorShare = IRegistry(registry).getCreatorShare(); + address centralWallet = IRegistry(registry).getCentralWallet(); + if (centralWallet == address(0)) centralWallet = market.treasury; + + uint256 creatorShareAmount = collateralToTreasury.fullMulDiv(creatorShare, WTFMath.WTF_ONE); + uint256 platformAmount = collateralToTreasury - creatorShareAmount; + + if (creatorShareAmount > 0) { + _transferOut(collateral, parentTokenId, creator, creatorShareAmount); + } + if (platformAmount > 0) { + _transferOut(collateral, parentTokenId, centralWallet, platformAmount); + } + + emit FeeSplit(address(this), creator, creatorShareAmount, centralWallet, platformAmount); + } + + /** + * @dev caller is always the msg.sender + */ + function _mintCollateralToOt( + MarketState memory market, + uint256 tokenId, + uint256 otDeltaOut, + bytes memory dataSwap, + address receiver + ) internal returns (uint256) { + (uint256 collateralDeltaIn, uint256 collateralToTreasury) = + market.mintCollateralToOt(tokenId, otDeltaOut, dataSwap); + uint256 collateralToPool = collateralDeltaIn - collateralToTreasury; + _marketCaps[tokenId] += collateralToPool; + _writeState(market); + + _mint(receiver, tokenId, otDeltaOut); + + _transferIn(collateral, parentTokenId, msg.sender, collateralDeltaIn); + _splitFee(market, collateralToTreasury); + + emit MintSwapV2(msg.sender, receiver, tokenId, collateralToPool, otDeltaOut, collateralToTreasury); + + // final check: mint cost >= redeem value + (uint256 collateralRedeemUserValue, uint256 collateralRedeemFee) = + market.curve.calRedeemValueByOtDelta(market.market, tokenId, otDeltaOut, dataSwap); + if ((collateralRedeemUserValue + collateralRedeemFee) > (collateralDeltaIn - collateralToTreasury)) { + revert Errors.MarketSwapPriceInvalidated(collateralDeltaIn, otDeltaOut); + } + + return collateralDeltaIn; + } + + /** + * @dev caller is always the msg.sender + */ + function _redeemOtToCollateral( + MarketState memory market, + uint256 tokenId, + uint256 otDeltaIn, + bytes memory dataSwap, + address receiver + ) internal returns (uint256) { + (uint256 collateralToReceiver, uint256 collateralToTreasury) = + market.redeemOtToCollateral(tokenId, otDeltaIn, dataSwap); + uint256 collateralFromPool = collateralToReceiver + collateralToTreasury; + + _marketCaps[tokenId] -= collateralFromPool; + _writeState(market); + + _burn(msg.sender, tokenId, otDeltaIn); + + _transferOut(collateral, parentTokenId, receiver, collateralToReceiver); + _splitFee(market, collateralToTreasury); + + emit RedeemSwapV2(msg.sender, receiver, tokenId, collateralFromPool, otDeltaIn, collateralToTreasury); + + // final check: mint cost >= redeem value + (uint256 collateralMintCost, uint256 collateralMintFee) = + market.curve.calMintCostByOtDelta(market.market, tokenId, otDeltaIn, dataSwap); + if ((collateralMintCost - collateralMintFee) < (collateralFromPool)) { + revert Errors.MarketSwapPriceInvalidated((collateralFromPool), otDeltaIn); + } + + return collateralToReceiver; + } + + function _calWinningOtSupply(MarketState memory market) internal view returns (uint256 otSupplyWinning) { + for (uint256 i = 0; i < market.numOutcomes; ++i) { + uint256 tokenId = Market.toTokenId(i); + if (Market.isWinner(market.answer, tokenId)) { + otSupplyWinning += totalSupply(tokenId); + } + } + } + + /** + * @dev There's ~2 ways to calculate claims: + * 1. On first claim, calculate the payoutPerOt once based on initial state and cache it. Then use it for every claim. This creates DUST and is stateful. + * 2. On every claim, calculate the payoutPerOt based on total market cap and remaining winning OT. Then use it for that claim. This create NO DUST and is stateless + * 3. You can try a hybrid of 1 & 2 (e.g caching the winning OTs and dynamically computing payoutPerOt). This adds more lines of code (liability). + * + * Option 1 vs 2 is primarily a matter of dust & statefulness. Option 2 is chosen to avoid accumulated dust (e.g 1million of 1 wei OT claims is not dust anymore) + * I am aware that in the extreme worst case scenario we can have up to 255 different outcomes, and all of them can be winners, making the gas cost very expensive to recompute for every claim due to the number of SLOADs. + * Outside of the code, it is however, indeed weird to create a prediction event where every outcome is correct. + * + * @dev event emission here is finicky at best, primarily as the backend stops working if the events are not a per-token-ledger-based whilst being 100% precise (hahaha) + * However, claiming onchain uses a batch claim to reduce the number of round downs for the user. + * To solve this, events for each winning claimed OT has a proportional payout except the last winning claimed OT which has the remainder of payout. + * + * @dev caller is always the msg.sender + * + */ + function _claim( + MarketState memory market, + uint256 otSupplyWinning, + uint256[] memory tokenIds, + uint256[] memory otToBurn, + address receiver + ) internal returns (uint256 payout, uint256 excess) { + // 1. calculate claim + uint256 otUserWinning; + (payout, excess, otUserWinning) = market.claim(tokenIds, otToBurn, otSupplyWinning); + + // 2a. find last winning OT index -> last winning claim has payout of remainder + uint256 len = tokenIds.length; + uint256 idxLastWinningOt = type(uint256).max; + for (uint256 i = len; i > 0; --i) { + uint256 idx = i - 1; + uint256 tokenId = tokenIds[idx]; + uint256 otBurned = otToBurn[idx]; + if (otBurned != 0 && Market.isWinner(market.answer, tokenId)) { + idxLastWinningOt = idx; + break; + } + } + + // 2b. emit event for each OT claimed + // 3. burn all non-zero claims + uint256 payoutRemaining = payout; + for (uint256 i = 0; i < len; ++i) { + uint256 tokenId = tokenIds[i]; + uint256 otBurned = otToBurn[i]; + if (otBurned == 0) { + continue; // user is not claiming => don't create a false positive event + } + + _burn(msg.sender, tokenId, otBurned); + if (Market.isWinner(market.answer, tokenId)) { + uint256 payoutProportional; + if (i != idxLastWinningOt) { + payoutProportional = payout.fullMulDiv(otBurned, otUserWinning); + payoutRemaining -= payoutProportional; + } else { + payoutProportional = payoutRemaining; + payoutRemaining = 0; + } + emit ClaimPayout(msg.sender, receiver, tokenId, otBurned, payoutProportional); + } else { + emit ClaimPayout(msg.sender, receiver, tokenId, otBurned, 0); + } + } + } + + /** + * @notice Read function to simulate the payout given an answer. Especially useful before market end + * @param answerSim answer to be simulated + * @param otUserWinning amount of winning OT to claim for payout calculation + */ + function simPayout(uint256 answerSim, uint256 otUserWinning) external view returns (uint256 payout) { + if (isRefunded) { + return refundValue.fullMulDiv(otUserWinning, WTFMath.WTF_ONE); + } + MarketState memory market = readState(); + market.answer = answerSim; + uint256 otSupplyWinning = _calWinningOtSupply(market); + return otSupplyWinning > 0 ? market.totalMarketCap.fullMulDiv(otUserWinning, otSupplyWinning) : 0; + } + + /** + * @notice Read total pool of funds in the market (aka totalMarketCap) + */ + function totalMarketCap() external view returns (uint256) { + return _storage.totalMarketCap; + } + + /** + * @notice Read pool of funds per outcome, calculated via cumulative mints - cumulative redeems per outcome + * + * @dev before finalisation, there's a lot of ways to define market cap: + * 1. marginal_price(tokenId) * total_supply(tokenId) - most canonical way but can be done via a lens contract + * 2. (CHOSEN) cumulative net amount - sum of mints minus sum of redeems + * 3. "area under curve" - finnicky as not all curves have a definitive & static area under curve + * 4. risk exposure - cost basis of all OT holders which is best suited offchain (3 & 4 is not the same) + * + * @dev after finalisation, the marketcap of the token can be defined as: payoutPerOt * otSupply + */ + function marketCap(uint256 tokenId) external view returns (uint256) { + MarketState memory market = readState(); + if (market.isFinalised) { + if (!Market.isWinner(market.answer, tokenId)) return 0; + + uint256 otSupplyWinning = _calWinningOtSupply(market); + if (otSupplyWinning == 0) return 0; + + return market.totalMarketCap.fullMulDiv(totalSupply(tokenId), otSupplyWinning); + } else { + return _marketCaps[tokenId]; + } + } + + /** + * @notice Read total supplies of all OTs in the market + */ + function totalSupplies() external view returns (uint256[] memory supplies) { + uint256 numOutcomes = IRegistry(registry).getNumOutcomes(questionId); + supplies = new uint256[](numOutcomes); + for (uint256 i = 0; i < numOutcomes; i++) { + supplies[i] = totalSupply(Market.toTokenId(i)); + } + } + + /** + * @notice used for market versioning or market logic differentiation + */ + function marketType() external pure returns (string memory) { + return "WTF_V2"; + } + + /** + * @notice helper function to get decimals of collateral + */ + function collateralDecimals() external view returns (uint8 decimals) { + return _collateralDecimals(collateral, parentTokenId); + } + + /** + * @notice read all storage values (externally & internally) into memory for gas-efficiency & data encapsulation + */ + function readState() public view returns (MarketState memory market) { + // immutable + market.market = address(this); + market.curve = IWTFCurve(curve); + market.timestampStart = timestampStart; + + // mutable, market related + market.totalMarketCap = _storage.totalMarketCap; + + // mutable, question related + (address treasury,/*feeRate*/, uint256 numOutcomes, uint128 timestampEnd, uint256 answer, bool isFinalised) = + IRegistry(registry).getConfig(address(this)); + market.treasury = treasury; + market.numOutcomes = numOutcomes; + market.timestampEnd = timestampEnd; + market.answer = answer; + market.isFinalised = isFinalised; + } + + /** + * @notice write memory into internal storage (external must be an explicit external call) + */ + function _writeState(MarketState memory market) internal { + _storage.totalMarketCap = market.totalMarketCap; + } + + /** + * @notice read immutable deploy parameters used to create market + */ + function readMarketDeployParams() external view returns (MarketDeployParams memory) { + return MarketDeployParams({ + collateral: collateral, + parentTokenId: parentTokenId, + questionId: questionId, + curve: address(curve), + timestampStart: timestampStart + }); + } + + /** + * @notice naming convention: OT . Nested collaterals will have OT prefix stripped for better readability + * @dev naming does not change, feel free to cache it offchain + * @inheritdoc IERC6909Metadata + */ + function name(uint256 tokenId) external view override(WTFERC6909, IERC6909Metadata) returns (string memory) { + string[] memory names = IRegistry(registry).getOutcomeNames(questionId); + if (!Market.isValidTokenId(tokenId) || tokenId > Market.toTokenId(names.length - 1)) { + revert Errors.MarketInvalidTokenId(tokenId); + } + string memory nameOutcome = names[Market.fromTokenId(tokenId)]; + string memory nameCollateral = _stripOTPrefix(_collateralName(collateral, parentTokenId)); + return _concat(OT_PREFIX, nameOutcome, nameCollateral, " "); + } + + /** + * @notice naming convention: OT--. Nested collaterals will have OT prefix stripped for better readability + * @dev naming does not change, feel free to cache it offchain + * @inheritdoc IERC6909Metadata + */ + function symbol(uint256 tokenId) external view override(WTFERC6909, IERC6909Metadata) returns (string memory) { + string[] memory names = IRegistry(registry).getOutcomeNames(questionId); + if (!Market.isValidTokenId(tokenId) || tokenId > Market.toTokenId(names.length - 1)) { + revert Errors.MarketInvalidTokenId(tokenId); + } + string memory nameOutcome = names[Market.fromTokenId(tokenId)]; + string memory nameCollateral = _stripOTPrefix(_collateralSymbol(collateral, parentTokenId)); + return _concat(OT_PREFIX, nameOutcome, nameCollateral, "-"); + } + + function _concat(string memory p, string memory o, string memory c, string memory d) + private + pure + returns (string memory) + { + return string(abi.encodePacked(p, d, o, d, c)); + } + + function _stripOTPrefix(string memory _str) private pure returns (string memory) { + StringLib.slice memory str = _str.toSlice(); + StringLib.slice memory otWithSpace = string.concat(OT_PREFIX, " ").toSlice(); + StringLib.slice memory otWithDash = string.concat(OT_PREFIX, "-").toSlice(); + return str.beyond(otWithSpace).beyond(otWithDash).toString(); + } + + function _onlyMarketTradeable(MarketState memory market) internal view { + if (market.timestampEnd <= block.timestamp) revert Errors.MarketEnded(); + if (market.answer != 0 || market.isFinalised) revert Errors.MarketResolved(); + // WTF: graduation or refund permanently closes the curve + if (isGraduated || isRefunded) revert Errors.MarketGraduated(); + } + + /** + * @dev this function is slightly different from WTFMarket as we need to add another check for the factory contract + */ + function _transfer(address from, address to, uint256 id, uint256 amount) internal override { + // block all OT transfers into a market EXCEPT: + // 1. market to market transfers (i.e market collateral is OT) + // 2. factory to market transfers (i.e during seed) + WTFControllerV2 controller = WTFControllerV2(factory); + if (controller.isMarket(to) && !controller.isMarket(msg.sender) && msg.sender != factory) { + revert Errors.MarketReceiverIsMarket(); + } + super._transfer(from, to, id, amount); + } +} + diff --git a/main/src/controllerv2/ControllerStorage.sol b/main/src/controllerv2/ControllerStorage.sol new file mode 100644 index 0000000..5cb5822 --- /dev/null +++ b/main/src/controllerv2/ControllerStorage.sol @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; +import {SlotDerivation} from "@openzeppelin/contracts/utils/SlotDerivation.sol"; + +struct QuestionParams { + uint96 timestampEnd; + string title; + bytes ancillaryData; + string imageUri; + string[] outcomeNames; + string[] outcomeImageUris; +} + +struct MarketParams { + uint256 parentTokenId; + address collateral; + address curve; + uint96 timestampStart; + uint80 feeRate; // creator-chosen fee rate, clamped by MINIMUM_FEE_RATE / MAXIMUM_FEE_RATE (hard constants) + uint8 tierId; // optional preset tier for graduation thresholds & dispute window +} + +struct QuestionStateV2 { + address creator; // immutable + uint96 timestampEnd; + + address oracle; // immutable + uint96 timestampFinalise; + + uint256 answer; + + uint96 timestampFlagExpiry; + + string title; // immutable + string imageUri; + string[] outcomeNames; + string[] outcomeImageUris; +} + +struct AncillaryDataUpdate { + uint256 timestamp; + bytes update; +} + +struct OutcomeNameDeduplicator { + mapping(string => bool) dedup; +} + +struct FeeRateOverride { + uint80 feeRate; + bool isOverride; +} + +struct CollateralConfig { + uint256 collateralSeedMin; + bool isWhitelisted; +} + +struct MarketTierConfig { + uint256 thresholdMcap; + uint256 thresholdMaxSupply; + uint256 disputeWindow; + bool isCustom; // true if this tier/override is actively configured +} + +/// @custom:storage-location erc7201:wtf.storage.Governance +struct GovernanceStorage { + address treasury; + uint80 feeRateDefault; + bool paused; + + mapping(address market => FeeRateOverride feeRateOverride) marketToOverride; + mapping(address collateral => CollateralConfig config) whitelistedCollaterals; + mapping(address curve => bool allowed) whitelistedCurves; + + // WTF: creator fee split & central wallet + uint80 creatorShare; // share of each fee given back to the market creator, scaled by WTF_ONE + address centralWallet; // platform portion of fees is swept here, withdrawable by admin + + // WTF: graduation thresholds (admin-settable default/fallback) + uint256 thresholdMcap; // graduate when totalMarketCap >= thresholdMcap + uint256 thresholdMaxSupply; // or when max(s_i) >= thresholdMaxSupply + + // WTF: dispute window after finalise (admin-settable, seconds). Within it, admin may + // overrideFinalise or creator/admin may refund; claim opens only after it passes. + uint256 disputeWindow; + + // WTF: Tier configurations (0 = Micro/PvP, 1 = Standard/Community, 2 = Flagship/Macro, etc.) + mapping(uint8 tierId => MarketTierConfig tierConfig) tiers; + // WTF: Market-specific tier binding and custom overrides + mapping(address market => uint8 tierId) marketTier; + mapping(address market => MarketTierConfig marketCustomConfig) marketOverrides; +} + +/// @custom:storage-location erc7201:wtf.storage.Registry +struct RegistryStorage { + EnumerableSet.AddressSet markets; + + mapping(bytes32 questionId => QuestionStateV2 state) questions; + mapping(bytes32 questionId => OutcomeNameDeduplicator deduplicator) outcomeDeduplicators; + + mapping(bytes32 updateId => AncillaryDataUpdate[] updatesPerId) updates; // updateId = keccak256(questionId,owner) +} + +library ControllerStorage { + function governance() internal pure returns (GovernanceStorage storage $) { + bytes32 slot = SlotDerivation.erc7201Slot("wtf.storage.Governance"); + assembly { + $.slot := slot + } + } + + function registry() internal pure returns (RegistryStorage storage $) { + bytes32 slot = SlotDerivation.erc7201Slot("wtf.storage.Registry"); + assembly { + $.slot := slot + } + } +} + diff --git a/main/src/controllerv2/Governance.sol b/main/src/controllerv2/Governance.sol new file mode 100644 index 0000000..e88c8ea --- /dev/null +++ b/main/src/controllerv2/Governance.sol @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import {HasFTEvents} from "@wtf/lib/Event.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import { + ControllerStorage, + GovernanceStorage, + FeeRateOverride, + CollateralConfig, + MarketTierConfig +} from "@wtf/src/controllerv2/ControllerStorage.sol"; + +abstract contract Governance is Initializable, HasFTEvents { + // WTF: fee rate bounds are hard-coded constants, NOT admin-settable. + // Creators pick feeRate within [MINIMUM_FEE_RATE, MAXIMUM_FEE_RATE] at market creation. + uint80 internal constant MAXIMUM_FEE_RATE = uint80(WTFMath.WTF_ONE * 3 / 100); // 3% + uint80 internal constant MINIMUM_FEE_RATE = uint80(WTFMath.WTF_ONE / 1000); // 0.1% + + function __Governance_init(address treasury_, uint80 feeRateDefault_) internal onlyInitializing { + __Governance_init_unchained(treasury_, feeRateDefault_); + } + + function __Governance_init_unchained(address treasury_, uint80 feeRateDefault_) internal onlyInitializing { + _setTreasury(treasury_); + _setFeeRateDefault(feeRateDefault_); + } + + function _setTreasury(address treasury) internal { + if (treasury == address(0) || treasury == address(this)) revert Errors.RegistryInvalidTreasuryAddress(); + + GovernanceStorage storage $ = ControllerStorage.governance(); + $.treasury = treasury; + + emit SetTreasury(treasury); + } + + function _setFeeRateDefault(uint80 feeRateNew) internal { + if (feeRateNew > MAXIMUM_FEE_RATE || feeRateNew < MINIMUM_FEE_RATE) { + if (feeRateNew > MAXIMUM_FEE_RATE) revert Errors.RegistryFeeRateTooHigh(); + revert Errors.RegistryFeeRateTooLow(); + } + + GovernanceStorage storage $ = ControllerStorage.governance(); + $.feeRateDefault = feeRateNew; + + emit SetProtocolFeeRate(feeRateNew); + } + + function _setFeeRateOverride(address market, uint80 feeRate, bool isOverride) internal { + if (isOverride && (feeRate > MAXIMUM_FEE_RATE || feeRate < MINIMUM_FEE_RATE)) { + if (feeRate > MAXIMUM_FEE_RATE) revert Errors.RegistryFeeRateTooHigh(); + revert Errors.RegistryFeeRateTooLow(); + } + + GovernanceStorage storage $ = ControllerStorage.governance(); + FeeRateOverride storage feeRateOverride = $.marketToOverride[market]; + + feeRateOverride.feeRate = isOverride ? feeRate : 0; + feeRateOverride.isOverride = isOverride; + + emit SetProtocolFeeOverride(market, isOverride ? feeRate : 0, isOverride); + } + + function _setCreatorShare(uint80 creatorShareNew) internal { + if (creatorShareNew > WTFMath.WTF_ONE) revert Errors.RegistryInvalidCreatorShare(); + + GovernanceStorage storage $ = ControllerStorage.governance(); + $.creatorShare = creatorShareNew; + + emit SetCreatorShare(creatorShareNew); + } + + function _setCentralWallet(address centralWalletNew) internal { + if (centralWalletNew == address(0) || centralWalletNew == address(this)) { + revert Errors.RegistryInvalidCentralWallet(); + } + + GovernanceStorage storage $ = ControllerStorage.governance(); + $.centralWallet = centralWalletNew; + + emit SetCentralWallet(centralWalletNew); + } + + function _setGraduationThresholds(uint256 thresholdMcapNew, uint256 thresholdMaxSupplyNew) internal { + GovernanceStorage storage $ = ControllerStorage.governance(); + $.thresholdMcap = thresholdMcapNew; + $.thresholdMaxSupply = thresholdMaxSupplyNew; + + emit SetGraduationThresholds(thresholdMcapNew, thresholdMaxSupplyNew); + } + + // WTF: dispute window after finalise (admin-settable). 0 is rejected: it would bypass the + // dispute period entirely (finalise -> instantly claimable) and gut the refund safety valve. + function _setDisputeWindow(uint256 disputeWindowNew) internal { + if (disputeWindowNew == 0) revert Errors.RegistryInvalidDisputeWindow(); + + GovernanceStorage storage $ = ControllerStorage.governance(); + $.disputeWindow = disputeWindowNew; + + emit SetDisputeWindow(disputeWindowNew); + } + + function _setMarketTier(uint8 tierId, uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow) internal { + if (disputeWindow == 0) revert Errors.RegistryInvalidDisputeWindow(); + + GovernanceStorage storage $ = ControllerStorage.governance(); + MarketTierConfig storage config = $.tiers[tierId]; + config.thresholdMcap = thresholdMcap; + config.thresholdMaxSupply = thresholdMaxSupply; + config.disputeWindow = disputeWindow; + config.isCustom = true; + + emit SetMarketTier(tierId, thresholdMcap, thresholdMaxSupply, disputeWindow); + } + + function _setMarketTierBinding(address market, uint8 tierId) internal { + GovernanceStorage storage $ = ControllerStorage.governance(); + $.marketTier[market] = tierId; + + emit SetMarketTierBinding(market, tierId); + } + + function _setMarketConfigOverride( + address market, + uint256 thresholdMcap, + uint256 thresholdMaxSupply, + uint256 disputeWindow, + bool isCustom + ) internal { + if (isCustom && disputeWindow == 0) revert Errors.RegistryInvalidDisputeWindow(); + + GovernanceStorage storage $ = ControllerStorage.governance(); + MarketTierConfig storage overrideConfig = $.marketOverrides[market]; + overrideConfig.thresholdMcap = isCustom ? thresholdMcap : 0; + overrideConfig.thresholdMaxSupply = isCustom ? thresholdMaxSupply : 0; + overrideConfig.disputeWindow = isCustom ? disputeWindow : 0; + overrideConfig.isCustom = isCustom; + + emit SetMarketConfigOverride(market, overrideConfig.thresholdMcap, overrideConfig.thresholdMaxSupply, overrideConfig.disputeWindow, isCustom); + } + + function _getMarketConfig(address market) + internal + view + returns (uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, uint8 tierId, bool isCustom) + { + GovernanceStorage storage $ = ControllerStorage.governance(); + MarketTierConfig storage overrideConfig = $.marketOverrides[market]; + if (overrideConfig.isCustom) { + return ( + overrideConfig.thresholdMcap, + overrideConfig.thresholdMaxSupply, + overrideConfig.disputeWindow, + $.marketTier[market], + true + ); + } + + tierId = $.marketTier[market]; + MarketTierConfig storage tierConfig = $.tiers[tierId]; + if (tierConfig.isCustom) { + return ( + tierConfig.thresholdMcap, + tierConfig.thresholdMaxSupply, + tierConfig.disputeWindow, + tierId, + false + ); + } + + return ( + $.thresholdMcap, + $.thresholdMaxSupply, + $.disputeWindow == 0 ? 1 days : $.disputeWindow, + tierId, + false + ); + } + + function _setWhitelistedCollateral(address collateral, bool whitelist, uint256 collateralSeedMin) internal { + // note: collateralSeedMin of 0 disables the check (any non-zero seed is accepted), + // but a non-trivial seed is still recommend to prevent deadlocks in the market + + GovernanceStorage storage $ = ControllerStorage.governance(); + CollateralConfig storage config = $.whitelistedCollaterals[collateral]; + if (whitelist) { + config.isWhitelisted = whitelist; + config.collateralSeedMin = collateralSeedMin; + } else { + config.isWhitelisted = whitelist; + config.collateralSeedMin = 0; // reset + } + + emit CollateralWhitelist(collateral, config.isWhitelisted, config.collateralSeedMin); + } + + function _setWhitelistedCurve(address curve, bool whitelist) internal { + if (curve == address(0)) revert Errors.RegistryInvalidCurve(); + + GovernanceStorage storage $ = ControllerStorage.governance(); + $.whitelistedCurves[curve] = whitelist; + emit CurveWhitelist(curve, whitelist); + } + + function _pause() internal { + GovernanceStorage storage $ = ControllerStorage.governance(); + $.paused = true; + + emit Paused(msg.sender); + } + + function _unpause() internal { + GovernanceStorage storage $ = ControllerStorage.governance(); + $.paused = false; + + emit Unpaused(msg.sender); + } + + // TODO: cosndier pause for market creation and question creation only? + + function _getFeeRate(address market) internal view returns (uint80) { + GovernanceStorage storage $ = ControllerStorage.governance(); + FeeRateOverride storage feeRateOverride = $.marketToOverride[market]; + + if (feeRateOverride.isOverride) { + return feeRateOverride.feeRate; + } else { + return $.feeRateDefault; + } + } + + function _getCreatorShare() internal view returns (uint80) { + return ControllerStorage.governance().creatorShare; + } + + function _getCentralWallet() internal view returns (address) { + return ControllerStorage.governance().centralWallet; + } + + function _getGraduationThresholds() internal view returns (uint256 thresholdMcap, uint256 thresholdMaxSupply) { + GovernanceStorage storage $ = ControllerStorage.governance(); + thresholdMcap = $.thresholdMcap; + thresholdMaxSupply = $.thresholdMaxSupply; + } + + function _getDisputeWindow() internal view returns (uint256) { + return ControllerStorage.governance().disputeWindow; + } +} + diff --git a/main/src/controllerv2/MarketFactory.sol b/main/src/controllerv2/MarketFactory.sol new file mode 100644 index 0000000..4ca45a8 --- /dev/null +++ b/main/src/controllerv2/MarketFactory.sol @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; +import {SSTORE2} from "@solady/utils/SSTORE2.sol"; + +import {HasFTEvents} from "@wtf/lib/Event.sol"; +import {TokenHelper} from "@wtf/lib/TokenHelper.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {Market, MarketDeployParams} from "@wtf/lib/Market.sol"; +import {QuestionV2} from "@wtf/lib/QuestionV2.sol"; +import {IWTFMarket} from "@wtf/src/interfaces/IWTFMarket.sol"; +import {IWTFCurve} from "@wtf/src/interfaces/IWTFCurve.sol"; +import {WTFMarketV2} from "@wtf/src/WTFMarketV2.sol"; +import { + ControllerStorage, + GovernanceStorage, + QuestionStateV2, + RegistryStorage +} from "@wtf/src/controllerv2/ControllerStorage.sol"; + +abstract contract MarketFactory is Initializable, HasFTEvents, TokenHelper { + using EnumerableSet for EnumerableSet.AddressSet; + using QuestionV2 for QuestionStateV2; + using WTFMath for uint256; + + bytes private constant EMPTY_BYTES = ""; + + address public immutable WTFMARKET_INIT_CODE_STORE; + uint256 private constant MIN_PARENT_OT_SEED = WTFMath.WTF_ONE; + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + WTFMARKET_INIT_CODE_STORE = SSTORE2.write(type(WTFMarketV2).creationCode); + } + + function _deployMarket( + address collateral, + uint256 parentTokenId, + bytes32 questionId, + address curve, + uint128 startBy + ) internal returns (address) { + GovernanceStorage storage gov = ControllerStorage.governance(); + RegistryStorage storage reg = ControllerStorage.registry(); + + if (collateral == address(0)) revert Errors.FactoryInvalidCollateral(); + if (curve == address(0)) revert Errors.FactoryInvalidCurve(); + if (!gov.whitelistedCurves[curve]) revert Errors.FactoryCurveNotAllowed(); + if (parentTokenId != NULL_PARENT_ID) { + // validate 6909 as WTFMarket + if (!reg.markets.contains(collateral)) revert Errors.Registry6909MustBeRegisteredMarket(); + if (!Market.isValidTokenId(parentTokenId)) revert Errors.RegistryInvalidTokenIdAsCollateral(); + + uint256 numOutcomes = reg.questions[IWTFMarket(collateral).questionId()].getNumOutcomes(); + uint256 parentTokenIdMax = Market.toTokenId(numOutcomes - 1); + if (parentTokenId > parentTokenIdMax) revert Errors.RegistryTokenIdNotCreatedForMarket(); + } + + uint96 timestampEnd = reg.questions[questionId].timestampEnd; + uint128 timestampStart = WTFMath.max128(startBy, block.timestamp.toUint128()); + if (uint128(timestampEnd) <= timestampStart) revert Errors.RegistryInvalidTimestamp(); + + MarketDeployParams memory params = MarketDeployParams({ + collateral: collateral, + parentTokenId: parentTokenId, + questionId: questionId, + curve: curve, + timestampStart: timestampStart + }); + address market = _create2(params); + if (market == address(0)) revert Errors.RegistryMarketDeploymentFailed(); + + reg.markets.add(market); + + return market; + } + + function _seedLiquidity( + address market, + address collateral, + uint256 parentTokenId, + address curve, + uint256[] memory tokenIds, + uint256[] memory otAmounts + ) internal returns (uint256 collateralTotal) { + // note: calSeedCostByOtDeltas can be state-modifying, and assertion that market address != controller address may not always hold + (bool ok, bytes memory ret) = + curve.staticcall(abi.encodeCall(IWTFCurve.calSeedCostByOtDeltas, (market, tokenIds, otAmounts, EMPTY_BYTES))); + if (!ok) revert Errors.FactorySeedCallFailed(); + (uint256[] memory collateralsIn,) = abi.decode(ret, (uint256[], uint256[])); + + uint256 len = collateralsIn.length; + for (uint256 i = 0; i < len; ++i) { + collateralTotal += collateralsIn[i]; + } + + // note: collateral must be transferred before calling seed + _transferFrom(collateral, parentTokenId, msg.sender, market, collateralTotal); + uint256 collateralSeed = WTFMarketV2(market).seed(tokenIds, otAmounts, EMPTY_BYTES); + + if (collateralSeed != collateralTotal) revert Errors.FactorySeedCostMismatch(); + } + + function _create2(MarketDeployParams memory params) private returns (address newMarket) { + bytes32 salt = _getSalt(params); + bytes memory creationCode = _getCreationCodeWithArgs(params); + assembly ("memory-safe") { + newMarket := create2(0, add(creationCode, 0x20), mload(creationCode), salt) + } + } + + function _getSalt(MarketDeployParams memory params) internal view returns (bytes32) { + return keccak256( + abi.encode( + params.collateral, + params.parentTokenId, + params.questionId, + params.curve, + params.timestampStart, + block.chainid + ) + ); + } + + function _getCreationCodeWithArgs(MarketDeployParams memory params) internal view returns (bytes memory) { + return abi.encodePacked( + SSTORE2.read(WTFMARKET_INIT_CODE_STORE), + abi.encode( + address(this), // note: assumption that this is registry (upgradeability can break) + address(this), // factory + params.collateral, + params.parentTokenId, + params.questionId, + params.curve, + params.timestampStart + ) + ); + } + + function _computeCounterfactual(MarketDeployParams memory params) internal view returns (address) { + bytes32 salt = _getSalt(params); + bytes memory creationCode = _getCreationCodeWithArgs(params); + + bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(creationCode))); + + return address(uint160(uint256(hash))); + } +} + diff --git a/main/src/controllerv2/Registry.sol b/main/src/controllerv2/Registry.sol new file mode 100644 index 0000000..48f3798 --- /dev/null +++ b/main/src/controllerv2/Registry.sol @@ -0,0 +1,250 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {HasFTEvents} from "@wtf/lib/Event.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {QuestionV2} from "@wtf/lib/QuestionV2.sol"; +import { + ControllerStorage, + QuestionStateV2, + AncillaryDataUpdate, + RegistryStorage, + OutcomeNameDeduplicator, + QuestionParams, + GovernanceStorage +} from "@wtf/src/controllerv2/ControllerStorage.sol"; + +library Registry { + uint256 private constant MAX_UPDATE_LENGTH = 30000; + + using QuestionV2 for QuestionStateV2; + + function createQuestion(QuestionParams calldata params, address oracle, address creator) + public + returns (bytes32 questionId) + { + if (oracle == address(0)) revert Errors.RegistryInvalidOracleAddress(); + questionId = QuestionV2.getId(creator, oracle, params.title, params.ancillaryData); + + _registerQuestion(questionId, params, oracle, creator); + _emitQuestionCreated(questionId, params, oracle, creator); + postUpdate(questionId, params.ancillaryData); + } + + function _registerQuestion(bytes32 questionId, QuestionParams calldata params, address oracle, address creator) + private + { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage state = reg.questions[questionId]; + + state.register( + reg.outcomeDeduplicators[questionId], + creator, + oracle, + params.timestampEnd, + params.title, + params.imageUri, + params.outcomeNames, + params.outcomeImageUris + ); + } + + function _emitQuestionCreated(bytes32 questionId, QuestionParams calldata params, address oracle, address creator) + private + { + emit HasFTEvents.CreateNewQuestionV2( + questionId, + oracle, + creator, + params.title, + params.imageUri, + params.timestampEnd, + params.outcomeNames, + params.outcomeImageUris, + params.ancillaryData + ); + emit HasFTEvents.ModifyEnd(questionId, 0, params.timestampEnd); + + emit HasFTEvents.QuestionImageUpdated(questionId, params.imageUri); + uint256 len = params.outcomeNames.length; + for (uint256 i = 0; i < len; ++i) { + emit HasFTEvents.AddOutcome(questionId, i, params.outcomeNames[i]); + emit HasFTEvents.OutcomeImageUpdated(questionId, i, params.outcomeImageUris[i]); + } + } + + function addOutcomes(bytes32 questionId, string[] calldata outcomeNames, string[] calldata outcomeImageUris) + public + { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + OutcomeNameDeduplicator storage dedup = reg.outcomeDeduplicators[questionId]; + + uint256 numOutcomesPrev = question.getNumOutcomes(); + question.addOutcomes(dedup, outcomeNames, outcomeImageUris); + uint256 numOutcomesNew = question.getNumOutcomes(); + + // numOutcomes start from 1, index start from 0 + for (uint256 i = numOutcomesPrev; i < numOutcomesNew; ++i) { + emit HasFTEvents.AddOutcome(questionId, i, question.outcomeNames[i]); + emit HasFTEvents.OutcomeImageUpdated(questionId, i, question.outcomeImageUris[i]); + } + } + + function modifyEnd(bytes32 questionId, uint96 timestampEndNew) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + if (!question.isRegistered()) revert Errors.RegistryQuestionNotFound(); + + uint96 prev = question.timestampEnd; + question.modifyEnd(timestampEndNew); + + emit HasFTEvents.ModifyEnd(questionId, prev, timestampEndNew); + } + + function resolveOutcome(bytes32 questionId, uint256 answer) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + + uint256 answerPrev = question.answer; + question.resolve(answer); + + emit HasFTEvents.Resolve(questionId, answerPrev, question.answer); + } + + function unresolveOutcome(bytes32 questionId) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + + uint256 answerPrev = question.answer; + question.unresolve(); + + emit HasFTEvents.Resolve(questionId, answerPrev, question.answer); + } + + function finaliseOutcome(bytes32 questionId, uint256 answerChallenge) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + if (!question.isRegistered()) revert Errors.RegistryQuestionNotFound(); + + question.finalise(answerChallenge); + + emit HasFTEvents.Finalise(questionId, answerChallenge); + } + + /** + * WTF: admin overrides a finalised answer within the 24h dispute window. + */ + function overrideFinaliseOutcome(bytes32 questionId, uint256 answerOverride) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + if (!question.isRegistered()) revert Errors.RegistryQuestionNotFound(); + + uint256 answerPrev = question.answer; + question.overrideFinalise(answerOverride, ControllerStorage.governance().disputeWindow); + + emit HasFTEvents.Resolve(questionId, answerPrev, question.answer); + emit HasFTEvents.OverrideFinalise(questionId, answerPrev, question.answer); + } + + function flag(bytes32 questionId) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + + question.flag(); + + emit HasFTEvents.QuestionFlagged(questionId, question.timestampFlagExpiry); + } + + function unflag(bytes32 questionId) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + + question.unflag(); + + emit HasFTEvents.QuestionUnflagged(questionId); + } + + function finaliseManually(bytes32 questionId, uint256 answerOverride) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + + uint256 answerPrev = question.answer; + question.manuallyFinalise(answerOverride); + + // treat manual finalise as a re-resolution even if the answer is the same + emit HasFTEvents.Resolve(questionId, answerPrev, answerOverride); + emit HasFTEvents.Finalise(questionId, answerOverride); + emit HasFTEvents.ManuallyFinalise(questionId, answerOverride); + } + + function setImageUri(bytes32 questionId, string calldata imageUri) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + if (!question.isRegistered()) revert Errors.RegistryQuestionNotFound(); + + question.imageUri = imageUri; + + emit HasFTEvents.QuestionImageUpdated(questionId, imageUri); + } + + function setOutcomeImageUri(bytes32 questionId, uint256 indexOutcome, string calldata imageUri) public { + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + if (!question.isRegistered()) revert Errors.RegistryQuestionNotFound(); + if (indexOutcome >= question.outcomeImageUris.length) revert Errors.RegistryInvalidNumOutcomes(); + + question.outcomeImageUris[indexOutcome] = imageUri; + emit HasFTEvents.OutcomeImageUpdated(questionId, indexOutcome, imageUri); + } + + function postUpdate(bytes32 questionId, bytes memory update) public { + if (update.length > MAX_UPDATE_LENGTH) revert Errors.RegistryExceedMaxAncillaryDataUpdateLength(); + + RegistryStorage storage reg = ControllerStorage.registry(); + if (!reg.questions[questionId].isRegistered()) revert Errors.RegistryQuestionNotFound(); + + bytes32 id = QuestionV2.getUpdateId(questionId, msg.sender); + reg.updates[id].push(AncillaryDataUpdate({timestamp: block.timestamp, update: update})); + + emit HasFTEvents.AncillaryDataUpdated(questionId, msg.sender, update); + } + + function getUpdates(bytes32 questionId, address owner) public view returns (AncillaryDataUpdate[] memory) { + RegistryStorage storage reg = ControllerStorage.registry(); + bytes32 id = QuestionV2.getUpdateId(questionId, owner); + return reg.updates[id]; + } + + function getLatestUpdate(bytes32 questionId, address owner) public view returns (AncillaryDataUpdate memory) { + RegistryStorage storage reg = ControllerStorage.registry(); + bytes32 id = QuestionV2.getUpdateId(questionId, owner); + AncillaryDataUpdate[] storage updatesOwner = reg.updates[id]; + if (updatesOwner.length == 0) return AncillaryDataUpdate({timestamp: 0, update: ""}); + return updatesOwner[updatesOwner.length - 1]; + } + + function getUpdatesPaginated(bytes32 questionId, address owner, uint256 offset, uint256 limit) + public + view + returns (AncillaryDataUpdate[] memory page) + { + RegistryStorage storage reg = ControllerStorage.registry(); + bytes32 id = QuestionV2.getUpdateId(questionId, owner); + + AncillaryDataUpdate[] storage updatesOwner = reg.updates[id]; + uint256 total = updatesOwner.length; + if (offset >= total) return new AncillaryDataUpdate[](0); + + uint256 from = offset; + uint256 to = from + limit; + if (to > total) to = total; + uint256 len = to - from; + + page = new AncillaryDataUpdate[](len); + for (uint256 i = 0; i < len; ++i) { + page[i] = updatesOwner[from + i]; + } + } +} + diff --git a/main/src/controllerv2/WTFControllerV2.sol b/main/src/controllerv2/WTFControllerV2.sol new file mode 100644 index 0000000..8021438 --- /dev/null +++ b/main/src/controllerv2/WTFControllerV2.sol @@ -0,0 +1,556 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import { + AccessControlDefaultAdminRulesUpgradeable +} from "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol"; +import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol"; + +import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; + +import {IWTFControllerV2} from "@wtf/src/interfaces/IWTFControllerV2.sol"; +import {IRegistry} from "@wtf/src/interfaces/IRegistry.sol"; +import {IWTFMarket} from "@wtf/src/interfaces/IWTFMarket.sol"; + +import {QuestionV2} from "@wtf/lib/QuestionV2.sol"; +import {Market, MarketDeployParams} from "@wtf/lib/Market.sol"; +import {Errors} from "@wtf/lib/Errors.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; + +import { + ControllerStorage, + QuestionStateV2, + AncillaryDataUpdate, + GovernanceStorage, + RegistryStorage, + CollateralConfig, + QuestionParams, + MarketParams, + MarketTierConfig +} from "@wtf/src/controllerv2/ControllerStorage.sol"; +import {Governance} from "@wtf/src/controllerv2/Governance.sol"; +import {Registry} from "@wtf/src/controllerv2/Registry.sol"; +import {MarketFactory} from "@wtf/src/controllerv2/MarketFactory.sol"; + +contract WTFControllerV2 is + Initializable, + AccessControlDefaultAdminRulesUpgradeable, + ReentrancyGuardTransient, + Governance, + MarketFactory, + IWTFControllerV2, + IRegistry +{ + using EnumerableSet for EnumerableSet.AddressSet; + using QuestionV2 for QuestionStateV2; + using WTFMath for uint256; + + bytes32 private constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); + bytes32 private constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); + bytes32 private constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); + + bytes private constant EMPTY_BYTES = ""; + + modifier whenUnpaused() { + if (_isPaused()) revert Errors.RegistryPaused(); + _; + } + + modifier onlyCreator(bytes32 questionId) { + _onlyCreator(questionId, msg.sender); + _; + } + + modifier onlyOracle(bytes32 questionId) { + _onlyOracle(questionId, msg.sender); + _; + } + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + _disableInitializers(); + } + + function initialize(address admin_, address treasury_, uint80 feeRateDefault_, uint48 adminTransferDelay_) + external + initializer + { + __AccessControlDefaultAdminRules_init(adminTransferDelay_, admin_); + __Governance_init(treasury_, feeRateDefault_); + // WTF: default values for admin-settable params - admin can change later via setters. + _setCreatorShare(uint80(WTFMath.WTF_ONE / 2)); // 50% of fees go back to the creator + _setCentralWallet(admin_); // central wallet == admin (admin private key can withdraw) + // Graduation thresholds (defaults, collateral units = 1e18; 100k pool cap / 1M OT max supply). + // A market with a smaller cap (e.g. 1k-10k) will never graduate with these defaults - tune before launch. + _setGraduationThresholds(100_000 * 10 ** 18, 1_000_000 * 10 ** 18); + // Dispute window after finalise (default 24h) - admin-settable via setDisputeWindow. + _setDisputeWindow(1 days); + } + + function deployMarket( + QuestionParams calldata paramsQuestion, + MarketParams calldata paramsMarket, + address oracle, + uint256 otSeed + ) external whenUnpaused nonReentrant returns (bytes32 questionId, address market) { + GovernanceStorage storage gov = ControllerStorage.governance(); + + // WTF: feeRate is chosen by the creator at creation and frozen. Bounds are hard constants. + if (paramsMarket.feeRate > MAXIMUM_FEE_RATE || paramsMarket.feeRate < MINIMUM_FEE_RATE) { + if (paramsMarket.feeRate > MAXIMUM_FEE_RATE) revert Errors.FactoryFeeRateExceedMaximumLimit(); + revert Errors.RegistryFeeRateTooLow(); + } + if (otSeed == 0) revert Errors.FactoryInvalidSeedAmount(); + if (paramsMarket.curve == address(0)) revert Errors.FactoryInvalidCurve(); + if (!gov.whitelistedCurves[paramsMarket.curve]) revert Errors.FactoryCurveNotAllowed(); + if (paramsMarket.collateral == address(0)) revert Errors.FactoryNativeTokenNotAllowed(); + if (paramsMarket.parentTokenId == NULL_PARENT_ID) { + if (!gov.whitelistedCollaterals[paramsMarket.collateral].isWhitelisted) { + revert Errors.RegistryCollateralNotWhitelisted(); + } + } + + uint256 numOutcomes; + (questionId, numOutcomes) = _ensureQuestionCreated(paramsQuestion, oracle); + + market = _deployMarket( + paramsMarket.collateral, + paramsMarket.parentTokenId, + questionId, + paramsMarket.curve, + paramsMarket.timestampStart + ); + // WTF: freeze the creator-chosen feeRate on this market before seeding (curve reads it via getConfig) + _setFeeRateOverride(market, paramsMarket.feeRate, true); + if (paramsMarket.tierId != 0) { + _setMarketTierBinding(market, paramsMarket.tierId); + } + emit CreateNewMarket( + market, + paramsMarket.collateral, + paramsMarket.parentTokenId, + questionId, + paramsMarket.curve, + IWTFMarket(market).timestampStart() + ); + + _seed(market, paramsMarket, numOutcomes, otSeed); + } + + function seedLiquidity(address market, uint256[] calldata tokenIds, uint256[] calldata otAmounts) + external + whenUnpaused + nonReentrant + { + RegistryStorage storage reg = ControllerStorage.registry(); + if (!reg.markets.contains(market)) revert Errors.RegistryMarketNotFound(); + + MarketDeployParams memory params = IWTFMarket(market).readMarketDeployParams(); + _onlyCreator(params.questionId, msg.sender); + QuestionStateV2 storage question = reg.questions[params.questionId]; + if (question.answer != 0 || question.isFinalised()) revert Errors.MarketResolved(); + + _seedLiquidity(market, params.collateral, params.parentTokenId, params.curve, tokenIds, otAmounts); + } + + function postUpdate(bytes32 questionId, bytes calldata update) external { + Registry.postUpdate(questionId, update); + } + + function addOutcomes(bytes32 questionId, string[] calldata names, string[] calldata imageUris) + external + nonReentrant + onlyCreator(questionId) + { + Registry.addOutcomes(questionId, names, imageUris); + } + + function modifyTimestampEnd(bytes32 questionId, uint128 timestampEndNew) + external + nonReentrant + onlyCreator(questionId) + { + Registry.modifyEnd(questionId, WTFMath.toUint96(uint256(timestampEndNew))); + } + + function setImageUri(bytes32 questionId, string calldata imageUri) external nonReentrant onlyCreator(questionId) { + Registry.setImageUri(questionId, imageUri); + } + + function setOutcomeImageUri(bytes32 questionId, uint256 indexOutcome, string calldata imageUri) + external + nonReentrant + onlyCreator(questionId) + { + Registry.setOutcomeImageUri(questionId, indexOutcome, imageUri); + } + + // WTF: pure creator settlement - the creator resolves & finalises with their private key + function resolveOutcome(bytes32 questionId, uint256 answer) external nonReentrant onlyCreator(questionId) { + Registry.resolveOutcome(questionId, answer); + } + + function unresolveOutcome(bytes32 questionId) external nonReentrant onlyCreator(questionId) { + Registry.unresolveOutcome(questionId); + } + + function finaliseOutcome(bytes32 questionId, uint256 answerChallenge) external nonReentrant onlyCreator(questionId) { + Registry.finaliseOutcome(questionId, answerChallenge); + } + + /** + * @notice WTF: admin can directly halt trading and settle any market at ANY time with an answer. + * Bypasses creator requirement, resolve + finalise atomically in one call. + */ + function adminSettle(bytes32 questionId, uint256 answer) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { + Registry.resolveOutcome(questionId, answer); + Registry.finaliseOutcome(questionId, answer); + } + + /** + * WTF: admin may override the finalised answer within the 24h dispute window. + */ + function overrideFinalise(bytes32 questionId, uint256 answer) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { + Registry.overrideFinaliseOutcome(questionId, answer); + } + + // WTF: admin-settable parameters + function setCreatorShare(uint80 creatorShareNew) external onlyRole(DEFAULT_ADMIN_ROLE) { + _setCreatorShare(creatorShareNew); + } + + function setCentralWallet(address centralWalletNew) external onlyRole(DEFAULT_ADMIN_ROLE) { + _setCentralWallet(centralWalletNew); + } + + function setGraduationThresholds(uint256 thresholdMcapNew, uint256 thresholdMaxSupplyNew) + external + onlyRole(DEFAULT_ADMIN_ROLE) + { + _setGraduationThresholds(thresholdMcapNew, thresholdMaxSupplyNew); + } + + // WTF: combined setter to configure both thresholds and dispute window in a single transaction + function setThresholdsAndWindow(uint256 thresholdMcapNew, uint256 thresholdMaxSupplyNew, uint256 disputeWindowNew) + external + onlyRole(DEFAULT_ADMIN_ROLE) + { + _setGraduationThresholds(thresholdMcapNew, thresholdMaxSupplyNew); + _setDisputeWindow(disputeWindowNew); + } + + // WTF: dispute window after finalise (seconds) - admin-settable, 0 rejected. + function setDisputeWindow(uint256 disputeWindowNew) external onlyRole(DEFAULT_ADMIN_ROLE) { + _setDisputeWindow(disputeWindowNew); + } + + function setMarketTier(uint8 tierId, uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow) + external + onlyRole(DEFAULT_ADMIN_ROLE) + { + _setMarketTier(tierId, thresholdMcap, thresholdMaxSupply, disputeWindow); + } + + function setMarketTierBinding(address market, uint8 tierId) external onlyRole(DEFAULT_ADMIN_ROLE) { + _setMarketTierBinding(market, tierId); + } + + function setMarketConfigOverride( + address market, + uint256 thresholdMcap, + uint256 thresholdMaxSupply, + uint256 disputeWindow, + bool isCustom + ) external onlyRole(DEFAULT_ADMIN_ROLE) { + _setMarketConfigOverride(market, thresholdMcap, thresholdMaxSupply, disputeWindow, isCustom); + } + + function getMarketConfig(address market) + external + view + override(IWTFControllerV2, IRegistry) + returns (uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, uint8 tierId, bool isCustom) + { + return _getMarketConfig(market); + } + + function getMarketTier(uint8 tierId) + external + view + override(IWTFControllerV2, IRegistry) + returns (uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, bool isCustom) + { + GovernanceStorage storage $ = ControllerStorage.governance(); + MarketTierConfig storage config = $.tiers[tierId]; + return (config.thresholdMcap, config.thresholdMaxSupply, config.disputeWindow, config.isCustom); + } + + function flag(bytes32 questionId) external nonReentrant onlyRole(OPERATOR_ROLE) { + Registry.flag(questionId); + } + + function unflag(bytes32 questionId) external nonReentrant onlyRole(OPERATOR_ROLE) { + Registry.unflag(questionId); + } + + function finaliseManually(bytes32 questionId, uint256 answer) external nonReentrant onlyRole(OPERATOR_ROLE) { + Registry.finaliseManually(questionId, answer); + } + + function setWhitelistedCurve(address curve, bool whitelist) external onlyRole(OPERATOR_ROLE) { + _setWhitelistedCurve(curve, whitelist); + } + + function setFeeRateOverride(address market, uint80 feeRate, bool isOverride) external onlyRole(OPERATOR_ROLE) { + _setFeeRateOverride(market, feeRate, isOverride); + } + + function setTreasury(address treasury_) external onlyRole(DEFAULT_ADMIN_ROLE) { + _setTreasury(treasury_); + } + + function setFeeRateDefault(uint80 feeRateNew) external onlyRole(DEFAULT_ADMIN_ROLE) { + _setFeeRateDefault(feeRateNew); + } + + function setWhitelistedCollateral(address collateral, bool whitelist, uint256 collateralSeedMin) + external + onlyRole(DEFAULT_ADMIN_ROLE) + { + _setWhitelistedCollateral(collateral, whitelist, collateralSeedMin); + } + + function unpause() external onlyRole(UNPAUSER_ROLE) { + _unpause(); + } + + function pause() external onlyRole(GUARDIAN_ROLE) { + _pause(); + } + + function isPaused() external view returns (bool) { + return _isPaused(); + } + + function isMarket(address market) external view returns (bool) { + return ControllerStorage.registry().markets.contains(market); + } + + function getDefaultFeeRate() external view returns (uint80) { + return ControllerStorage.governance().feeRateDefault; + } + + function getFeeRate(address market) external view returns (uint80) { + return _getFeeRate(market); + } + + function getNumOutcomes(bytes32 questionId) external view returns (uint256) { + return ControllerStorage.registry().questions[questionId].getNumOutcomes(); + } + + function getOutcomeEnd(bytes32 questionId) external view returns (uint128) { + return ControllerStorage.registry().questions[questionId].timestampEnd; + } + + function isFinalised(bytes32 questionId) external view returns (bool) { + return ControllerStorage.registry().questions[questionId].isFinalised(); + } + + function getOutcomeAnswer(bytes32 questionId) external view returns (uint256) { + return ControllerStorage.registry().questions[questionId].answer; + } + + function getOutcomeNames(bytes32 questionId) external view returns (string[] memory) { + return ControllerStorage.registry().questions[questionId].outcomeNames; + } + + /// @dev forked from uma-ctf-adaptor but using ControllerStorage slots + function getAncillaryUpdates(bytes32 questionId, address owner) + external + view + returns (AncillaryDataUpdate[] memory) + { + return Registry.getUpdates(questionId, owner); + } + + /// @dev forked from uma-ctf-adaptor but using ControllerStorage slots + function getLatestAncillaryUpdate(bytes32 questionId, address owner) + external + view + returns (AncillaryDataUpdate memory) + { + return Registry.getLatestUpdate(questionId, owner); + } + + function getAncillaryUpdatesPaginated(bytes32 questionId, address owner, uint256 offset, uint256 limit) + external + view + returns (AncillaryDataUpdate[] memory) + { + return Registry.getUpdatesPaginated(questionId, owner, offset, limit); + } + + function getConfig(address market) + external + view + returns ( + address treasuryOut, + uint80 feeRate, + uint256 numOutcomes, + uint128 timestampEnd, + uint256 answer, + bool isFinalised_ + ) + { + GovernanceStorage storage gov = ControllerStorage.governance(); + RegistryStorage storage reg = ControllerStorage.registry(); + + treasuryOut = gov.treasury; + feeRate = _getFeeRate(market); + + bytes32 questionId = IWTFMarket(market).questionId(); + QuestionStateV2 storage question = reg.questions[questionId]; + numOutcomes = question.getNumOutcomes(); + timestampEnd = question.timestampEnd; + answer = question.answer; + isFinalised_ = question.isFinalised(); + } + + // WTF: read accessors for market contracts & frontends + function getCreator(bytes32 questionId) external view override(IWTFControllerV2, IRegistry) returns (address) { + return ControllerStorage.registry().questions[questionId].creator; + } + + function getCreatorShare() external view override(IWTFControllerV2, IRegistry) returns (uint80) { + return _getCreatorShare(); + } + + function getCentralWallet() external view override(IWTFControllerV2, IRegistry) returns (address) { + return _getCentralWallet(); + } + + function getGraduationThresholds() + external + view + override(IWTFControllerV2, IRegistry) + returns (uint256 thresholdMcap, uint256 thresholdMaxSupply) + { + return _getGraduationThresholds(); + } + + function getDisputeWindow() external view override(IWTFControllerV2, IRegistry) returns (uint256) { + return _getDisputeWindow(); + } + + function isClaimable(bytes32 questionId) external view override(IWTFControllerV2, IRegistry) returns (bool) { + return ControllerStorage.registry().questions[questionId].isClaimable(_getDisputeWindow()); + } + + function isWithinDisputeWindow(bytes32 questionId) + external + view + override(IWTFControllerV2, IRegistry) + returns (bool) + { + return ControllerStorage.registry().questions[questionId].isWithinDisputeWindow(_getDisputeWindow()); + } + + function isMarketClaimable(address market) external view override(IWTFControllerV2, IRegistry) returns (bool) { + bytes32 questionId = IWTFMarket(market).questionId(); + (,, uint256 disputeWindow,,) = _getMarketConfig(market); + return ControllerStorage.registry().questions[questionId].isClaimable(disputeWindow); + } + + function isMarketWithinDisputeWindow(address market) + external + view + override(IWTFControllerV2, IRegistry) + returns (bool) + { + bytes32 questionId = IWTFMarket(market).questionId(); + (,, uint256 disputeWindow,,) = _getMarketConfig(market); + return ControllerStorage.registry().questions[questionId].isWithinDisputeWindow(disputeWindow); + } + + function isAdmin(address account) external view override(IWTFControllerV2, IRegistry) returns (bool) { + return hasRole(DEFAULT_ADMIN_ROLE, account); + } + + function predictMarketAddress( + address collateral, + uint256 parentTokenId, + bytes32 questionId, + address curve, + uint128 timestampStart + ) external view returns (address) { + return _computeCounterfactual( + MarketDeployParams({ + collateral: collateral, + parentTokenId: parentTokenId, + questionId: questionId, + curve: curve, + timestampStart: timestampStart + }) + ); + } + + function _onlyCreator(bytes32 questionId, address creator) internal view { + RegistryStorage storage $ = ControllerStorage.registry(); + if (!$.questions[questionId].isRegistered()) revert Errors.RegistryQuestionNotFound(); + if ($.questions[questionId].creator != creator) revert Errors.RegistryOnlyCreator(); + } + + function _onlyOracle(bytes32 questionId, address oracle) internal view { + RegistryStorage storage $ = ControllerStorage.registry(); + if (!$.questions[questionId].isRegistered()) revert Errors.RegistryQuestionNotFound(); + if ($.questions[questionId].oracle != oracle) revert Errors.RegistryOnlyOracle(); + } + + function _isPaused() internal view returns (bool) { + GovernanceStorage storage $ = ControllerStorage.governance(); + return $.paused; + } + + function _ensureQuestionCreated(QuestionParams calldata paramsQuestion, address oracle) + private + returns (bytes32 questionId, uint256 numOutcomes) + { + questionId = QuestionV2.getId(msg.sender, oracle, paramsQuestion.title, paramsQuestion.ancillaryData); + + RegistryStorage storage reg = ControllerStorage.registry(); + QuestionStateV2 storage question = reg.questions[questionId]; + + if (!question.isRegistered()) { + Registry.createQuestion(paramsQuestion, oracle, msg.sender); + + numOutcomes = paramsQuestion.outcomeNames.length; + } else { + // note: questionId guarantees msg.sender == creator + numOutcomes = question.getNumOutcomes(); + } + } + + function _seed(address market, MarketParams calldata paramsMarket, uint256 numOutcomes, uint256 otSeed) private { + uint256[] memory tokenIds = new uint256[](numOutcomes); + uint256[] memory otAmounts = new uint256[](numOutcomes); + for (uint256 i = 0; i < numOutcomes; ++i) { + tokenIds[i] = Market.toTokenId(i); + otAmounts[i] = otSeed; + } + + uint256 collateralTotal = _seedLiquidity( + market, paramsMarket.collateral, paramsMarket.parentTokenId, paramsMarket.curve, tokenIds, otAmounts + ); + + if (paramsMarket.parentTokenId == NULL_PARENT_ID) { + GovernanceStorage storage gov = ControllerStorage.governance(); + if (collateralTotal < gov.whitelistedCollaterals[paramsMarket.collateral].collateralSeedMin) { + revert Errors.RegistrySeedBelowMinimum(); + } + } + + // note: unable to enforce collateral value for nested markets (marginal price is volatile) + } +} + diff --git a/main/src/interfaces/IRegistry.sol b/main/src/interfaces/IRegistry.sol new file mode 100644 index 0000000..603f317 --- /dev/null +++ b/main/src/interfaces/IRegistry.sol @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +interface IRegistry { + function isFinalised(bytes32 questionId) external view returns (bool finalised); + + function getOutcomeAnswer(bytes32 questionId) external view returns (uint256 answer); + + function getOutcomeEnd(bytes32 questionId) external view returns (uint128 timestampEnd); + + function getNumOutcomes(bytes32 questionId) external view returns (uint256 numOutcomes); + + function getOutcomeNames(bytes32 questionId) external view returns (string[] memory names); + + function getConfig(address market) + external + view + returns ( + address _treasury, + uint80 _feeRate, + uint256 _numOutcomes, + uint128 _timestampEnd, + uint256 _answer, + bool _isFinalised + ); + + function isPaused() external view returns (bool); + + // WTF: fee split & graduation accessors + function getCreator(bytes32 questionId) external view returns (address creator); + + function getCreatorShare() external view returns (uint80 creatorShare); + + function getCentralWallet() external view returns (address centralWallet); + + function getGraduationThresholds() external view returns (uint256 thresholdMcap, uint256 thresholdMaxSupply); + + function getDisputeWindow() external view returns (uint256 disputeWindow); + + function isClaimable(bytes32 questionId) external view returns (bool claimable); + + function isWithinDisputeWindow(bytes32 questionId) external view returns (bool withinWindow); + + function isMarketClaimable(address market) external view returns (bool claimable); + + function isMarketWithinDisputeWindow(address market) external view returns (bool withinWindow); + + function getMarketConfig(address market) + external + view + returns (uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, uint8 tierId, bool isCustom); + + function getMarketTier(uint8 tierId) + external + view + returns (uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, bool isCustom); + + function isAdmin(address account) external view returns (bool isAdminAccount); +} + diff --git a/main/src/interfaces/IWTFControllerV2.sol b/main/src/interfaces/IWTFControllerV2.sol new file mode 100644 index 0000000..558997c --- /dev/null +++ b/main/src/interfaces/IWTFControllerV2.sol @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {QuestionParams, MarketParams} from "@wtf/src/controllerv2/ControllerStorage.sol"; + +interface IWTFControllerV2 { + /** + * @notice assumes 1 OT seed amount for all outcomes + */ + function deployMarket( + QuestionParams calldata paramsQuestion, + MarketParams calldata paramsMarket, + address oracle, + uint256 otSeed + ) external returns (bytes32 questionId, address market); + + function seedLiquidity(address market, uint256[] calldata tokenIds, uint256[] calldata otAmounts) external; + function postUpdate(bytes32 questionId, bytes calldata update) external; + + function addOutcomes(bytes32 questionId, string[] calldata names, string[] calldata imageUris) external; + function modifyTimestampEnd(bytes32 questionId, uint128 timestampEndNew) external; + function setImageUri(bytes32 questionId, string calldata imageUri) external; + function setOutcomeImageUri(bytes32 questionId, uint256 indexOutcome, string calldata imageUri) external; + + function resolveOutcome(bytes32 questionId, uint256 answer) external; + function unresolveOutcome(bytes32 questionId) external; + function finaliseOutcome(bytes32 questionId, uint256 answerChallenge) external; + + // WTF: settlement & admin params + function adminSettle(bytes32 questionId, uint256 answer) external; + function overrideFinalise(bytes32 questionId, uint256 answer) external; + function setCreatorShare(uint80 creatorShareNew) external; + function setCentralWallet(address centralWalletNew) external; + function setGraduationThresholds(uint256 thresholdMcapNew, uint256 thresholdMaxSupplyNew) external; + + function setThresholdsAndWindow(uint256 thresholdMcapNew, uint256 thresholdMaxSupplyNew, uint256 disputeWindowNew) external; + + function setDisputeWindow(uint256 disputeWindowNew) external; + + function setMarketTier(uint8 tierId, uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow) external; + function setMarketTierBinding(address market, uint8 tierId) external; + function setMarketConfigOverride(address market, uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, bool isCustom) external; + + function getCreator(bytes32 questionId) external view returns (address creator); + function getCreatorShare() external view returns (uint80 creatorShare); + function getCentralWallet() external view returns (address centralWallet); + function getGraduationThresholds() external view returns (uint256 thresholdMcap, uint256 thresholdMaxSupply); + function getDisputeWindow() external view returns (uint256 disputeWindow); + function isClaimable(bytes32 questionId) external view returns (bool claimable); + function isWithinDisputeWindow(bytes32 questionId) external view returns (bool withinWindow); + function isMarketClaimable(address market) external view returns (bool claimable); + function isMarketWithinDisputeWindow(address market) external view returns (bool withinWindow); + function getMarketConfig(address market) external view returns (uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, uint8 tierId, bool isCustom); + function getMarketTier(uint8 tierId) external view returns (uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, bool isCustom); + function isAdmin(address account) external view returns (bool isAdminAccount); + + function predictMarketAddress( + address collateral, + uint256 parentTokenId, + bytes32 questionId, + address curve, + uint128 timestampStart + ) external view returns (address); + + function getDefaultFeeRate() external view returns (uint80); +} + diff --git a/main/src/interfaces/IWTFCurve.sol b/main/src/interfaces/IWTFCurve.sol new file mode 100644 index 0000000..1be500d --- /dev/null +++ b/main/src/interfaces/IWTFCurve.sol @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +interface IWTFCurve { + /** + * @notice calculate marginal price of an OT. Marginal price refers to the cost to buy an infinitesimal amount of OT. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * @return price marginal price, scaled to decimals of collateral + */ + function calMarginalPrice(address market, uint256 tokenId) external view returns (uint256 price); + + /** + * @notice calculate cost of OT given OT to mint. Cost refers to the total amount of collateral required. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * @return collateralFromUser amount of collateral required from user. note that part of it goes to treasury as fees + * @return collateralToTreasury fee of trade, given to treasury + * @dev may contain state-modifying calls, note the lack of `view` modifier + */ + function calMintCostByOtDelta(address market, uint256 tokenId, uint256 otDelta, bytes calldata dataSwap) + external + returns (uint256 collateralFromUser, uint256 collateralToTreasury); + + /** + * @notice calculate value of OT given OT to redeem. Value refers to the total amount of collateral the OT is worth. Term is similar, but not the same as cost. + * @return collateralToUser amount of collateral given to user. note that amount is POST fees (fees are already deducted) + * @return collateralToTreasury fee of trade, given to treasury + * @dev may contain state-modifying calls, note the lack of `view` modifier + */ + function calRedeemValueByOtDelta(address market, uint256 tokenId, uint256 otDelta, bytes calldata dataSwap) + external + returns (uint256 collateralToUser, uint256 collateralToTreasury); + + /** + * @notice calculate cost of OTs given OTs to seed. Cost refers to the total amount of collateral required. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * the curve is agnostic to whether fees are charged and if OTs are given back to the seeder or to treasury. + * @notice this function is called only for seed. Non-seed transactions do not use this. + * seeding is different from minting as it is used to initialise the market, thus it is crucial for: + * - setting up an initial "rate" for multi-dimensional bonding curves (i.e LMSR, AMMs) whereby invariants affect each other + * - bypassing user-facing special mechanics (i.e mint premiums) + * - seed at a fixed price without quotations (i.e RFQ or an external oracle) + * - creating a curve where no OTs are minted and only collateral is donated (use dataSwap with otDeltas of 0) + * @return collateralsFromUser amount of collaterals required from user + * @return collateralsToTreasury fee of seed, given to treasury + * @dev the curve can still implement the exact same formulas as mints, and it is not required to offer a preferntial quote + * @dev may contain state-modifying calls, note the lack of `view` modifier + * @dev guessing from collaterals is not provided due to possibility of onchain reverts with multiple swaps + */ + function calSeedCostByOtDeltas( + address market, + uint256[] calldata tokenIds, + uint256[] calldata otDeltas, + bytes calldata dataSwap + ) external returns (uint256[] memory collateralsFromUser, uint256[] memory collateralsToTreasury); + + /** + * @notice approximate amount of OT to mint given collateral to spend. Cost refers to the total amount of collateral required. Term comes from Robin Hanson's paper on Market Scoring Rules(AMM) + * @return otDelta best approximated amount of OT to mint + * @return collateralFromUser expected amount of collateral required from user, PLEASE read DbC below. + * @dev Interface's Design by Contract(DbC) MUST be followed: Given no other factors between approx and actual swap, + * collateralFromUser returned must match the collateralFromUser returned by `calMintCostByOtDelta` called during actual swap. + */ + function calOtDeltaByMintCost(address market, uint256 tokenId, uint256 collateralDelta, bytes calldata dataGuess) + external + view + returns (uint256 otDelta, uint256 collateralFromUser); + + /** + * @notice approximate amount of OT to redeem given collateral to receive. Value refers to the total amount of collateral the OT is worth. Term is similar, but not the same as cost. + * @return otDelta best approximated amount of OT to redem + * @return collateralToUser expected amount of collateral given to user, PLEASE read DbC below. + * @dev Interface's Design by Contract(DbC) MUST be followed: Given no other factors between approx and actual swap, + * collateralToUser returned must match the collateralToUser returned by `calRedeemValueByOtDelta` called during actual swap. + */ + function calOtDeltaByRedeemValue(address market, uint256 tokenId, uint256 collateralDelta, bytes calldata dataGuess) + external + view + returns (uint256 otDelta, uint256 collateralToUser); + + /** + * @notice Exposes the curve's underlying cost function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simCost(uint256 otSupply) external view returns (uint256 cost); + + /** + * @notice Exposes the curve's underlying cost function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simCost(address market, uint256 tokenId, uint256 otSupply) external view returns (uint256 cost); + + /** + * @notice Exposes the curve's underlying marginal price function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simMarginalPrice(uint256 otSupply) external view returns (uint256 price); + + /** + * @notice Exposes the curve's underlying marginal price function + * @notice Does not return in collateral decimal precision as this is market-agnostic, refer to the curve library for decimals + * @dev You are STRONGLY recommended to rely on `cal` functions instead of rawdogging everything using `simCost`. + */ + function simMarginalPrice(address market, uint256 tokenId, uint256 otSupply) external view returns (uint256 price); + + /** + * @notice Exposes the curve's underlying seed logic, so that it is possible to estimate costs without a market + * @return collateralFromUserTotal total amount of collateral required, given in collateral decimals + * @return collateralToTreasuryTotal total amount of fees to treasury, given in collateral decimals + * @dev Interface's Design by Contract(DbC) MUST be followed: Given to other factors between simSeed and seed, + * collateralFromUserTotal must be sum of collateralsFromUser in calSeedCostByOtDeltas. collateralToTreasuryTotal must be sum of collateralsToTreasury in calSeedCostByOtDeltas. + */ + function simSeed(uint256[] calldata tokenIds, uint256[] calldata otDeltas, uint8 collateralDecimals, uint80 feeRate) + external + view + returns (uint256 collateralFromUserTotal, uint256 collateralToTreasuryTotal); + + /** + * @notice There are a lot of factors involved in the curve, so this is a rather inaccurate function that attempts to "approximately" value an OT. + * Calling this when all other factors are not aligned results in an invalid number. + * Additionally, even when called properly there is no meaning to the number other than for frontend displays. + * @dev DO NOT RELY ON THIS FOR ONCHAIN LOGIC + * @return collateralFromUser collateral required from user when minting from otFrom, assuming all factors aligned + * @return collateralToTreasury collateral given to treasury, assuming all factors aligned + * @dev collateralFromUser + collateralToTreasury = total approximated value of the position-ish + */ + function extrapolateMintForOffchainOnly(address market, uint256 tokenId, uint256 otFrom, uint256 otDelta) + external + view + returns (uint256 collateralFromUser, uint256 collateralToTreasury); + + /** + * @notice There are a lot of factors involved in the curve, so this is a rather inaccurate function that attempts to "approximately" value an OT. + * Calling this when all other factors are not aligned results in an invalid number. + * Additionally, even when called properly there is no meaning to the number other than for frontend displays. + * @dev DO NOT RELY ON THIS FOR ONCHAIN LOGIC + * @return collateralToUser collateral given to user when redeeming from otFrom, assuming all factors aligned + * @return collateralToTreasury collateral given to treasury, assuming all factors aligned + * @dev collateralToUser + collateralToTreasury = total approximated value of the position-ish + */ + function extrapolateRedeemForOffchainOnly(address market, uint256 tokenId, uint256 otFrom, uint256 otDelta) + external + view + returns (uint256 collateralToUser, uint256 collateralToTreasury); +} + diff --git a/main/src/interfaces/IWTFMarket.sol b/main/src/interfaces/IWTFMarket.sol new file mode 100644 index 0000000..f4ef35a --- /dev/null +++ b/main/src/interfaces/IWTFMarket.sol @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +import {MarketDeployParams, MarketState} from "@wtf/lib/Market.sol"; +import {IERC6909TokenSupply, IERC6909Metadata} from "@openzeppelin/contracts/interfaces/IERC6909.sol"; + +interface IWTFMarket is IERC6909Metadata, IERC6909TokenSupply { + function mintCollateralToExactOt( + address receiver, + uint256 tokenId, + uint256 otDeltaOut, + bytes calldata dataSwap, + bytes calldata dataCallback + ) external returns (uint256 collateralIn); + + function redeemExactOtToCollateral(address receiver, uint256 tokenId, uint256 otDeltaIn, bytes calldata dataSwap) + external + returns (uint256 collateralOut); + + function seed(uint256 tokenId, uint256 otSeed, bytes calldata dataSwap) external; + + function claim(address receiver, uint256[] memory tokenIds, uint256[] memory otToBurn) + external + returns (uint256 payout); + + function simPayout(uint256 answerSim, uint256 otUserWinning) external view returns (uint256 payout); + + function totalMarketCap() external view returns (uint256); + + function marketType() external view returns (string memory); + + function collateralDecimals() external view returns (uint8 decimal); + + function readState() external view returns (MarketState memory); + + function readMarketDeployParams() external view returns (MarketDeployParams memory); + + function registry() external view returns (address); + + function questionId() external view returns (bytes32); + + function timestampStart() external view returns (uint128); +} + diff --git a/main/src/interfaces/IWTFMarketV2.sol b/main/src/interfaces/IWTFMarketV2.sol new file mode 100644 index 0000000..0c282fc --- /dev/null +++ b/main/src/interfaces/IWTFMarketV2.sol @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.0; + +import {MarketDeployParams, MarketState} from "@wtf/lib/Market.sol"; +import {IERC6909TokenSupply, IERC6909Metadata} from "@openzeppelin/contracts/interfaces/IERC6909.sol"; + +interface IWTFMarketV2 is IERC6909Metadata, IERC6909TokenSupply { + function mintCollateralToExactOt(address receiver, uint256 tokenId, uint256 otDeltaOut, bytes calldata dataSwap) + external + returns (uint256 collateralIn); + + function redeemExactOtToCollateral(address receiver, uint256 tokenId, uint256 otDeltaIn, bytes calldata dataSwap) + external + returns (uint256 collateralOut); + + function seed(uint256[] calldata tokenIds, uint256[] calldata otAmounts, bytes calldata dataSwap) + external + returns (uint256 collateralConsumed); + + function claim(address receiver, uint256[] memory tokenIds, uint256[] memory otToBurn) + external + returns (uint256 payout); + + function simPayout(uint256 answerSim, uint256 otUserWinning) external view returns (uint256 payout); + + function totalMarketCap() external view returns (uint256); + + /** + * @notice new function signature, not supported in IWTFMarket + */ + function marketCap(uint256 tokenId) external view returns (uint256); + + function marketType() external view returns (string memory); + + function collateralDecimals() external view returns (uint8 decimal); + + function readState() external view returns (MarketState memory); + + function readMarketDeployParams() external view returns (MarketDeployParams memory); + + function registry() external view returns (address); + + function questionId() external view returns (bytes32); + + function timestampStart() external view returns (uint128); + + // WTF: graduation & refund + function graduate() external returns (uint256 redeemValue_); + function forceGraduate() external returns (uint256 redeemValue_); + + function refund() external; + + function isGraduated() external view returns (bool graduated); + + function redeemValue() external view returns (uint256 redeemValue_); + + function isRefunded() external view returns (bool refunded); + + function refundValue() external view returns (uint256 refundValue_); + + function graduationProbs(uint256 index) external view returns (uint256 prob); + + function clobOpenPrices() external view returns (uint256[] memory prices); +} + diff --git a/main/src/libraries/Errors.sol b/main/src/libraries/Errors.sol new file mode 100644 index 0000000..d46dce0 --- /dev/null +++ b/main/src/libraries/Errors.sol @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +library Errors { + error FactoryInvalidCurve(); + error FactoryInvalidCollateral(); + error FactoryInvalidSeedAmount(); + error FactoryUnsuccessfulMarketDeployment(); + error FactoryFeeRateExceedMaximumLimit(); + error FactoryCurveNotAllowed(); + error FactorySeedCostMismatch(); + error FactorySeedCallFailed(); + error FactoryNativeTokenNotAllowed(); + + error CurveInvalidCost(uint256 quantity); + error CurveOtDeltaNotOnTick(uint256 otDelta, uint256 tick); + error CurveInvalidStartEnd(); + + error RegistryInsufficientOutcomesGiven(); + error RegistryExceedMaxNames(); + error RegistryAlreadyRegistered(); + error RegistryInvalidAddressPtr(); + error RegistryEndTimestampHasPassed(); + error RegistryEmptyTitle(); + error RegistryExceedMaxTitleLength(); + error RegistryExceedMaxDescriptionLength(); + error RegistryEmptyName(); + error RegistryExceedMaxNameLength(); + error RegistryDuplicateOutcome(); + error RegistryNotRegistered(); + error RegistryAlreadyFinalised(); + error RegistryEndTimestampBeforeExisting(); + error RegistryInvalidAnswer(); + error RegistrySameAnswer(); + error RegistryNotResolved(); + error RegistryAnswerDoesNotMatchCurrent(); + error Registry6909MustBeRegisteredMarket(); + error RegistryInvalidTokenIdAsCollateral(); + error RegistryTokenIdNotCreatedForMarket(); + error RegistryInvalidTreasuryAddress(); + error RegistryExceedMaxAncillaryDataUpdateLength(); + + error GuessInvalidDataLength(uint256 len, uint256 required); + error GuessMinGreaterThanMax(uint256 guessMin, uint256 guessMax); + error GuessMaxIterationsZero(); + error GuessEpsAboveMax(); + error GuessExceedMaxIterations(uint256 maxIterations); + error GuessExceedMaxInterpolationIterations(uint256 maxIterations); + error GuessTargetUnreachable(uint256 current, uint256 target); + + error MarketUnprocessableAnswer(uint256 answer); + error MarketPayoutPerOutcomeAlreadyCalculated(uint256 payoutPerOutcome); + error MarketNotFinalised(); + error MarketNotResolved(); + error MarketSwapAmountCannotBeZero(); + error MarketTooManyTotalSupplies(uint256 required); + error MarketTooManyOutcomes(); + error MarketNotStarted(); + error MarketEnded(); + error MarketResolved(); + error MarketUnauthorizedAccess(address account, address required); + error MarketZeroCostBasis(); + error MarketInvalidTokenId(uint256 tokenId); + error MarketSwapPriceInvalidated(uint256 collateralDelta, uint256 otDelta); + error MarketArrayLengthsMismatch(); + error MarketNoClaim(); + error MarketPaused(); + error MarketNotWhole(); + error MarketReceiverIsMarket(); + error MarketZeroAddress(); + error MarketNoTokenIdsToSeed(); + + // WTF: graduation & refund + error MarketGraduated(); + error MarketAlreadyGraduated(); + error MarketGraduationThresholdNotMet(); + error MarketZeroTotalSupply(); + error MarketZeroSumPrice(); + error MarketClaimWindowNotPassed(); + error MarketAlreadyRefunded(); + error MarketRefundWindowPassed(); + + error RouterUnauthorized(); + error RouterDbCViolated(); + error RouterSlippage(); + error RouterUnsupportedSelector(); + error RouterArrayLengthsMismatch(); + error RouterNotClaimableYet(); + error RouterIntegratorFeeTooHigh(); + error RouterInvalidIntegrator(); + error RouterInvalidMarket(); + error RouterInvalidSwapAmount(); + + error RegistryUnauthorized(); + error RegistryFeeRateTooHigh(); + error RegistryFeeRateTooLow(); + error RegistryInvalidCreatorShare(); + error RegistryInvalidCentralWallet(); + error RegistryInvalidDisputeWindow(); + error RegistryQuestionNotFound(); + error RegistryQuestionAlreadyExists(); + error RegistryQuestionAlreadyFinalised(); + error RegistryQuestionNotResolved(); + error RegistryInvalidNumOutcomes(); + error RegistryInvalidTimestamp(); + error RegistrySeedTooLow(); + error RegistryCurveNotAllowed(); + error RegistryMarketDeploymentFailed(); + error RegistryCollateralNotWhitelisted(); + error RegistryPaused(); + error RegistryInvalidOracleAddress(); + error RegistryOnlyCreator(); + error RegistryOnlyOracle(); + error RegistryOnlyCreatorOrOracleOrAdmin(); + error RegistrySeedBelowMinimum(); + error RegistryManualFinaliseTooEarly(); + error RegistryAlreadyFlagged(); + error RegistryNotFlagged(); + error RegistryOutcomeImagesMismatch(); + error RegistryMarketNotFound(); + error RegistryMinSeedCannotBeZero(); + error RegistryInvalidCurve(); + error RegistryOutcomeLengthMismatch(); + error RegistryQuestionIsFlagged(); + error RegistryNotFinalised(); + error RegistryOverrideTooLate(); + + error AdaptorInvalidQuestion(); + error AdaptorSeedCostExceedsBudget(); + + error MarketInsufficientSeedCollateral(); + + error Safe6909TransferFailed(); + + error RouterStaticCallFailed(); + + error DRegistryQuestionNotResolved(); + error DRegistryQuestionAlreadyFinalised(); + error DRegistryLimitIsZero(); + error DRegistryInvalidQuestion(); + + error AdaptorMarketDoesNotMatchQuestionId(); + error AdaptorOtAmountsDoesNotMatch(); + + // TODO: cleanup +} + diff --git a/main/src/libraries/Event.sol b/main/src/libraries/Event.sol new file mode 100644 index 0000000..30e2e4f --- /dev/null +++ b/main/src/libraries/Event.sol @@ -0,0 +1,319 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +/** + * @dev NOTE: a lot of learnings are inspired from mangrove + * All WTF related events are listed here + */ +interface HasFTEvents { + /** + * Events in solidity are a lose-only feature. + * If you look at it in the perspective of a gas efficiency purist, every event and additional field in the event adds gas. + * Spamming events is also bizzare since many events become additional lines of liability(code) whilst providing zero benefits. + * However, trying to emit as few events as possible and with as few fields as possible misses the original intent of events as offchain consumers cannot effectively consume these events. + * In order words - with events, everyone loses. + * + * We can try to minimise our Ls via these main considerations: + * - Minimise gas usage (don't spam events) + * - An indexer must be able to monitor or create the state of WTF + * - It should be possible to query historical information such as marginal prices, total cost, total supply via RPC calls & block tags. This is especially important in reconciling indexed events with onchain state. + * - Any hot data requirements should and must be accessed via RPC calls instead of events. + * + * It is nontrivial to find the "best" solution, especially since they are in conflict and continual development exists. + */ + /* WTF Creation & Configuration */ + + /** + * Emitted when creating new market + */ + event CreateNewMarket( + address indexed market, + address collateral, + uint256 parentTokenId, + bytes32 questionId, + address curve, + uint256 timestampStart + ); + + /** + * Emitted when creating new question + * + * NOTE: yes, you can get the title from calling the ptr... + * + * @dev this event is a legacy event and is only emitted by `WTFMarketController.sol`. Please see the version CreateNewQuestionV + */ + event CreateNewQuestion(bytes32 indexed questionId, string title, address ptr); + + /** + * Emitted when adding an outcome to a question + */ + event AddOutcome(bytes32 indexed questionId, uint256 indexOutcomeFromZero, string name); + + /** + * Emitted when creating a new question (timestampPrev is 0) or extending the end timestamp of an existing market + * + * Please use this as a single source of truth/a ledger of amendments to the end timestamp, instead of attempting to track end timestamp via multiple possible event sources. + * Please reconcile by identifying missing timestamps between timestampPrev & timestampNext. All questions must have exactly one event where timestampPrev is 0. + * + * @dev this event is a legacy event and is only emitted by `WTFMarketController.sol`. Please see ModifyEnd which has the same data but different naming for better clarity. + * In this version, end timestamp can only be extended to ensure that only the earliest timestamp is used for all questions + */ + event ExtendEnd(bytes32 indexed questionId, uint128 timestampPrev, uint128 timestampNext); + + /** + * Emitted when resolving a question + */ + event Resolve(bytes32 indexed questionId, uint256 answerPrev, uint256 answerNext); + + /** + * Emitted when finalising the resolution + */ + event Finalise(bytes32 indexed questionId, uint256 answer); + + /** + * Emitted when manually finalising a question + */ + event ManuallyFinalise(bytes32 indexed questionId, uint256 answer); + + /* WTF Market Activities (Trading & Claiming) */ + + /** + * Indexers please use this to maintain a user ledger via single-entry accounting (+outcome -collateral) + * Please reconcile values using an RPC call & block tag + * + * Mint comes from protocol terminology: mint => user buys OTs from pool using collateral + * Swap is added because Mint is conflicts with the "typical" Mint event + */ + event MintSwap( + address indexed caller, + address indexed receiver, + uint256 indexed tokenId, + uint256 collateralFromUser, + uint256 otToUser, + uint256 collateralToTreasury + ); + + /** + * Indexers please use this to maintain a user ledger via single-entry accounting (-outcome +collateral) + * Please reconcile values using an RPC call & block tag + * + * Redeem comes from protocol terminology: redeem => user sells OTs from pool to get collateral + * Swap is added because + */ + event RedeemSwap( + address indexed caller, + address indexed receiver, + uint256 indexed tokenId, + uint256 collateralToUser, + uint256 otToPool, + uint256 collateralToTreasury + ); + + /** + * Indexers please use this to maintain a user ledger via single-entry accounting (-outcome +collateral) + * Please reconcile values using an RPC call & block tag + * + * Claiming is a similar financial transaction as redeem when viewed as a bookkeeper just that it has no fees (fee = 0). + */ + event ClaimPayout( + address indexed caller, address indexed receiver, uint256 indexed tokenId, uint256 otBurned, uint256 payout + ); + + /** + * Emitted when setting the fee of a market + * + * @dev this event is a legacy event and there is no longer a per-market fee. Use SetProtocolFeeRate and SetProtocolFeeOverride instead. + */ + event SetFeeRate(address indexed market, uint256 feeRate); + + /** + * Emitted when setting treasury address + */ + event SetTreasury(address indexed market); + + /** + * Emitted when pausing trading. + * Only trading can be paused. All markets will be paused. + */ + event Paused(address account); + + /** + * Emitted when unpausing. All markets will be unpaused. + */ + event Unpaused(address account); + + /** + * Emitted when creating a new question (timestampPrev is 0) or modifying the end timestamp of an existing market + * + * Please use this as a single source of truth/a ledger of amendments to the end timestamp, instead of attempting to track end timestamp via multiple possible event sources. + * Please reconcile by identifying missing timestamps between timestampPrev & timestampNext. All questions must have exactly one event where timestampPrev is 0. + * + * @dev the naming can be slightly confusing due to differing versions: + * In this version, end timestamp can be modified earlier to support markets whereby the market itself is a parlay (i.e P(A|B)). + */ + event ModifyEnd(bytes32 indexed questionId, uint96 timestampPrev, uint96 timestampNext); + + /** + * Emitted when setting a new default protocol fee rate + */ + event SetProtocolFeeRate(uint80 feeRateNew); + + /** + * Emitted when setting the fee rate of a specific market + */ + event SetProtocolFeeOverride(address indexed market, uint80 feeRate, bool isOverride); + + // WTF: admin-settable parameters + event SetCreatorShare(uint80 creatorShareNew); + event SetCentralWallet(address indexed centralWalletNew); + event SetGraduationThresholds(uint256 thresholdMcap, uint256 thresholdMaxSupply); + event SetDisputeWindow(uint256 disputeWindow); + event SetMarketTier(uint8 indexed tierId, uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow); + event SetMarketTierBinding(address indexed market, uint8 indexed tierId); + event SetMarketConfigOverride(address indexed market, uint256 thresholdMcap, uint256 thresholdMaxSupply, uint256 disputeWindow, bool isCustom); + + // WTF: graduation & refund + event GraduateMarket( + address indexed market, + uint256 totalMarketCap, + uint256 totalSupply, + uint256 redeemValue, + uint256[] probs + ); + event MarketRefunded(address indexed market, uint256 refundValue); + event OverrideFinalise(bytes32 indexed questionId, uint256 answerPrev, uint256 answerNext); + event FeeSplit( + address indexed market, + address indexed creator, + uint256 creatorShareAmount, + address indexed centralWallet, + uint256 platformAmount + ); + + /** + * Emitted when creating new question + * + * @dev this replaces CreateNewQuestion + */ + event CreateNewQuestionV2( + bytes32 indexed questionId, + address indexed oracle, + address indexed creator, + string title, + string imageUri, + uint96 timestampEnd, + string[] outcomeNames, + string[] outcomeImageUris, + bytes ancillaryData + ); + + /** + * Emitted when image URI for outcomes is updated + */ + event OutcomeImageUpdated(bytes32 indexed questionId, uint256 indexOutcomeFromZero, string imageUri); + + /** + * Emitted when image URI for question is updated + */ + event QuestionImageUpdated(bytes32 indexed questionId, string imageUri); + + /** + * Emitted when ancillary data is appended. This includes the initial ancillary data + */ + event AncillaryDataUpdated(bytes32 indexed questionId, address indexed owner, bytes update); + + /** + * Emitted when a question is flagged by an admin for manual finalisation + * + * @dev Similar in theory to uma-ctf-adaptor + */ + event QuestionFlagged(bytes32 indexed questionId, uint96 timestampFlagExpiry); + + /** + * Emitted when a question is unflagged by an admin + * + * @dev Similar in theory to uma-ctf-adaptor + */ + event QuestionUnflagged(bytes32 indexed questionId); + + /** + * Emitted when whitelisting a collateral + */ + event CollateralWhitelist(address indexed collateral, bool isWhitelisted, uint256 collateralSeedMin); + + /** + * Emitted when whitelisting a curve + */ + event CurveWhitelist(address indexed curve, bool isWhitelisted); + + /** + * Indexers please use this to maintain a user ledger via single-entry accounting (+outcome -collateral) + * Please reconcile values using an RPC call & block tag + * + * Mint comes from protocol terminology: mint => user buys OTs from pool using collateral + * Swap is added because Mint is conflicts with the "typical" Mint event + * + * @dev this replaces MintSwap + */ + event MintSwapV2( + address indexed caller, + address indexed receiver, + uint256 indexed tokenId, + uint256 collateralToPool, + uint256 otToUser, + uint256 collateralToTreasury + ); + + /** + * Indexers please use this to maintain a user ledger via single-entry accounting (-outcome +collateral) + * Please reconcile values using an RPC call & block tag + * + * Redeem comes from protocol terminology: redeem => user sells OTs from pool to get collateral + * Swap is added because + * + * @dev this replaces RedeemSwap + */ + event RedeemSwapV2( + address indexed caller, + address indexed receiver, + uint256 indexed tokenId, + uint256 collateralFromPool, + uint256 otToPool, + uint256 collateralToTreasury + ); + + /** + * Emitted by router when an integrator fee is charged on a mint. + * Integrator fee is always charged in collateral. + */ + event MintIntegratorFee( + address indexed caller, + address indexed integrator, + address market, + uint256 tokenId, + uint256 collateralFromUser, + uint256 collateralToIntegrator + ); + + /** + * Emitted by router when an integrator fee is charged on a redeem. + * Integrator fee is always charged in collateral. + */ + event RedeemIntegratorFee( + address indexed caller, + address indexed integrator, + address market, + uint256 tokenId, + uint256 collateralToUser, + uint256 collateralToIntegrator + ); + + /** + * Emitted by dispute registry when a dispute is raised. + * Does not include a snapshot of the answer as current answer is mutable and can re-resolve. + */ + event DisputeAncillaryDataUpdated( + bytes32 indexed questionId, address indexed owner, uint256 answerProposed, bytes update + ); +} + diff --git a/main/src/libraries/LogExpMath.sol b/main/src/libraries/LogExpMath.sol new file mode 100644 index 0000000..8f91271 --- /dev/null +++ b/main/src/libraries/LogExpMath.sol @@ -0,0 +1,511 @@ +// SPDX-License-Identifier: MIT +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +// Software. + +// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +pragma solidity ^0.8.0; + +/* solhint-disable */ + +/** + * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). + * + * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural + * exponentiation and logarithm (where the base is Euler's number). + * + * @author Fernando Martinelli - @fernandomartinelli + * @author Sergio Yuhjtman - @sergioyuhjtman + * @author Daniel Fernandez - @dmf7z + */ +library LogExpMath { + // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying + // two numbers, and multiply by ONE when dividing them. + + // All arguments and return values are 18 decimal fixed point numbers. + uint256 constant UONE_18 = 1e18; + int256 constant ONE_18 = 1e18; + + // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the + // case of ln36, 36 decimals. + int256 constant ONE_20 = 1e20; + int256 constant ONE_36 = 1e36; + + // The domain of natural exponentiation is bound by the word size and number of decimals used. + // + // Because internally the result will be stored using 20 decimals, the largest possible result is + // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. + // The smallest possible result is 10^(-18), which makes largest negative argument + // ln(10^(-18)) = -41.446531673892822312. + // We use 130.0 and -41.0 to have some safety margin. + int256 constant MAX_NATURAL_EXPONENT = 130e18; + int256 constant MIN_NATURAL_EXPONENT = -41e18; + + // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point + // 256 bit integer. + int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; + int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; + + uint256 constant MILD_EXPONENT_BOUND = 2 ** 254 / uint256(ONE_20); + + // 18 decimal constants + int256 constant x0 = 128000000000000000000; // 2ˆ7 + int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) + int256 constant x1 = 64000000000000000000; // 2ˆ6 + int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) + + // 20 decimal constants + int256 constant x2 = 3200000000000000000000; // 2ˆ5 + int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) + int256 constant x3 = 1600000000000000000000; // 2ˆ4 + int256 constant a3 = 888611052050787263676000000; // eˆ(x3) + int256 constant x4 = 800000000000000000000; // 2ˆ3 + int256 constant a4 = 298095798704172827474000; // eˆ(x4) + int256 constant x5 = 400000000000000000000; // 2ˆ2 + int256 constant a5 = 5459815003314423907810; // eˆ(x5) + int256 constant x6 = 200000000000000000000; // 2ˆ1 + int256 constant a6 = 738905609893065022723; // eˆ(x6) + int256 constant x7 = 100000000000000000000; // 2ˆ0 + int256 constant a7 = 271828182845904523536; // eˆ(x7) + int256 constant x8 = 50000000000000000000; // 2ˆ-1 + int256 constant a8 = 164872127070012814685; // eˆ(x8) + int256 constant x9 = 25000000000000000000; // 2ˆ-2 + int256 constant a9 = 128402541668774148407; // eˆ(x9) + int256 constant x10 = 12500000000000000000; // 2ˆ-3 + int256 constant a10 = 113314845306682631683; // eˆ(x10) + int256 constant x11 = 6250000000000000000; // 2ˆ-4 + int256 constant a11 = 106449445891785942956; // eˆ(x11) + + /** + * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. + * + * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. + */ + function pow(uint256 x, uint256 y) internal pure returns (uint256) { + if (y == 0) { + // We solve the 0^0 indetermination by making it equal one. + return uint256(ONE_18); + } + + if (x == 0) { + return 0; + } + + // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to + // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means + // x^y = exp(y * ln(x)). + + // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. + require(x >> 255 == 0, "x out of bounds"); + int256 x_int256 = int256(x); + + // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In + // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. + + // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. + require(y < MILD_EXPONENT_BOUND, "y out of bounds"); + int256 y_int256 = int256(y); + + int256 logx_times_y; + if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { + int256 ln_36_x = _ln_36(x_int256); + + // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just + // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal + // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the + // (downscaled) last 18 decimals. + logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); + } else { + logx_times_y = _ln(x_int256) * y_int256; + } + logx_times_y /= ONE_18; + + // Finally, we compute exp(y * ln(x)) to arrive at x^y + require(MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, "product out of bounds"); + + return uint256(exp(logx_times_y)); + } + + /** + * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. + * + * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. + */ + function exp(int256 x) internal pure returns (int256) { + require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "invalid exponent"); + + if (x < 0) { + // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it + // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). + // Fixed point division requires multiplying by ONE_18. + return ((ONE_18 * ONE_18) / exp(-x)); + } + + // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, + // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 + // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the + // decomposition. + // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this + // decomposition, which will be lower than the smallest x_n. + // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. + // We mutate x by subtracting x_n, making it the remainder of the decomposition. + + // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause + // intermediate overflows. Instead we store them as plain integers, with 0 decimals. + // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the + // decomposition. + + // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct + // it and compute the accumulated product. + + int256 firstAN; + if (x >= x0) { + x -= x0; + firstAN = a0; + } else if (x >= x1) { + x -= x1; + firstAN = a1; + } else { + firstAN = 1; // One with no decimal places + } + + // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the + // smaller terms. + x *= 100; + + // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point + // one. Recall that fixed point multiplication requires dividing by ONE_20. + int256 product = ONE_20; + + if (x >= x2) { + x -= x2; + product = (product * a2) / ONE_20; + } + if (x >= x3) { + x -= x3; + product = (product * a3) / ONE_20; + } + if (x >= x4) { + x -= x4; + product = (product * a4) / ONE_20; + } + if (x >= x5) { + x -= x5; + product = (product * a5) / ONE_20; + } + if (x >= x6) { + x -= x6; + product = (product * a6) / ONE_20; + } + if (x >= x7) { + x -= x7; + product = (product * a7) / ONE_20; + } + if (x >= x8) { + x -= x8; + product = (product * a8) / ONE_20; + } + if (x >= x9) { + x -= x9; + product = (product * a9) / ONE_20; + } + + // x10 and x11 are unnecessary here since we have high enough precision already. + + // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series + // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). + + int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. + int256 term; // Each term in the sum, where the nth term is (x^n / n!). + + // The first term is simply x. + term = x; + seriesSum += term; + + // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, + // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. + + term = ((term * x) / ONE_20) / 2; + seriesSum += term; + + term = ((term * x) / ONE_20) / 3; + seriesSum += term; + + term = ((term * x) / ONE_20) / 4; + seriesSum += term; + + term = ((term * x) / ONE_20) / 5; + seriesSum += term; + + term = ((term * x) / ONE_20) / 6; + seriesSum += term; + + term = ((term * x) / ONE_20) / 7; + seriesSum += term; + + term = ((term * x) / ONE_20) / 8; + seriesSum += term; + + term = ((term * x) / ONE_20) / 9; + seriesSum += term; + + term = ((term * x) / ONE_20) / 10; + seriesSum += term; + + term = ((term * x) / ONE_20) / 11; + seriesSum += term; + + term = ((term * x) / ONE_20) / 12; + seriesSum += term; + + // 12 Taylor terms are sufficient for 18 decimal precision. + + // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor + // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply + // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), + // and then drop two digits to return an 18 decimal value. + + return (((product * seriesSum) / ONE_20) * firstAN) / 100; + } + + /** + * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. + */ + function log(int256 arg, int256 base) internal pure returns (int256) { + // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). + + // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by + // upscaling. + + int256 logBase; + if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { + logBase = _ln_36(base); + } else { + logBase = _ln(base) * ONE_18; + } + + int256 logArg; + if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { + logArg = _ln_36(arg); + } else { + logArg = _ln(arg) * ONE_18; + } + + // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places + return (logArg * ONE_18) / logBase; + } + + /** + * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. + */ + function ln(int256 a) internal pure returns (int256) { + // The real natural logarithm is not defined for negative numbers or zero. + require(a > 0, "out of bounds"); + if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { + return _ln_36(a) / ONE_18; + } else { + return _ln(a); + } + } + + /** + * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. + */ + function _ln(int256 a) private pure returns (int256) { + if (a < ONE_18) { + // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less + // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. + // Fixed point division requires multiplying by ONE_18. + return (-_ln((ONE_18 * ONE_18) / a)); + } + + // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which + // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, + // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot + // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. + // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this + // decomposition, which will be lower than the smallest a_n. + // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. + // We mutate a by subtracting a_n, making it the remainder of the decomposition. + + // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point + // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by + // ONE_18 to convert them to fixed point. + // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide + // by it and compute the accumulated sum. + + int256 sum = 0; + if (a >= a0 * ONE_18) { + a /= a0; // Integer, not fixed point division + sum += x0; + } + + if (a >= a1 * ONE_18) { + a /= a1; // Integer, not fixed point division + sum += x1; + } + + // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. + sum *= 100; + a *= 100; + + // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. + + if (a >= a2) { + a = (a * ONE_20) / a2; + sum += x2; + } + + if (a >= a3) { + a = (a * ONE_20) / a3; + sum += x3; + } + + if (a >= a4) { + a = (a * ONE_20) / a4; + sum += x4; + } + + if (a >= a5) { + a = (a * ONE_20) / a5; + sum += x5; + } + + if (a >= a6) { + a = (a * ONE_20) / a6; + sum += x6; + } + + if (a >= a7) { + a = (a * ONE_20) / a7; + sum += x7; + } + + if (a >= a8) { + a = (a * ONE_20) / a8; + sum += x8; + } + + if (a >= a9) { + a = (a * ONE_20) / a9; + sum += x9; + } + + if (a >= a10) { + a = (a * ONE_20) / a10; + sum += x10; + } + + if (a >= a11) { + a = (a * ONE_20) / a11; + sum += x11; + } + + // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series + // that converges rapidly for values of `a` close to one - the same one used in ln_36. + // Let z = (a - 1) / (a + 1). + // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) + + // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires + // division by ONE_20. + int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); + int256 z_squared = (z * z) / ONE_20; + + // num is the numerator of the series: the z^(2 * n + 1) term + int256 num = z; + + // seriesSum holds the accumulated sum of each term in the series, starting with the initial z + int256 seriesSum = num; + + // In each step, the numerator is multiplied by z^2 + num = (num * z_squared) / ONE_20; + seriesSum += num / 3; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 5; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 7; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 9; + + num = (num * z_squared) / ONE_20; + seriesSum += num / 11; + + // 6 Taylor terms are sufficient for 36 decimal precision. + + // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) + seriesSum *= 2; + + // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both + // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal + // value. + + return (sum + seriesSum) / 100; + } + + /** + * @dev Internal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, + * for x close to one. + * + * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. + */ + function _ln_36(int256 x) private pure returns (int256) { + // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits + // worthwhile. + + // First, we transform x to a 36 digit fixed point value. + x *= ONE_18; + + // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). + // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) + + // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires + // division by ONE_36. + int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); + int256 z_squared = (z * z) / ONE_36; + + // num is the numerator of the series: the z^(2 * n + 1) term + int256 num = z; + + // seriesSum holds the accumulated sum of each term in the series, starting with the initial z + int256 seriesSum = num; + + // In each step, the numerator is multiplied by z^2 + num = (num * z_squared) / ONE_36; + seriesSum += num / 3; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 5; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 7; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 9; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 11; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 13; + + num = (num * z_squared) / ONE_36; + seriesSum += num / 15; + + // 8 Taylor terms are sufficient for 36 decimal precision. + + // All that remains is multiplying by 2 (non fixed point). + return seriesSum * 2; + } +} + diff --git a/main/src/libraries/Market.sol b/main/src/libraries/Market.sol new file mode 100644 index 0000000..faf32ef --- /dev/null +++ b/main/src/libraries/Market.sol @@ -0,0 +1,215 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import "@wtf/lib/Errors.sol"; +import "@solady/utils/FixedPointMathLib.sol"; +import "@wtf/lib/WTFMath.sol"; +import "@wtf/lib/RedeemMath.sol"; +import {IWTFCurve} from "@wtf/src/interfaces/IWTFCurve.sol"; + +struct MarketDeployParams { + address collateral; + uint256 parentTokenId; + bytes32 questionId; + address curve; + uint128 timestampStart; +} + +struct SwapParams { + bool isMint; // collateral -> outcome + uint256 amount; + bool isExactIn; + uint256 minOutOrMaxIn; // exactIn = min output, exactOut = max input +} + +struct MarketState { + // immutable + address market; + IWTFCurve curve; + uint128 timestampStart; + // mutable, market related + uint256 totalMarketCap; + // mutable, question related + address treasury; + uint256 numOutcomes; + uint128 timestampEnd; + uint256 answer; + bool isFinalised; +} + +library Market { + using FixedPointMathLib for uint256; + + function isValidTokenId(uint256 tokenId) internal pure returns (bool) { + // 0 is null token id + if (tokenId == 0) return false; + + // power of 2 + if ((tokenId) & (tokenId - 1) != 0) { + return false; + } + + return true; + } + + /** + * @notice TokenId works in powers of 2 from 0th index. + * While the brain works with counts, most things are however 0-th indexed + * @dev You are STRONGLY recommended to use this to avoid off-by-index errors + */ + function toTokenId(uint256 indexOutcomeFromZero) internal pure returns (uint256) { + // 1st outcome -> 2**(1-1) = tokenId 1 + // 2nd outcome -> 2**(2-1) = tokenId 2 + // 3rd outcome -> 2**(3-1) = tokenId 4 + + return 2 ** indexOutcomeFromZero; + } + + /** + * @notice Reverse of toTokenId + * @dev Almost everything should be done in terms of token id, especially core logic to avoid off-by-index errors + * Try not to convert ids back and forth + */ + function fromTokenId(uint256 tokenId) internal pure returns (uint256) { + // tokenId 1 -> log2(1) = index 0 + // tokenId 2 -> log2(2) = index 1 + // tokenId 4 -> log2(4) = index 2 + if (!isValidTokenId(tokenId)) revert Errors.MarketInvalidTokenId(tokenId); + + uint256 index = 0; + uint256 temp = tokenId >> 1; + while (temp > 0) { + temp >>= 1; + index++; + } + return index; + } + + /** + * ** + * @return winner boolean value indicating whether tokenId is a winning OT + * @dev Check via bitwise & operator. Refer to truth table: + * ┌───┬───┬─────┬─────┬─────┐ + * │ A │ B │ AND │ OR │ XOR │ + * ├───┼───┼─────┼─────┼─────┤ + * │ 0 │ 0 │ 0 │ 0 │ 0 │ + * │ 0 │ 1 │ 0 │ 1 │ 1 │ + * │ 1 │ 0 │ 0 │ 1 │ 1 │ + * │ 1 │ 1 │ 1 │ 1 │ 0 │ + * └───┴───┴─────┴─────┴─────┘ + */ + function isWinner(uint256 answer, uint256 tokenId) internal pure returns (bool) { + // answer: 0b101 + // tokenId 1: 0b001 -> 0b101 & 0b001 is a winner + // tokenId 2: 0b010 -> 0b101 & 0b010 is NOT a winner + // tokenId 4: 0b100 -> 0b101 & 0b100 is a winner + + return (answer & tokenId) != 0; + } + + /** + * @dev invariant must be followed: mint more => pay more & mint more => price higher + */ + function mintCollateralToOt(MarketState memory self, uint256 tokenId, uint256 otDeltaOut, bytes memory data) + internal + returns (uint256 collateralDeltaIn, uint256 collateralToTreasury) + { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (otDeltaOut == 0) revert Errors.MarketSwapAmountCannotBeZero(); + if (!isValidTokenId(tokenId) || tokenId > toTokenId(self.numOutcomes - 1)) { + revert Errors.MarketInvalidTokenId(tokenId); + } + + /// ------------------------------------------------------------ + /// MATH + /// ------------------------------------------------------------ + (collateralDeltaIn, collateralToTreasury) = + self.curve.calMintCostByOtDelta(self.market, tokenId, otDeltaOut, data); + + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (collateralDeltaIn == 0) revert Errors.MarketZeroCostBasis(); + if (collateralDeltaIn < collateralToTreasury) revert Errors.MarketNotWhole(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.totalMarketCap += collateralDeltaIn - collateralToTreasury; + } + + /** + * @dev invariant must be followed: redeem more => price lower + */ + function redeemOtToCollateral(MarketState memory self, uint256 tokenId, uint256 otDeltaIn, bytes memory data) + internal + returns (uint256 collateralToUser, uint256 collateralToTreasury) + { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (otDeltaIn == 0) revert Errors.MarketSwapAmountCannotBeZero(); + if (!isValidTokenId(tokenId) || tokenId > toTokenId(self.numOutcomes - 1)) { + revert Errors.MarketInvalidTokenId(tokenId); + } + + /// ------------------------------------------------------------ + /// MATH + /// ------------------------------------------------------------ + (collateralToUser, collateralToTreasury) = + self.curve.calRedeemValueByOtDelta(self.market, tokenId, otDeltaIn, data); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.totalMarketCap -= collateralToUser + collateralToTreasury; + } + + function claim( + MarketState memory self, + uint256[] memory tokenIds, + uint256[] memory otToBurn, + uint256 otSupplyWinning + ) internal pure returns (uint256 payout, uint256 excess, uint256 otUserWinning) { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (tokenIds.length != otToBurn.length) revert Errors.MarketArrayLengthsMismatch(); + if (tokenIds.length == 0) revert Errors.MarketNoClaim(); + + // very awkward edge case: somehow no one holds the winners -> send to treasury and think about how to redistribute + if (otSupplyWinning == 0) { + excess = self.totalMarketCap; + self.totalMarketCap = 0; + // payout = 0, otUserWinning = 0 + return (payout, excess, otUserWinning); + } + + /// ------------------------------------------------------------ + /// MATH + /// ------------------------------------------------------------ + uint256 len = tokenIds.length; + for (uint256 i = 0; i < len; ++i) { + uint256 tokenId = tokenIds[i]; + uint256 otBurned = otToBurn[i]; + if (Market.isWinner(self.answer, tokenId)) { + otUserWinning += otBurned; + } + } + + if (otSupplyWinning == otUserWinning) { + payout = self.totalMarketCap; + } else { + payout = self.totalMarketCap.fullMulDiv(otUserWinning, otSupplyWinning); + } + // excess = 0 here + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.totalMarketCap -= payout; + } +} + diff --git a/main/src/libraries/QuestionV2.sol b/main/src/libraries/QuestionV2.sol new file mode 100644 index 0000000..9bdcccd --- /dev/null +++ b/main/src/libraries/QuestionV2.sol @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.29; + +import {Errors} from "@wtf/lib/Errors.sol"; +import {WTFMath} from "@wtf/lib/WTFMath.sol"; +import {OutcomeNameDeduplicator, QuestionStateV2} from "@wtf/src/controllerv2/ControllerStorage.sol"; + +library QuestionV2 { + using QuestionV2 for QuestionStateV2; + using WTFMath for uint256; + + uint256 private constant MAX_TITLE_LENGTH = 1000; + uint256 private constant MAX_NAME_LENGTH = 50; + uint256 private constant MAX_NUM_OUTCOMES = 255; // outcome answer is represented as a binary uint256, thus, only 255 possible outcomes are supported + + uint256 private constant EMPTY_ANSWER = 0; + uint96 private constant EMPTY_TIMESTAMP_FINALISE = 0; + + uint256 private constant SAFETY_PERIOD = 1 days; + + function register( + QuestionStateV2 storage self, + OutcomeNameDeduplicator storage dedup, + address creator, + address oracle, + uint96 timestampEnd, + string memory title, + string memory imageUri, + string[] memory outcomeNames, + string[] memory outcomeImageUris + ) internal { + uint256 len = outcomeNames.length; + if (len <= 1) revert Errors.RegistryInsufficientOutcomesGiven(); + if (len > MAX_NUM_OUTCOMES) revert Errors.RegistryExceedMaxNames(); + if (outcomeNames.length != outcomeImageUris.length) revert Errors.RegistryOutcomeImagesMismatch(); + if (self.isRegistered()) revert Errors.RegistryAlreadyRegistered(); + if (timestampEnd < block.timestamp) revert Errors.RegistryEndTimestampHasPassed(); + if (bytes(title).length == 0) revert Errors.RegistryEmptyTitle(); + if (bytes(title).length > MAX_TITLE_LENGTH) revert Errors.RegistryExceedMaxTitleLength(); + + for (uint256 i = 0; i < len; ++i) { + string memory name = outcomeNames[i]; + uint256 lenName = bytes(name).length; + if (lenName == 0) revert Errors.RegistryEmptyName(); + if (lenName > MAX_NAME_LENGTH) revert Errors.RegistryExceedMaxNameLength(); + if (dedup.dedup[name]) revert Errors.RegistryDuplicateOutcome(); + dedup.dedup[name] = true; + } + + self.creator = creator; + self.oracle = oracle; + self.timestampEnd = timestampEnd; + self.title = title; + self.imageUri = imageUri; + self.outcomeNames = outcomeNames; + self.outcomeImageUris = outcomeImageUris; + } + + function addOutcomes( + QuestionStateV2 storage self, + OutcomeNameDeduplicator storage dedup, + string[] calldata outcomeNamesToAdd, + string[] calldata outcomeImageUrisToAdd + ) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + // cannot add when finalised + // can add when resolved (hail mary measure to recover protocol funds if needed) + uint256 lenOutcomesCurrent = self.outcomeNames.length; + uint256 lenOutcomesAdd = outcomeNamesToAdd.length; + if (outcomeNamesToAdd.length != outcomeImageUrisToAdd.length) revert Errors.RegistryOutcomeLengthMismatch(); + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (self.isFinalised()) revert Errors.RegistryAlreadyFinalised(); + if (self.isFlagged()) revert Errors.RegistryQuestionIsFlagged(); + if (lenOutcomesAdd == 0) revert Errors.RegistryInsufficientOutcomesGiven(); + if (lenOutcomesCurrent + lenOutcomesAdd > MAX_NUM_OUTCOMES) revert Errors.RegistryExceedMaxNames(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + for (uint256 i = 0; i < lenOutcomesAdd; ++i) { + string memory name = outcomeNamesToAdd[i]; + string memory imageUri = outcomeImageUrisToAdd[i]; + uint256 lenName = bytes(name).length; + if (lenName == 0) revert Errors.RegistryEmptyName(); + if (lenName > MAX_NAME_LENGTH) revert Errors.RegistryExceedMaxNameLength(); + if (dedup.dedup[name]) revert Errors.RegistryDuplicateOutcome(); + + dedup.dedup[name] = true; + self.outcomeNames.push(name); // ._. + self.outcomeImageUris.push(imageUri); + } + } + + function isRegistered(QuestionStateV2 storage self) internal view returns (bool) { + return self.creator != address(0); + } + + function isResolved(QuestionStateV2 storage self) internal view returns (bool) { + return self.answer != EMPTY_ANSWER; + } + + function isFlagged(QuestionStateV2 storage self) internal view returns (bool) { + return self.timestampFlagExpiry != 0; + } + + function isFinalised(QuestionStateV2 storage self) internal view returns (bool) { + return self.timestampFinalise != EMPTY_TIMESTAMP_FINALISE; + } + + /** + * WTF: within the admin-configured dispute window, admin may overrideFinalise and creator/admin may refund. + */ + function isWithinDisputeWindow(QuestionStateV2 storage self, uint256 disputeWindow) internal view returns (bool) { + return self.isFinalised() + && block.timestamp < uint256(self.timestampFinalise) + disputeWindow; + } + + /** + * WTF: claim is only allowed after the admin-configured dispute window has passed. + */ + function isClaimable(QuestionStateV2 storage self, uint256 disputeWindow) internal view returns (bool) { + return self.isFinalised() + && block.timestamp >= uint256(self.timestampFinalise) + disputeWindow; + } + + function getNumOutcomes(QuestionStateV2 storage self) internal view returns (uint256) { + return self.outcomeNames.length; + } + + function getId(address creator, address oracle, string memory title, bytes memory ancillaryData) + internal + pure + returns (bytes32 questionId) + { + return keccak256(abi.encode(creator, oracle, title, ancillaryData)); + } + + function getUpdateId(bytes32 questionId, address owner) internal pure returns (bytes32 updateId) { + return keccak256(abi.encode(questionId, owner)); + } + + function modifyEnd(QuestionStateV2 storage self, uint96 timestampEndNew) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + // cannot end when there's no question + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + // to harden the contracts: timestampEnd = max(block.timestamp-1,timestampEnd) + // note: this still does not remove the issue that start can be > end and curves should be aware of this + uint96 timestampGuard = (block.timestamp - 1).toUint96(); // whether trading stops before or after timestampEnd, this guarantees it will end + if (timestampEndNew < timestampGuard) { + self.timestampEnd = timestampGuard; + } else { + self.timestampEnd = timestampEndNew; + } + } + + function resolve(QuestionStateV2 storage self, uint256 answer) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + // can resolve & re-resolve before question end + // cannot re-resolve the same answer + // cannot resolve a null-answer (outcomes are exhaustive => at least 1 winner) + // cannot re-resolve when it's already finalised + // if flagged, resolution & finalisation is frozen to allow manual intervention + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (self.isFinalised()) revert Errors.RegistryAlreadyFinalised(); + if (self.isFlagged()) revert Errors.RegistryQuestionIsFlagged(); + if (answer == EMPTY_ANSWER || answer >= 2 ** self.outcomeNames.length) revert Errors.RegistryInvalidAnswer(); + if (answer == self.answer) revert Errors.RegistrySameAnswer(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.answer = answer; + } + + function unresolve(QuestionStateV2 storage self) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + // can unresolve only before finalization & answer exists + // if flagged, resolution & finalisation is frozen to allow manual intervention + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (self.isFinalised()) revert Errors.RegistryAlreadyFinalised(); + if (!self.isResolved()) revert Errors.RegistryNotResolved(); + if (self.isFlagged()) revert Errors.RegistryQuestionIsFlagged(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.answer = EMPTY_ANSWER; + } + + function flag(QuestionStateV2 storage self) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (self.isFlagged()) revert Errors.RegistryAlreadyFlagged(); + if (self.isFinalised()) revert Errors.RegistryAlreadyFinalised(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.timestampFlagExpiry = (block.timestamp + SAFETY_PERIOD).toUint96(); + } + + function unflag(QuestionStateV2 storage self) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (!self.isFlagged()) revert Errors.RegistryNotFlagged(); + if (self.isFinalised()) revert Errors.RegistryAlreadyFinalised(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.timestampFlagExpiry = 0; + } + + function finalise(QuestionStateV2 storage self, uint256 answerChallenge) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + // cannot finalise when there's no outcome + // cannot finalise when there's no resolution + // if flagged, resolution & finalisation is frozen to allow manual intervention + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (self.isFinalised()) revert Errors.RegistryAlreadyFinalised(); + if (!self.isResolved()) revert Errors.RegistryNotResolved(); + if (self.isFlagged()) revert Errors.RegistryQuestionIsFlagged(); + if (self.answer != answerChallenge) revert Errors.RegistryAnswerDoesNotMatchCurrent(); + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.timestampFinalise = block.timestamp.toUint96(); + } + + function manuallyFinalise(QuestionStateV2 storage self, uint256 answerOverride) internal { + /// ------------------------------------------------------------ + /// CHECKS + /// ------------------------------------------------------------ + // can finalise different answer + // can finalise even when there's no resolution + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (self.isFinalised()) revert Errors.RegistryAlreadyFinalised(); + if (!self.isFlagged()) revert Errors.RegistryNotFlagged(); + if (block.timestamp < self.timestampFlagExpiry) revert Errors.RegistryManualFinaliseTooEarly(); + if (answerOverride == EMPTY_ANSWER || answerOverride >= 2 ** self.outcomeNames.length) { + revert Errors.RegistryInvalidAnswer(); + } + + /// ------------------------------------------------------------ + /// WRITE + /// ------------------------------------------------------------ + self.answer = answerOverride; + self.timestampFinalise = block.timestamp.toUint96(); + } + + /** + * WTF: admin overrides the finalised answer within the configured dispute window. + * Re-uses the same finalise timestamp so the dispute window is not extended. + */ + function overrideFinalise(QuestionStateV2 storage self, uint256 answerOverride, uint256 disputeWindow) internal { + if (!self.isRegistered()) revert Errors.RegistryNotRegistered(); + if (!self.isFinalised()) revert Errors.RegistryNotFinalised(); + if (!self.isWithinDisputeWindow(disputeWindow)) revert Errors.RegistryOverrideTooLate(); + if (answerOverride == EMPTY_ANSWER || answerOverride >= 2 ** self.outcomeNames.length) { + revert Errors.RegistryInvalidAnswer(); + } + if (answerOverride == self.answer) revert Errors.RegistrySameAnswer(); + + self.answer = answerOverride; + } +} + diff --git a/main/src/libraries/RedeemMath.sol b/main/src/libraries/RedeemMath.sol new file mode 100644 index 0000000..974ec5d --- /dev/null +++ b/main/src/libraries/RedeemMath.sol @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import "@solady/utils/FixedPointMathLib.sol"; +import "@wtf/lib/WTFMath.sol"; +import "@wtf/lib/LogExpMath.sol"; + +library RedeemMath { + struct RedeemParams { + // time factor params + uint256 timeFromStartToEnd; + uint256 timeFromStartToRedeem; + uint256 timeKink; + uint256 timeExponent; + // growth factor params + uint256 growthC1; + uint256 growthC2; + } + + using FixedPointMathLib for uint256; + using LogExpMath for uint256; + using LogExpMath for int256; + using RedeemMath for RedeemParams; + using WTFMath for *; + + uint256 public constant MINIMUM_TAX_RATE = WTFMath.WTF_ONE / 1_000; // 10 bip or 0.1% + uint256 public constant MAXIMUM_TAX_RATE = WTFMath.WTF_ONE * 9 / 10; // 90% + uint256 public constant MINIMUM_OT_PROPORTION = WTFMath.WTF_ONE / 100_000_000; // 1 bip of 1 bip + + uint256 private constant ONE_MILLION = 1e6 * WTFMath.WTF_ONE; + uint256 private constant TEN_MILLION = 1e7 * WTFMath.WTF_ONE; + + uint256 private constant ONE_POINT_TWO_FIVE = WTFMath.WTF_ONE * 125 / 100; + uint256 private constant ONE_POINT_FIVE = WTFMath.WTF_ONE * 15 / 10; + + function calGrowthFactor(RedeemParams memory self, uint256 otSupply, uint256 otDelta) + internal + pure + returns (uint256) + { + // X = otDelta/otSupply + // growthfactor = c1*e^(c2*X) + uint256 otProportion = otDelta.fullMulDivUp(WTFMath.WTF_ONE, otSupply); + if (otProportion < MINIMUM_OT_PROPORTION) { + otProportion = MINIMUM_OT_PROPORTION; + } + int256 exponent = self.growthC2.fullMulDivUp(otProportion, WTFMath.WTF_ONE).toInt256(); + uint256 result = self.growthC1.fullMulDivUp(exponent.exp().toUint256(), WTFMath.WTF_ONE); + + return result; + } + + function calSupplyFactor(uint256 otSupply) internal pure returns (uint256) { + // supply factor is a piecewise function + uint256 supplyFactor; + if (otSupply <= ONE_MILLION) { + supplyFactor = WTFMath.WTF_ONE; + } else if (otSupply <= TEN_MILLION) { + supplyFactor = ONE_POINT_TWO_FIVE; + } else { + supplyFactor = ONE_POINT_FIVE; + } + + return supplyFactor; + } + + function calTimeFactor(RedeemParams memory self) internal pure returns (uint256) { + // timefactor = (1+max(0,t-kink))^growth, t=%time passed + uint256 timePassed = self.timeFromStartToRedeem.fullMulDivUp(WTFMath.WTF_ONE, self.timeFromStartToEnd); + uint256 baseScale = WTFMath.WTF_ONE; + if (timePassed > self.timeKink) { + baseScale += timePassed - self.timeKink; + } + uint256 result = baseScale.pow(self.timeExponent); + return result; + } + + function calRedeemTaxRate(RedeemParams memory self, uint256 otSupply, uint256 otDelta) + internal + pure + returns (uint256) + { + //r = min(1,growthfactor*supplyfactor*timefactor) + uint256 growthFactor = self.calGrowthFactor(otSupply, otDelta); + uint256 supplyFactor = calSupplyFactor(otSupply); + uint256 timeFactor = self.calTimeFactor(); + uint256 rate = growthFactor.fullMulDivUp(supplyFactor, WTFMath.WTF_ONE).fullMulDivUp(timeFactor, WTFMath.WTF_ONE); + + return WTFMath.clamp(rate, MINIMUM_TAX_RATE, MAXIMUM_TAX_RATE); + } + + function newRedeemParams( + uint128 timestampStart, + uint128 timestampEnd, + uint128 timestampCurrent, + uint256 timeKink, + uint256 timeExponent, + uint256 growthC1, + uint256 growthC2 + ) internal pure returns (RedeemParams memory) { + uint256 timeFromStartToEnd; + uint256 timeFromStartToRedeem; + if (timestampEnd <= timestampStart) { + timeFromStartToEnd = 1; + timeFromStartToRedeem = 1; + } else { + timeFromStartToEnd = timestampEnd - timestampStart; + if (timestampStart < timestampCurrent) { + timeFromStartToRedeem = timestampCurrent - timestampStart; + if (timeFromStartToRedeem > timeFromStartToEnd) { + timeFromStartToRedeem = timeFromStartToEnd; // clamp to 100% to avoid reverts + } + } + } + + return RedeemParams({ + timeFromStartToEnd: timeFromStartToEnd, + timeFromStartToRedeem: timeFromStartToRedeem, + timeKink: timeKink, + timeExponent: timeExponent, + growthC1: growthC1, + growthC2: growthC2 + }); + } +} + diff --git a/main/src/libraries/StringLib.sol b/main/src/libraries/StringLib.sol new file mode 100644 index 0000000..d5ea4a5 --- /dev/null +++ b/main/src/libraries/StringLib.sol @@ -0,0 +1,661 @@ +/* + * @title String & slice utility library for Solidity contracts. + * @author Nick Johnson + * + * @dev Functionality in this library is largely implemented using an + * abstraction called a 'slice'. A slice represents a part of a string - + * anything from the entire string to a single character, or even no + * characters at all (a 0-length slice). Since a slice only has to specify + * an offset and a length, copying and manipulating slices is a lot less + * expensive than copying and manipulating the strings they reference. + * + * To further reduce gas costs, most functions on slice that need to return + * a slice modify the original one instead of allocating a new one; for + * instance, `s.split(".")` will return the text up to the first '.', + * modifying s to only contain the remainder of the string after the '.'. + * In situations where you do not want to modify the original slice, you + * can make a copy first with `.copy()`, for example: + * `s.copy().split(".")`. Try and avoid using this idiom in loops; since + * Solidity has no memory management, it will result in allocating many + * short-lived slices that are later discarded. + * + * Functions that return two slices come in two versions: a non-allocating + * version that takes the second slice as an argument, modifying it in + * place, and an allocating version that allocates and returns the second + * slice; see `nextRune` for example. + * + * Functions that have to copy string data will return strings rather than + * slices; these can be cast back to slices for further processing if + * required. + * + * For convenience, some functions are provided with non-modifying + * variants that create a new slice and return both; for instance, + * `s.splitNew('.')` leaves s unmodified, and returns two values + * corresponding to the left and right parts of the string. + */ + +pragma solidity ^0.8.0; + +library StringLib { + struct slice { + uint256 _len; + uint256 _ptr; + } + + function memcpy(uint256 dest, uint256 src, uint256 len) private pure { + // Copy word-length chunks while possible + for (; len >= 32; len -= 32) { + assembly { + mstore(dest, mload(src)) + } + dest += 32; + src += 32; + } + + // Copy remaining bytes + uint256 mask = type(uint256).max; + if (len > 0) { + mask = 256 ** (32 - len) - 1; + } + assembly { + let srcpart := and(mload(src), not(mask)) + let destpart := and(mload(dest), mask) + mstore(dest, or(destpart, srcpart)) + } + } + + /* + * @dev Returns a slice containing the entire string. + * @param self The string to make a slice from. + * @return A newly allocated slice containing the entire string. + */ + function toSlice(string memory self) internal pure returns (slice memory) { + uint256 ptr; + assembly { + ptr := add(self, 0x20) + } + return slice(bytes(self).length, ptr); + } + + /* + * @dev Returns the length of a null-terminated bytes32 string. + * @param self The value to find the length of. + * @return The length of the string, from 0 to 32. + */ + function len(bytes32 self) internal pure returns (uint256) { + uint256 ret; + if (self == 0) return 0; + if (uint256(self) & type(uint128).max == 0) { + ret += 16; + self = bytes32(uint256(self) / 0x100000000000000000000000000000000); + } + if (uint256(self) & type(uint64).max == 0) { + ret += 8; + self = bytes32(uint256(self) / 0x10000000000000000); + } + if (uint256(self) & type(uint32).max == 0) { + ret += 4; + self = bytes32(uint256(self) / 0x100000000); + } + if (uint256(self) & type(uint16).max == 0) { + ret += 2; + self = bytes32(uint256(self) / 0x10000); + } + if (uint256(self) & type(uint8).max == 0) { + ret += 1; + } + return 32 - ret; + } + + /* + * @dev Returns a slice containing the entire bytes32, interpreted as a + * null-terminated utf-8 string. + * @param self The bytes32 value to convert to a slice. + * @return A new slice containing the value of the input argument up to the + * first null. + */ + function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { + // Allocate space for `self` in memory, copy it there, and point ret at it + assembly { + let ptr := mload(0x40) + mstore(0x40, add(ptr, 0x20)) + mstore(ptr, self) + mstore(add(ret, 0x20), ptr) + } + ret._len = len(self); + } + + /* + * @dev Returns a new slice containing the same data as the current slice. + * @param self The slice to copy. + * @return A new slice containing the same data as `self`. + */ + function copy(slice memory self) internal pure returns (slice memory) { + return slice(self._len, self._ptr); + } + + /* + * @dev Copies a slice to a new string. + * @param self The slice to copy. + * @return A newly allocated string containing the slice's text. + */ + function toString(slice memory self) internal pure returns (string memory) { + string memory ret = new string(self._len); + uint256 retptr; + assembly { + retptr := add(ret, 32) + } + + memcpy(retptr, self._ptr, self._len); + return ret; + } + + /* + * @dev Returns the length in runes of the slice. Note that this operation + * takes time proportional to the length of the slice; avoid using it + * in loops, and call `slice.empty()` if you only need to know whether + * the slice is empty or not. + * @param self The slice to operate on. + * @return The length of the slice in runes. + */ + function len(slice memory self) internal pure returns (uint256 l) { + // Starting at ptr-31 means the LSB will be the byte we care about + uint256 ptr = self._ptr - 31; + uint256 end = ptr + self._len; + for (l = 0; ptr < end; l++) { + uint8 b; + assembly { + b := and(mload(ptr), 0xFF) + } + if (b < 0x80) { + ptr += 1; + } else if (b < 0xE0) { + ptr += 2; + } else if (b < 0xF0) { + ptr += 3; + } else if (b < 0xF8) { + ptr += 4; + } else if (b < 0xFC) { + ptr += 5; + } else { + ptr += 6; + } + } + } + + /* + * @dev Returns true if the slice is empty (has a length of 0). + * @param self The slice to operate on. + * @return True if the slice is empty, False otherwise. + */ + function empty(slice memory self) internal pure returns (bool) { + return self._len == 0; + } + + /* + * @dev Extracts the first rune in the slice into `rune`, advancing the + * slice to point to the next rune and returning `self`. + * @param self The slice to operate on. + * @param rune The slice that will contain the first rune. + * @return `rune`. + */ + function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { + rune._ptr = self._ptr; + + if (self._len == 0) { + rune._len = 0; + return rune; + } + + uint256 l; + uint256 b; + // Load the first byte of the rune into the LSBs of b + assembly { + b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) + } + if (b < 0x80) { + l = 1; + } else if (b < 0xE0) { + l = 2; + } else if (b < 0xF0) { + l = 3; + } else { + l = 4; + } + + // Check for truncated codepoints + if (l > self._len) { + rune._len = self._len; + self._ptr += self._len; + self._len = 0; + return rune; + } + + self._ptr += l; + self._len -= l; + rune._len = l; + return rune; + } + + /* + * @dev Returns the first rune in the slice, advancing the slice to point + * to the next rune. + * @param self The slice to operate on. + * @return A slice containing only the first rune from `self`. + */ + function nextRune(slice memory self) internal pure returns (slice memory ret) { + nextRune(self, ret); + } + + /* + * @dev Returns the keccak-256 hash of the slice. + * @param self The slice to hash. + * @return The hash of the slice. + */ + function keccak(slice memory self) internal pure returns (bytes32 ret) { + assembly { + ret := keccak256(mload(add(self, 32)), mload(self)) + } + } + + /* + * @dev Returns true if `self` starts with `needle`. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return True if the slice starts with the provided text, false otherwise. + */ + function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + if (self._ptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + return equal; + } + + /* + * @dev If `self` starts with `needle`, `needle` is removed from the + * beginning of `self`. Otherwise, `self` is unmodified. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return `self` + */ + function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { + if (self._len < needle._len) { + return self; + } + + bool equal = true; + if (self._ptr != needle._ptr) { + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + self._ptr += needle._len; + } + + return self; + } + + /* + * @dev Returns true if the slice ends with `needle`. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return True if the slice starts with the provided text, false otherwise. + */ + function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + uint256 selfptr = self._ptr + self._len - needle._len; + + if (selfptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + + return equal; + } + + /* + * @dev If `self` ends with `needle`, `needle` is removed from the + * end of `self`. Otherwise, `self` is unmodified. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return `self` + */ + function until(slice memory self, slice memory needle) internal pure returns (slice memory) { + if (self._len < needle._len) { + return self; + } + + uint256 selfptr = self._ptr + self._len - needle._len; + bool equal = true; + if (selfptr != needle._ptr) { + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + } + + return self; + } + + // Returns the memory address of the first byte of the first occurrence of + // `needle` in `self`, or the first byte after `self` if not found. + function findPtr(uint256 selflen, uint256 selfptr, uint256 needlelen, uint256 needleptr) + private + pure + returns (uint256) + { + uint256 ptr = selfptr; + uint256 idx; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask; + if (needlelen > 0) { + mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + } + + bytes32 needledata; + assembly { + needledata := and(mload(needleptr), mask) + } + + uint256 end = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { + ptrdata := and(mload(ptr), mask) + } + + while (ptrdata != needledata) { + if (ptr >= end) return selfptr + selflen; + ptr++; + assembly { + ptrdata := and(mload(ptr), mask) + } + } + return ptr; + } else { + // For long needles, use hashing + bytes32 hash; + assembly { + hash := keccak256(needleptr, needlelen) + } + + for (idx = 0; idx <= selflen - needlelen; idx++) { + bytes32 testHash; + assembly { + testHash := keccak256(ptr, needlelen) + } + if (hash == testHash) return ptr; + ptr += 1; + } + } + } + return selfptr + selflen; + } + + // Returns the memory address of the first byte after the last occurrence of + // `needle` in `self`, or the address of `self` if not found. + function rfindPtr(uint256 selflen, uint256 selfptr, uint256 needlelen, uint256 needleptr) + private + pure + returns (uint256) + { + uint256 ptr; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask; + if (needlelen > 0) { + mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + } + + bytes32 needledata; + assembly { + needledata := and(mload(needleptr), mask) + } + + ptr = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { + ptrdata := and(mload(ptr), mask) + } + + while (ptrdata != needledata) { + if (ptr <= selfptr) return selfptr; + ptr--; + assembly { + ptrdata := and(mload(ptr), mask) + } + } + return ptr + needlelen; + } else { + // For long needles, use hashing + bytes32 hash; + assembly { + hash := keccak256(needleptr, needlelen) + } + ptr = selfptr + (selflen - needlelen); + while (ptr >= selfptr) { + bytes32 testHash; + assembly { + testHash := keccak256(ptr, needlelen) + } + if (hash == testHash) return ptr + needlelen; + ptr -= 1; + } + } + } + return selfptr; + } + + /* + * @dev Modifies `self` to contain everything from the first occurrence of + * `needle` to the end of the slice. `self` is set to the empty slice + * if `needle` is not found. + * @param self The slice to search and modify. + * @param needle The text to search for. + * @return `self`. + */ + function find(slice memory self, slice memory needle) internal pure returns (slice memory) { + uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len -= ptr - self._ptr; + self._ptr = ptr; + return self; + } + + /* + * @dev Modifies `self` to contain the part of the string from the start of + * `self` to the end of the first occurrence of `needle`. If `needle` + * is not found, `self` is set to the empty slice. + * @param self The slice to search and modify. + * @param needle The text to search for. + * @return `self`. + */ + function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { + uint256 ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len = ptr - self._ptr; + return self; + } + + /* + * @dev Splits the slice, setting `self` to everything after the first + * occurrence of `needle`, and `token` to everything before it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and `token` is set to the entirety of `self`. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @param token An output parameter to which the first token is written. + * @return `token`. + */ + function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { + uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = self._ptr; + token._len = ptr - self._ptr; + if (ptr == self._ptr + self._len) { + // Not found + self._len = 0; + } else { + self._len -= token._len + needle._len; + self._ptr = ptr + needle._len; + } + return token; + } + + /* + * @dev Splits the slice, setting `self` to everything after the first + * occurrence of `needle`, and returning everything before it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and the entirety of `self` is returned. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @return The part of `self` up to the first occurrence of `delim`. + */ + function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { + split(self, needle, token); + } + + /* + * @dev Splits the slice, setting `self` to everything before the last + * occurrence of `needle`, and `token` to everything after it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and `token` is set to the entirety of `self`. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @param token An output parameter to which the first token is written. + * @return `token`. + */ + function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { + uint256 ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = ptr; + token._len = self._len - (ptr - self._ptr); + if (ptr == self._ptr) { + // Not found + self._len = 0; + } else { + self._len -= token._len + needle._len; + } + return token; + } + + /* + * @dev Splits the slice, setting `self` to everything before the last + * occurrence of `needle`, and returning everything after it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and the entirety of `self` is returned. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @return The part of `self` after the last occurrence of `delim`. + */ + function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { + rsplit(self, needle, token); + } + + /* + * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. + * @param self The slice to search. + * @param needle The text to search for in `self`. + * @return The number of occurrences of `needle` found in `self`. + */ + function count(slice memory self, slice memory needle) internal pure returns (uint256 cnt) { + uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; + while (ptr <= self._ptr + self._len) { + cnt++; + ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; + } + } + + /* + * @dev Returns True if `self` contains `needle`. + * @param self The slice to search. + * @param needle The text to search for in `self`. + * @return True if `needle` is found in `self`, false otherwise. + */ + function contains(slice memory self, slice memory needle) internal pure returns (bool) { + return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; + } + + /* + * @dev Returns a newly allocated string containing the concatenation of + * `self` and `other`. + * @param self The first slice to concatenate. + * @param other The second slice to concatenate. + * @return The concatenation of the two strings. + */ + function concat(slice memory self, slice memory other) internal pure returns (string memory) { + string memory ret = new string(self._len + other._len); + uint256 retptr; + assembly { + retptr := add(ret, 32) + } + memcpy(retptr, self._ptr, self._len); + memcpy(retptr + self._len, other._ptr, other._len); + return ret; + } + + /* + * @dev Joins an array of slices, using `self` as a delimiter, returning a + * newly allocated string. + * @param self The delimiter to use. + * @param parts A list of slices to join. + * @return A newly allocated string containing all the slices in `parts`, + * joined with `self`. + */ + function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { + if (parts.length == 0) return ""; + + uint256 length = self._len * (parts.length - 1); + for (uint256 i = 0; i < parts.length; i++) { + length += parts[i]._len; + } + + string memory ret = new string(length); + uint256 retptr; + assembly { + retptr := add(ret, 32) + } + + for (uint256 i = 0; i < parts.length; i++) { + memcpy(retptr, parts[i]._ptr, parts[i]._len); + retptr += parts[i]._len; + if (i < parts.length - 1) { + memcpy(retptr, self._ptr, self._len); + retptr += self._len; + } + } + + return ret; + } +} + diff --git a/main/src/libraries/TokenHelper.sol b/main/src/libraries/TokenHelper.sol new file mode 100644 index 0000000..cd4af1e --- /dev/null +++ b/main/src/libraries/TokenHelper.sol @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol"; +import {IERC20Metadata} from "@openzeppelin/contracts/interfaces/IERC20Metadata.sol"; +import {IERC6909, IERC6909Metadata} from "@openzeppelin/contracts/interfaces/IERC6909.sol"; +import "@wtf/lib/Errors.sol"; + +abstract contract TokenHelper { + using SafeERC20 for IERC20; + + uint256 internal constant NULL_PARENT_ID = 0; + + function _forceApprove(address collateralOrParentOt, uint256 parentTokenId, address spender, uint256 amount) + internal + { + if (parentTokenId != NULL_PARENT_ID) { + IERC6909(collateralOrParentOt).approve(spender, parentTokenId, amount); + return; + } else { + return IERC20(collateralOrParentOt).forceApprove(spender, amount); + } + } + + function _transferIn(address collateralOrParentOt, uint256 parentTokenId, address from, uint256 amount) internal { + if (amount == 0) return; + + if (parentTokenId != NULL_PARENT_ID) { + _safeTransferFrom6909(collateralOrParentOt, from, address(this), parentTokenId, amount); + return; + } else { + IERC20(collateralOrParentOt).safeTransferFrom(from, address(this), amount); + } + } + + function _transferOut(address collateralOrParentOt, uint256 parentTokenId, address to, uint256 amount) internal { + if (amount == 0) return; + + if (parentTokenId != NULL_PARENT_ID) { + return _safeTransfer6909(collateralOrParentOt, to, parentTokenId, amount); + } else { + return IERC20(collateralOrParentOt).safeTransfer(to, amount); + } + } + + function _transferFrom( + address collateralOrParentOt, + uint256 parentTokenId, + address from, + address to, + uint256 amount + ) internal { + if (amount == 0) return; + if (parentTokenId != NULL_PARENT_ID) { + return _safeTransferFrom6909(collateralOrParentOt, from, to, parentTokenId, amount); + } else { + return IERC20(collateralOrParentOt).safeTransferFrom(from, to, amount); + } + } + + function _balance(address collateralOrParentOt, uint256 parentTokenId, address owner) + internal + view + returns (uint256) + { + if (parentTokenId != NULL_PARENT_ID) { + return IERC6909(collateralOrParentOt).balanceOf(owner, parentTokenId); + } else { + return IERC20(collateralOrParentOt).balanceOf(owner); + } + } + + function _selfBalance(address collateralOrParentOt, uint256 parentTokenId) internal view returns (uint256) { + if (parentTokenId != NULL_PARENT_ID) { + return IERC6909(collateralOrParentOt).balanceOf(address(this), parentTokenId); + } else { + return IERC20(collateralOrParentOt).balanceOf(address(this)); + } + } + + function _collateralDecimals(address collateralOrParentOt, uint256 parentTokenId) internal view returns (uint8) { + if (parentTokenId != NULL_PARENT_ID) { + return IERC6909Metadata(collateralOrParentOt).decimals(parentTokenId); + } else { + return IERC20Metadata(collateralOrParentOt).decimals(); + } + } + + function _collateralName(address collateralOrParentOt, uint256 parentTokenId) + internal + view + returns (string memory) + { + if (parentTokenId != NULL_PARENT_ID) { + return IERC6909Metadata(collateralOrParentOt).name(parentTokenId); + } else { + return IERC20Metadata(collateralOrParentOt).name(); + } + } + + function _collateralSymbol(address collateralOrParentOt, uint256 parentTokenId) + internal + view + returns (string memory) + { + if (parentTokenId != NULL_PARENT_ID) { + return IERC6909Metadata(collateralOrParentOt).symbol(parentTokenId); + } else { + return IERC20Metadata(collateralOrParentOt).symbol(); + } + } + + function _safeTransfer6909(address parent, address to, uint256 id, uint256 amount) internal { + (bool success, bytes memory data) = parent.call(abi.encodeCall(IERC6909.transfer, (to, id, amount))); + require(success && (data.length == 0 || abi.decode(data, (bool))), Errors.Safe6909TransferFailed()); + } + + function _safeTransferFrom6909(address parent, address from, address to, uint256 id, uint256 amount) internal { + (bool success, bytes memory data) = parent.call(abi.encodeCall(IERC6909.transferFrom, (from, to, id, amount))); + require(success && (data.length == 0 || abi.decode(data, (bool))), Errors.Safe6909TransferFailed()); + } +} + diff --git a/main/src/libraries/WTFMath.sol b/main/src/libraries/WTFMath.sol new file mode 100644 index 0000000..9178467 --- /dev/null +++ b/main/src/libraries/WTFMath.sol @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +pragma solidity ^0.8.20; + +import "@solady/utils/FixedPointMathLib.sol"; + +library WTFMath { + error SafeCastOverflow(); + error ClampIncorrectBounds(); + + using FixedPointMathLib for uint256; + + // All multiplications and divisions are inlined. This means we need to: + // divide by ONE when multiplying and multiply by ONE when dividing + uint256 internal constant WTF_ONE = 1e18; // 1 = 18 decimal places + int256 internal constant WTF_IONE = 1e18; // 1 = 18 decimal places + uint8 internal constant WTF_DECIMALS = 18; // keep it aligned with LogExpMath & FixedPointMathLib pls + + function min(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } + + function max(uint256 a, uint256 b) internal pure returns (uint256) { + return a > b ? a : b; + } + + function min128(uint128 a, uint128 b) internal pure returns (uint128) { + return a < b ? a : b; + } + + function max128(uint128 a, uint128 b) internal pure returns (uint128) { + return a > b ? a : b; + } + + function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { + return a <= b && a >= FixedPointMathLib.fullMulDivUp(b, WTF_ONE - eps, WTF_ONE); + } + + function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { + return a >= b && a <= FixedPointMathLib.fullMulDiv(b, WTF_ONE + eps, WTF_ONE); + } + + function clamp(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256 res) { + if (lower > upper) revert ClampIncorrectBounds(); + res = x; + if (x < lower) res = lower; + else if (x > upper) res = upper; + } + + /*/////////////////////////////////////////////////////////////// + SAFE CASTS + //////////////////////////////////////////////////////////////*/ + /// @dev forked from uniswap V4 but without custom reverts + function toUint256(int256 x) internal pure returns (uint256 y) { + if (x < 0) revert SafeCastOverflow(); + y = uint256(x); + } + + function toUint96(uint256 x) internal pure returns (uint96 y) { + y = uint96(x); + if (x != y) revert SafeCastOverflow(); + } + + /// @dev forked from uniswap V4 but without custom reverts + function toUint128(uint256 x) internal pure returns (uint128 y) { + y = uint128(x); + if (x != y) revert SafeCastOverflow(); + } + + /// @dev forked from uniswap V4 but without custom reverts + function toInt256(uint256 x) internal pure returns (int256 y) { + y = int256(x); + if (y < 0) revert SafeCastOverflow(); + } + + /// @dev this is just int256(uint128(x)), which will always pass. We use this so that the compiler will yell at us if we edit the type of x + function to128Int256(uint128 x) internal pure returns (int256 y) { + assembly ("memory-safe") { + y := x + } + } +} + diff --git a/mock/MockERC20.sol b/mock/MockERC20.sol new file mode 100644 index 0000000..a79d42e --- /dev/null +++ b/mock/MockERC20.sol @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// @dev Minimal ERC20 for testing. No external imports so it compiles inside the +/// junction tree without needing node_modules packages. +contract MockERC20 { + string public name; + string public symbol; + uint8 public immutable decimals; + + uint256 public totalSupply; + + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; + + event Transfer(address indexed from, address indexed to, uint256 amount); + event Approval(address indexed owner, address indexed spender, uint256 amount); + + constructor(string memory name_, string memory symbol_, uint8 decimals_) { + name = name_; + symbol = symbol_; + decimals = decimals_; + } + + function mint(address to, uint256 amount) external { + totalSupply += amount; + balanceOf[to] += amount; + emit Transfer(address(0), to, amount); + } + + function approve(address spender, uint256 amount) external returns (bool) { + allowance[msg.sender][spender] = amount; + emit Approval(msg.sender, spender, amount); + return true; + } + + function transfer(address to, uint256 amount) external returns (bool) { + _transfer(msg.sender, to, amount); + return true; + } + + function transferFrom(address from, address to, uint256 amount) external returns (bool) { + uint256 allowed = allowance[from][msg.sender]; + if (allowed != type(uint256).max) { + require(allowed >= amount, "MockERC20: insufficient allowance"); + allowance[from][msg.sender] = allowed - amount; + } + _transfer(from, to, amount); + return true; + } + + function _transfer(address from, address to, uint256 amount) internal { + require(balanceOf[from] >= amount, "MockERC20: insufficient balance"); + balanceOf[from] -= amount; + balanceOf[to] += amount; + emit Transfer(from, to, amount); + } +} diff --git a/mock/TestProxy.sol b/mock/TestProxy.sol new file mode 100644 index 0000000..21a8f97 --- /dev/null +++ b/mock/TestProxy.sol @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// @dev Minimal non-upgradeable delegatecall proxy for testing upgradeable +/// contracts (WTFControllerV2 uses an initializer + _disableInitializers()). +contract TestProxy { + bytes32 private constant _IMPLEMENTATION_SLOT = + bytes32(uint256(keccak256("test.proxy.implementation")) - 1); + + constructor(address implementation_) { + bytes32 slot = _IMPLEMENTATION_SLOT; + assembly { + sstore(slot, implementation_) + } + } + + fallback() external payable { + bytes32 slot = _IMPLEMENTATION_SLOT; + address impl; + assembly { + impl := sload(slot) + } + assembly { + calldatacopy(0, 0, calldatasize()) + let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch result + case 0 { + revert(0, returndatasize()) + } + default { + return(0, returndatasize()) + } + } + } +}