Verified contractPartialMIT
Autopilot
Address0x1dc28eb93ef0d4fa69bb824de2c6ab00d7954a0c
- Balance
0 ETH
- Transactions
4
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,300,751
- Creation transaction
- 0x75122458bf…3520d6bbc1
- Libraries
- src/libraries/TwapLib.sol:TwapLib0x7cf6…6a2fc5src/libraries/AutopilotLib.sol:AutopilotLib0x57cf…61e182
39 files
- src/Autopilot.solmain36.9 KB
- lib/openzeppelin-contracts/contracts/access/AccessControl.sol7.04 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts/contracts/governance/TimelockController.sol16.26 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol216 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/proxy/Clones.sol14.52 KB
- lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol2.6 KB
- lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol1.34 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.96 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol997 B
- lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol819 B
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.8 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Create2.sol4.37 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol5.55 KB
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol12.13 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol879 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.66 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/IndexFactory.sol9.6 KB
- src/IndexToken.sol34.35 KB
- src/interfaces/IIndexFactory.sol3.63 KB
- src/interfaces/IUniswapV3.sol1.66 KB
- src/libraries/AutopilotLib.sol23.9 KB
- src/libraries/IndexLib.sol12.99 KB
- src/libraries/PlanLib.sol3.83 KB
- src/libraries/TwapLib.sol18.86 KB
src/Autopilot.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {IndexFactory} from "./IndexFactory.sol";
import {IndexToken} from "./IndexToken.sol";
import {Types} from "./interfaces/IIndexFactory.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {TwapLib} from "./libraries/TwapLib.sol";
import {PlanLib} from "./libraries/PlanLib.sol";
import {AutopilotLib} from "./libraries/AutopilotLib.sol";
/// @title Autopilot
/// @notice Makes an index rebalance itself with no human and no trusted bot. Installed as the index's operator,
/// it prices every component from the time-weighted average of an explicit oracle pool (Uniswap V3 or any
/// pool with the same oracle, such as Aerodrome Slipstream on Base), lets anyone trigger a due rebalance
/// (reimbursed from a per-index gas tank), verifies any caller-supplied aggregator route against the TWAP,
/// and when none is supplied swaps the leg itself through the same pools it prices from, on each pool's own
/// venue. It relays signed market-cap weight updates under the index's own WeightPolicy. It holds index
/// tokens only inside a single leg's swap and otherwise holds nothing but gas tanks.
///
/// Everything it does to an index goes through the operator hooks the index already exposes and is bounded by the
/// index's OperatorLimits (band move and width per window) and WeightPolicy (weight cap and move per window), so a
/// bug or a manipulated TWAP is bounded the same way a rogue operator key is.
contract Autopilot is ReentrancyGuard {
using SafeERC20 for IERC20;
// ------------------------------------------------------------------ types
/// @dev Per-index policy. Either trigger may be disabled with 0, not both.
struct Config {
uint32 interval; // seconds since the index's last rebalance before a time-based rebalance is due; 0 = off
uint16 driftThresholdBps; // max |current - target| weight (bps of NAV) that makes a rebalance due; 0 = off
uint16 maxSlippageBps; // band half-width around the TWAP, and the haircut on every leg's minimum output
uint32 twapWindow; // seconds of price history each TWAP averages
uint16 tipBps; // paid on top of the gas reimbursement to whoever triggers
address weightsSigner; // per-index signer for refreshWeights; address(0) uses the contract default
uint96 minLegValue; // numeraire (1e18 = $1); a rebalance is only worth sending once some leg is worth this
uint96 maxLegValue; // numeraire; the most one poke sells per leg, the rest waits for the next poke; 0 = no cap
}
/// @dev Where one component is priced. `pool` pairs the token with WETH (the hub) or with the stablecoin and is
/// validated against the pool's own token0/token1 when stored. For WETH and the stablecoin themselves
/// `pool` must be address(0): the stablecoin is always 1 and WETH prices from the chain's `stablePool`.
struct Route {
address token; // must equal the component at the same position, so stale routes are detected
address pool; // oracle pool of token/WETH or token/stablecoin
uint8 kind; // 0 concentrated liquidity (Uniswap V3 interface), 1 classic volatile (Solidly-style)
}
// -------------------------------------------------------------- constants
uint256 internal constant BPS = 10_000;
uint256 internal constant WAD = 1e18;
uint256 internal constant PAGE = 16; // indexes scanned per checkUpkeep call; keeps the view under keeper gas limits
uint256 internal constant GAS_OVERHEAD = 40_000; // base tx cost plus the reimbursement transfer
uint256 internal constant MAX_REIMBURSABLE_GAS = 4_000_000; // per poke, so a gas-burning route cannot drain a tank
uint256 internal constant MIN_PRIORITY_ALLOWANCE = 0.01 gwei; // reimbursed priority fee floor above basefee
uint256 internal constant MAX_SLIPPAGE_BPS = 5_000;
uint32 internal constant MIN_TWAP_WINDOW = 300; // shorter averages are too cheap to move on most pools
int24 internal constant MIN_DIVERGENCE_TICKS = 200; // spot may always sit about 2 percent off the TWAP
// EIP-712: domain EIP712Domain(name,version,chainId,verifyingContract) with name "Basket Autopilot", version "1"
bytes32 internal constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 internal constant WEIGHTS_TYPEHASH =
keccak256("WeightsUpdate(address index,uint16[] weightsBps,uint256 deadline,uint256 nonce)");
// isDue reasons. 1..4 mean due; 10 and up explain why not. Mirrored in the app and the bot.
uint8 internal constant DUE_INTERVAL = 1;
uint8 internal constant DUE_THRESHOLD = 2;
uint8 internal constant DUE_BOTH = 3;
uint8 internal constant DUE_CONTINUING = 4; // a sliced rebalance is open; the next poke continues it
uint8 internal constant NOT_ENROLLED = 10;
uint8 internal constant PAUSED = 11;
uint8 internal constant NOT_OPERATOR = 12;
uint8 internal constant AUCTIONS_ACTIVE = 13;
uint8 internal constant ROUTES_STALE = 14;
uint8 internal constant PRICE_UNAVAILABLE = 15;
uint8 internal constant NAV_ZERO = 16;
uint8 internal constant NOT_TRIGGERED = 17;
uint8 internal constant BELOW_INDEX_THRESHOLD = 18;
uint8 internal constant NO_LEGS = 19;
uint8 internal constant BAND_MOVE_EXCEEDS_LIMITS = 20;
uint8 internal constant PRICE_DIVERGED = 21;
uint8 internal constant NOT_WORTH_TRADING = 22; // due, but every planned leg is below minLegValue
uint8 internal constant NOTHING_FILLABLE = 23; // due, but every leg is capped to zero by its pools' liquidity
// ------------------------------------------------------------- immutables
bytes32 public immutable DOMAIN_SEPARATOR;
IndexFactory public immutable factory;
address public immutable weth;
address public immutable stable;
uint8 public immutable wethDecimals;
uint8 public immutable stableDecimals;
// ---------------------------------------------------------------- storage
address public owner;
address public pendingOwner;
address public defaultWeightsSigner;
address public stablePool; // the WETH/stablecoin oracle pool behind every WETH-denominated price
uint8 public stablePoolKind; // pool kind of stablePool (see Route.kind)
/// @notice The router used to swap through a pool, keyed by the pool's factory. Set by the owner; a router
/// must also be an allowed swap target on the index factory before Autopilot will call it.
mapping(address => AutopilotLib.Venue) public venue;
address internal _active; // the index whose poke is executing; only it may call executeLeg
mapping(address => bool) public enrolled;
mapping(address => address) public configOwner;
mapping(address => bool) public paused;
mapping(address => uint256) public tank;
mapping(address => uint256) public weightNonce;
mapping(address => Config) public config;
mapping(address => Route[]) internal _routes;
address[] internal _enrolledList;
mapping(address => uint256) internal _listPos; // position + 1
/// @notice Pool factories whose pools may set prices, stored as kind + 1 (0 = not allowed). A route's pool
/// must name an allowed factory of its kind and that factory must confirm it. Removing a factory
/// blocks new routes through its pools; routes already stored keep pricing until re-set.
mapping(address => uint8) public oracleFactory;
// ----------------------------------------------------------------- events
event OwnershipTransferStarted(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event DefaultWeightsSignerSet(address indexed signer);
event StablePoolSet(address indexed pool, uint8 kind);
event VenueSet(address indexed factory, address router, uint8 style);
event OracleFactorySet(address indexed factory, uint8 kind, bool allowed);
event Enrolled(address indexed index, address indexed configOwner);
event Unenrolled(address indexed index);
event ConfigOwnerTransferred(address indexed index, address indexed from, address indexed to);
event ConfigSet(address indexed index, Config config);
event RoutesSet(address indexed index);
event PausedSet(address indexed index, bool paused);
event Funded(address indexed index, address indexed from, uint256 amount);
event Withdrawn(address indexed index, address indexed to, uint256 amount);
event Poked(address indexed index, address indexed caller, uint8 reason, uint256 legs, uint256 reimbursed);
event WeightsRefreshed(address indexed index, uint256 indexed nonce, uint16[] weightsBps, uint256 reimbursed);
// ----------------------------------------------------------------- errors
error NotOwner();
error NotAuthorized();
error ZeroAddress();
error NotIndex();
error NotOperator();
error AlreadyEnrolled();
error NotEnrolled();
error BadConfig();
error SlippageExceedsOperatorLimit();
error BadPool(address token);
error LengthMismatch();
error RoutesStale();
error NotDue(uint8 reason);
error BadSwapTarget();
error BadSignature();
error Expired();
error PriceUnavailable(address token);
error PriceDiverged(address token);
error PriceUnrepresentable();
error InsufficientTank();
error TransferFailed();
// -------------------------------------------------------------- modifiers
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
/// @dev The address that enrolled the index, or the index's live owner. Everything either of them can set is
/// bounded by limits only the index owner controls, so the enroller cannot widen the blast radius.
modifier onlyConfigOwner(address index) {
_authConfig(index);
_;
}
function _authConfig(address index) internal view {
if (msg.sender != configOwner[index] && msg.sender != IndexToken(index).owner()) revert NotAuthorized();
}
// ------------------------------------------------------------ constructor
/// @param _stablePool The WETH/stablecoin oracle pool.
/// @param _stablePoolKind Its kind (see Route.kind).
constructor(
address _factory,
address _weth,
address _stable,
address _stablePool,
uint8 _stablePoolKind,
address _defaultWeightsSigner
) {
DOMAIN_SEPARATOR = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256("Basket Autopilot"), keccak256("1"), block.chainid, address(this))
);
if (_factory == address(0) || _weth == address(0) || _stable == address(0)) revert ZeroAddress();
factory = IndexFactory(_factory);
weth = _weth;
stable = _stable;
wethDecimals = IERC20Decimals(_weth).decimals();
stableDecimals = IERC20Decimals(_stable).decimals();
owner = msg.sender;
defaultWeightsSigner = _defaultWeightsSigner;
// the hub pool's own factory is allowed so the constructor can validate it; others are added by the owner
_setOracleFactory(TwapLib.factoryOf(_stablePool), _stablePoolKind, true);
_setStablePool(_stablePool, _stablePoolKind);
}
// ------------------------------------------------------------- enrollment
/// @notice Create an index that is born on autopilot. `p.operator` must be this contract and `p.owner` must be
/// the caller, who becomes the config owner. Any ETH sent funds the index's gas tank.
/// @param minDelay 0 for an index owned by `p.owner`; otherwise the index is owned by a fresh
/// TimelockController with that delay and `p.owner` is its proposer and executor (see
/// IndexFactory.createIndexWithTimelock).
function create(Types.CreateParams calldata p, uint256 minDelay, Config calldata c, Route[] calldata routes)
external
payable
returns (address index, address timelock)
{
if (p.operator != address(this)) revert NotOperator();
// nobody may enroll an index in someone else's name and keep the config keys
if (p.owner != msg.sender) revert NotAuthorized();
// the index's own limits must admit our band width from birth; _enroll checks them against the new index
// and the whole creation reverts if they do not
if (minDelay == 0) {
index = factory.createIndex(p);
} else {
(index, timelock) = factory.createIndexWithTimelock(p, minDelay);
}
_enroll(index, msg.sender, c, routes);
_fund(index, msg.value);
}
/// @notice Put an existing index on autopilot. The index owner must have set this contract as operator first.
function enroll(address index, Config calldata c, Route[] calldata routes) external payable {
if (msg.sender != IndexToken(index).owner()) revert NotAuthorized();
_enroll(index, msg.sender, c, routes);
_fund(index, msg.value);
}
function unenroll(address index) external onlyConfigOwner(index) {
if (!enrolled[index]) revert NotEnrolled();
enrolled[index] = false;
delete config[index];
delete _routes[index];
delete paused[index];
uint256 pos = _listPos[index] - 1;
uint256 last = _enrolledList.length - 1;
if (pos != last) {
address moved = _enrolledList[last];
_enrolledList[pos] = moved;
_listPos[moved] = pos + 1;
}
_enrolledList.pop();
delete _listPos[index];
emit Unenrolled(index);
}
function setConfig(address index, Config calldata c) external onlyConfigOwner(index) {
if (!enrolled[index]) revert NotEnrolled();
_validateConfig(IndexToken(index), c);
config[index] = c;
emit ConfigSet(index, c);
}
function setRoutes(address index, Route[] calldata routes) external onlyConfigOwner(index) {
if (!enrolled[index]) revert NotEnrolled();
_storeRoutes(index, IndexToken(index).getComponents(), routes);
}
function setPaused(address index, bool p) external onlyConfigOwner(index) {
paused[index] = p;
emit PausedSet(index, p);
}
/// @notice Hand day-to-day control (config, routes, pause, tank withdrawals) to another address. The index
/// owner may always call this, so a stale enroller can be removed after an ownership transfer.
function transferConfigOwner(address index, address to) external onlyConfigOwner(index) {
if (to == address(0)) revert ZeroAddress();
emit ConfigOwnerTransferred(index, configOwner[index], to);
configOwner[index] = to;
}
// --------------------------------------------------------------- gas tank
/// @notice Top up an index's gas tank. Only the index owner or the enroller; the tank is not a public donation box.
function fund(address index) external payable {
if (!factory.isIndex(index)) revert NotIndex();
if (msg.sender != configOwner[index] && msg.sender != IndexToken(index).owner()) revert NotAuthorized();
_fund(index, msg.value);
}
function withdraw(address index, address to, uint256 amount) external onlyConfigOwner(index) nonReentrant {
if (to == address(0)) revert ZeroAddress();
if (amount > tank[index]) revert InsufficientTank();
tank[index] -= amount;
(bool ok,) = to.call{value: amount}("");
if (!ok) revert TransferFailed();
emit Withdrawn(index, to, amount);
}
// ------------------------------------------------------------- triggering
/// @notice Rebalance a due index. Anyone may call. Refreshes the index's bands to the TWAP, plans the legs,
/// executes each one against the caller's route (verified against the TWAP) or Autopilot's own swap
/// through the pools the leg's tokens price from, then reimburses the caller's gas plus the tip.
/// @param routes Empty, or one entry per planned leg in `plan` order. An entry with `target == address(0)`
/// uses Autopilot's own swap for that leg.
function poke(address index, IndexToken.SwapLeg[] calldata routes) external nonReentrant {
uint256 gasStart = gasleft();
(uint8 reason, uint256 legs) = _poke(index, routes);
_reimburse(index, gasStart, reason, legs);
}
/// @notice Chainlink Automation entry point: `performData` is the ABI-encoded index address.
function performUpkeep(bytes calldata performData) external nonReentrant {
uint256 gasStart = gasleft();
address index = abi.decode(performData, (address));
IndexToken.SwapLeg[] memory none;
(uint8 reason, uint256 legs) = _poke(index, none);
_reimburse(index, gasStart, reason, legs);
}
/// @notice Chainlink Automation check: scans one page of enrolled indexes and returns the first that is due.
/// @param checkData Optional ABI-encoded page number; empty means page 0.
function checkUpkeep(bytes calldata checkData) external view returns (bool upkeepNeeded, bytes memory performData) {
uint256 page = checkData.length >= 32 ? abi.decode(checkData, (uint256)) : 0;
uint256 start = page * PAGE;
uint256 end = start + PAGE;
uint256 n = _enrolledList.length;
if (end > n) end = n;
for (uint256 i = start; i < end; ++i) {
address index = _enrolledList[i];
(bool due,) = isDue(index);
if (due) return (true, abi.encode(index));
}
return (false, "");
}
/// @notice Relay a market-cap (or equal) weight update signed by the index's weights signer. Anyone may call;
/// the caller's gas (plus the tip) is paid back from the index's tank exactly like a poke, and an empty
/// tank never blocks the update. The index enforces its WeightPolicy (cap and per-window move), so the
/// signer is a powerless key.
function refreshWeights(address index, uint16[] calldata weightsBps, uint256 deadline, bytes calldata sig)
external
nonReentrant
{
uint256 gasStart = gasleft();
if (!enrolled[index]) revert NotEnrolled();
if (block.timestamp > deadline) revert Expired();
uint256 nonce = weightNonce[index];
bytes32 digest = _weightsDigest(index, weightsBps, deadline, nonce);
address signer = config[index].weightsSigner;
if (signer == address(0)) signer = defaultWeightsSigner;
(address recovered, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest, sig);
if (signer == address(0) || err != ECDSA.RecoverError.NoError || recovered != signer) revert BadSignature();
weightNonce[index] = nonce + 1;
IndexToken(index).setTargetWeights(weightsBps);
emit WeightsRefreshed(index, nonce, weightsBps, _payback(index, gasStart));
}
// ------------------------------------------------------------- governance
function transferOwnership(address to) external onlyOwner {
pendingOwner = to;
emit OwnershipTransferStarted(owner, to);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotAuthorized();
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
function setDefaultWeightsSigner(address signer) external onlyOwner {
defaultWeightsSigner = signer;
emit DefaultWeightsSignerSet(signer);
}
/// @notice Change the WETH/stablecoin oracle pool and its kind.
function setStablePool(address pool, uint8 kind) external onlyOwner {
_setStablePool(pool, kind);
}
/// @notice Register the router Autopilot uses to swap through pools of each factory (see AutopilotLib styles).
/// A zero router removes the venue; legs through its pools then need a keeper-supplied route.
function setVenues(address[] calldata facs, address[] calldata routers, uint8[] calldata styles)
external
onlyOwner
{
if (facs.length != routers.length || facs.length != styles.length) revert LengthMismatch();
for (uint256 i; i < facs.length; ++i) {
if (styles[i] > AutopilotLib.STYLE_CLASSIC) revert BadConfig();
venue[facs[i]] = AutopilotLib.Venue(routers[i], styles[i]);
emit VenueSet(facs[i], routers[i], styles[i]);
}
}
/// @notice One leg of Autopilot's own swap path. Callable only by the index whose poke is running, which has
/// approved exactly `amountIn` to this contract; the index itself checks what it received.
function executeLeg(address tokenIn, uint256 amountIn, uint256 minOut, address[] calldata pools) external {
if (msg.sender != _active || msg.sender == address(0)) revert NotAuthorized();
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
AutopilotLib.swapThrough(pools, tokenIn, amountIn, minOut, msg.sender, venue, address(factory));
}
/// @notice Allow or disallow a pool factory, of the given kind, as a source of pools that may set prices.
function setOracleFactory(address fac, uint8 kind, bool allowed) external onlyOwner {
_setOracleFactory(fac, kind, allowed);
}
// ------------------------------------------------------------------ views
function getRoutes(address index) external view returns (Route[] memory) {
return _routes[index];
}
function enrolledCount() external view returns (uint256) {
return _enrolledList.length;
}
function enrolledAt(uint256 i) external view returns (address) {
return _enrolledList[i];
}
/// @notice The digest the weights signer must sign for the index's current nonce.
function weightsDigest(address index, uint16[] calldata weightsBps, uint256 deadline)
external
view
returns (bytes32)
{
return _weightsDigest(index, weightsBps, deadline, weightNonce[index]);
}
/// @notice TWAP price of every component in the index's numeraire (1e18 per whole token).
function prices(address index) external view returns (uint256[] memory) {
return _prices(index, IndexToken(index).getComponents());
}
/// @notice The legs `poke` would execute right now and the TWAP price per component, each leg already capped
/// to what one poke should trade (the per-poke value cap and the pricing pools' depth, see
/// AutopilotLib.sliceLegs). Callers building aggregator routes use these sell amounts and pass them in
/// `SwapLeg.sellAmount`; the minimum output a leg must deliver is sellAmount * priceSell / 10^decSell
/// * 10^decBuy / priceBuy, less `maxSlippageBps`.
function plan(address index) external view returns (uint256[] memory px, IndexToken.RebalanceLeg[] memory legs) {
IndexToken t = IndexToken(index);
IndexToken.Component[] memory cs = t.getComponents();
TwapLib.PriceInput memory pin = _priceInput(index, cs);
px = TwapLib.priceAll(pin);
legs = AutopilotLib.sliceLegs(_execIn(index, pin, cs, px, AutopilotLib.planAt(index, cs, px).legs));
}
/// @notice The oracle pool component `i` is priced from (address(0) for the stablecoin itself, or when the
/// stored routes no longer match the components). Read its `liquidity()` and the cardinality word of
/// `slot0()` (TwapLib.cardinalityOf) to warn about thin pools (TWAP manipulation) and short histories
/// (`observe` reverts with OLD).
function poolOf(address index, uint256 i) external view returns (address) {
IndexToken.Component[] memory cs = IndexToken(index).getComponents();
if (!_routesMatch(index, cs)) return address(0);
return _poolFor(index, cs[i].token, i);
}
/// @notice Whether `poke` would succeed right now, and why or why not (see the reason constants).
function isDue(address index) public view returns (bool due, uint8 reason) {
if (!enrolled[index]) return (false, NOT_ENROLLED);
if (paused[index]) return (false, PAUSED);
IndexToken t = IndexToken(index);
if (t.operator() != address(this)) return (false, NOT_OPERATOR);
if (t.hasActiveAuctions()) return (false, AUCTIONS_ACTIVE);
IndexToken.Component[] memory cs = t.getComponents();
if (!_routesMatch(index, cs)) return (false, ROUTES_STALE);
uint256[] memory px;
try this.prices(index) returns (uint256[] memory q) {
px = q;
} catch (bytes memory err) {
bytes4 sel;
assembly {
sel := mload(add(err, 32))
}
return (false, sel == PriceDiverged.selector ? PRICE_DIVERGED : PRICE_UNAVAILABLE);
}
PlanLib.Plan memory p = AutopilotLib.planAt(index, cs, px);
if (p.nav == 0) return (false, NAV_ZERO);
Config memory c = config[index];
bool open = t.rebalanceOpen(); // a sliced rebalance in progress stays due until it completes
bool byInterval = c.interval != 0 && block.timestamp >= t.lastRebalance() + c.interval;
bool byThreshold = c.driftThresholdBps != 0 && p.maxDrift >= c.driftThresholdBps;
if (!open && !byInterval && !byThreshold) return (false, NOT_TRIGGERED);
(,, uint16 indexThreshold,) = t.rebalanceConfig();
if (p.maxDrift < indexThreshold) return (false, BELOW_INDEX_THRESHOLD);
if (p.count == 0) return (false, NO_LEGS);
AutopilotLib.ExecIn memory x = _execIn(index, _priceInput(index, cs), cs, px, p.legs);
(uint256 maxV, uint256 fillable) = AutopilotLib.legStats(x);
if (fillable == 0) return (false, NOTHING_FILLABLE);
if (maxV < c.minLegValue) return (false, NOT_WORTH_TRADING);
if (!AutopilotLib.bandsAllowed(index, cs, px, c.maxSlippageBps)) return (false, BAND_MOVE_EXCEEDS_LIMITS);
reason =
open ? DUE_CONTINUING : byInterval && byThreshold ? DUE_BOTH : byInterval ? DUE_INTERVAL : DUE_THRESHOLD;
due = true;
}
// --------------------------------------------------------------- internal
function _enroll(address index, address cfgOwner, Config calldata c, Route[] calldata routes) internal {
if (!factory.isIndex(index)) revert NotIndex();
if (enrolled[index]) revert AlreadyEnrolled();
IndexToken t = IndexToken(index);
if (t.operator() != address(this)) revert NotOperator();
_validateConfig(t, c);
_storeRoutes(index, t.getComponents(), routes);
enrolled[index] = true;
configOwner[index] = cfgOwner;
config[index] = c;
_enrolledList.push(index);
_listPos[index] = _enrolledList.length;
emit Enrolled(index, cfgOwner);
emit ConfigSet(index, c);
}
function _validateConfig(IndexToken t, Config calldata c) internal view {
if (c.interval == 0 && c.driftThresholdBps == 0) revert BadConfig();
if (c.driftThresholdBps > BPS) revert BadConfig();
if (c.maxSlippageBps == 0 || c.maxSlippageBps > MAX_SLIPPAGE_BPS) revert BadConfig();
if (c.twapWindow < MIN_TWAP_WINDOW || c.twapWindow > 7 days) revert BadConfig();
if (c.tipBps > BPS) revert BadConfig();
(, uint16 maxHalfWidthBps) = t.operatorLimits();
if (c.maxSlippageBps > maxHalfWidthBps) revert SlippageExceedsOperatorLimit();
}
/// @dev Every pool is checked against its own token0/token1: it must contain the component and pair it with
/// WETH or the stablecoin. WETH and the stablecoin carry no pool of their own.
function _storeRoutes(address index, IndexToken.Component[] memory cs, Route[] calldata routes) internal {
uint256 n = cs.length;
if (routes.length != n) revert LengthMismatch();
delete _routes[index];
for (uint256 i; i < n; ++i) {
address token = cs[i].token;
if (routes[i].token != token) revert RoutesStale();
address pool = routes[i].pool;
if (token == weth || token == stable) {
if (pool != address(0)) revert BadPool(token);
} else {
address other = _checkPool(pool, routes[i].kind, token);
if (other != weth && other != stable) revert BadPool(token);
}
_routes[index].push(routes[i]);
}
emit RoutesSet(index);
}
function _checkPool(address pool, uint8 kind, address token) internal view returns (address other) {
address fac;
(other, fac) = TwapLib.validate(pool, kind, token);
if (oracleFactory[fac] != kind + 1) revert BadPool(token);
}
function _setOracleFactory(address fac, uint8 kind, bool allowed) internal {
if (fac == address(0)) revert ZeroAddress();
if (kind > TwapLib.KIND_CLASSIC) revert BadConfig();
oracleFactory[fac] = allowed ? kind + 1 : 0;
emit OracleFactorySet(fac, kind, allowed);
}
function _setStablePool(address pool, uint8 kind) internal {
if (_checkPool(pool, kind, weth) != stable) revert BadPool(stable);
stablePool = pool;
stablePoolKind = kind;
emit StablePoolSet(pool, kind);
}
function _fund(address index, uint256 amount) internal {
if (amount == 0) return;
tank[index] += amount;
emit Funded(index, msg.sender, amount);
}
function _routesMatch(address index, IndexToken.Component[] memory cs) internal view returns (bool) {
Route[] storage rs = _routes[index];
if (rs.length != cs.length) return false;
for (uint256 i; i < cs.length; ++i) {
if (rs[i].token != cs[i].token) return false;
}
return true;
}
function _poke(address index, IndexToken.SwapLeg[] memory routes) internal returns (uint8 reason, uint256 n) {
bool due;
(due, reason) = isDue(index);
if (!due) revert NotDue(reason);
IndexToken t = IndexToken(index);
IndexToken.Component[] memory cs = t.getComponents();
TwapLib.PriceInput memory pin = _priceInput(index, cs);
uint256[] memory px = TwapLib.priceAll(pin);
(uint128[] memory lo, uint128[] memory hi) = AutopilotLib.bounds(px, config[index].maxSlippageBps);
t.setAllPriceBounds(lo, hi);
(,, IndexToken.RebalanceLeg[] memory legs) = t.previewRebalance();
n = legs.length;
if (routes.length != 0 && routes.length != n) revert LengthMismatch();
AutopilotLib.ExecIn memory x = _execIn(index, pin, cs, px, legs);
x.routes = routes;
(IndexToken.SwapLeg[] memory exec, uint256 fillable) = AutopilotLib.buildExec(x);
if (fillable == 0) revert NotDue(NOTHING_FILLABLE);
_active = index;
t.rebalanceSwap(exec);
_active = address(0);
}
function _execIn(
address index,
TwapLib.PriceInput memory pin,
IndexToken.Component[] memory cs,
uint256[] memory px,
IndexToken.RebalanceLeg[] memory legs
) internal view returns (AutopilotLib.ExecIn memory x) {
Config storage c = config[index];
x.index = index;
x.autopilot = address(this);
x.p = pin;
x.cs = cs;
x.px = px;
x.legs = legs;
x.slip = c.maxSlippageBps;
x.maxLegValue = c.maxLegValue;
x.minLegValue = c.minLegValue;
}
/// @dev Pays the caller back from the index's tank. An empty tank or a caller that cannot receive ETH never
/// blocks the rebalance; the ETH simply stays in the tank. Reimbursed gas is capped per poke and the gas
/// price is capped near the basefee, so a poker cannot drain a tank with a gas-burning route or by routing
/// the tank to a block builder through a huge priority fee. The tip is the intended incentive.
function _reimburse(address index, uint256 gasStart, uint8 reason, uint256 legs) internal {
emit Poked(index, msg.sender, reason, legs, _payback(index, gasStart));
}
/// @dev The reimbursement itself: gas since `gasStart` (capped) at the capped gas price, plus the tip, from
/// the index's tank to msg.sender. Returns what was paid (0 when the tank is empty or the caller refuses).
function _payback(address index, uint256 gasStart) internal returns (uint256 pay) {
uint256 used = gasStart - gasleft() + GAS_OVERHEAD;
if (used > MAX_REIMBURSABLE_GAS) used = MAX_REIMBURSABLE_GAS;
pay = used * _reimbursableGasPrice() * (BPS + config[index].tipBps) / BPS;
uint256 bal = tank[index];
if (pay > bal) pay = bal;
if (pay > 0) {
tank[index] = bal - pay;
(bool ok,) = msg.sender.call{value: pay}("");
if (!ok) {
tank[index] = bal;
pay = 0;
}
}
}
/// @dev tx.gasprice capped at basefee plus a priority allowance of a quarter of the basefee, at least
/// MIN_PRIORITY_ALLOWANCE (which matters on rollups where the basefee is tiny).
function _reimbursableGasPrice() internal view returns (uint256) {
uint256 allowance = block.basefee / 4;
if (allowance < MIN_PRIORITY_ALLOWANCE) allowance = MIN_PRIORITY_ALLOWANCE;
uint256 cap = block.basefee + allowance;
return tx.gasprice < cap ? tx.gasprice : cap;
}
// --------------------------------------------------------------- pricing
/// @dev Numeraire (1e18 per whole token) for every component from the TWAP of the pool its route names; the
/// arithmetic lives in TwapLib.priceAll (external library) to keep this contract under the size limit.
function _prices(address index, IndexToken.Component[] memory cs) internal view returns (uint256[] memory) {
return TwapLib.priceAll(_priceInput(index, cs));
}
/// @dev The pricing inputs for `index`: each component's pool and kind from its routes, the hubs, and the
/// window and divergence limit from its config.
function _priceInput(address index, IndexToken.Component[] memory cs)
internal
view
returns (TwapLib.PriceInput memory p)
{
uint256 n = cs.length;
Route[] storage rs = _routes[index];
if (rs.length != n) revert RoutesStale();
Config storage cfg = config[index];
// a pool whose spot sits more than twice the slippage (at least about 2 percent) off its own average is
// being moved or manipulated; refuse to price from it until it settles
int24 maxDelta = int24(uint24(cfg.maxSlippageBps)) * 2;
if (maxDelta < MIN_DIVERGENCE_TICKS) maxDelta = MIN_DIVERGENCE_TICKS;
p.tokens = new address[](n);
p.pools = new address[](n);
p.kinds = new uint8[](n);
p.decimals = new uint8[](n);
for (uint256 i; i < n; ++i) {
if (rs[i].token != cs[i].token) revert RoutesStale();
p.tokens[i] = cs[i].token;
p.pools[i] = rs[i].pool;
p.kinds[i] = rs[i].kind;
p.decimals[i] = cs[i].decimals;
}
p.weth = weth;
p.stable = stable;
p.wethDecimals = wethDecimals;
p.stableDecimals = stableDecimals;
p.stablePool = stablePool;
p.stablePoolKind = stablePoolKind;
p.window = cfg.twapWindow;
p.maxDelta = maxDelta;
}
function _poolFor(address index, address token, uint256 i) internal view returns (address) {
if (token == stable) return address(0);
if (token == weth) return stablePool;
return _routes[index][i].pool;
}
function _weightsDigest(address index, uint16[] calldata weightsBps, uint256 deadline, uint256 nonce)
internal
view
returns (bytes32)
{
uint16[] memory w = weightsBps;
bytes32 structHash =
keccak256(abi.encode(WEIGHTS_TYPEHASH, index, keccak256(abi.encodePacked(w)), deadline, nonce));
return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
}
}
interface IERC20Decimals {
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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);
_;
}
/// @inheritdoc ERC165
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) {
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) {
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).
*
* Emits a {RoleRevoked} event if the calling account had `role` and this call successfully revoked it.
*
* 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 {
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) {
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) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts/contracts/governance/TimelockController.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (governance/TimelockController.sol)
pragma solidity ^0.8.20;
import {AccessControl} from "../access/AccessControl.sol";
import {ERC721Holder} from "../token/ERC721/utils/ERC721Holder.sol";
import {ERC1155Holder} from "../token/ERC1155/utils/ERC1155Holder.sol";
import {Address} from "../utils/Address.sol";
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*/
contract TimelockController is AccessControl, ERC721Holder, ERC1155Holder {
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
uint256 internal constant DONE_TIMESTAMP = uint256(1);
mapping(bytes32 id => uint256) private _timestamps;
uint256 private _minDelay;
enum OperationState {
Unset,
Waiting,
Ready,
Done
}
/**
* @dev Mismatch between the parameters length for an operation call.
*/
error TimelockInvalidOperationLength(uint256 targets, uint256 payloads, uint256 values);
/**
* @dev The schedule operation doesn't meet the minimum delay.
*/
error TimelockInsufficientDelay(uint256 delay, uint256 minDelay);
/**
* @dev The current state of an operation is not as required.
* The `expectedStates` is a bitmap with the bits enabled for each OperationState enum position
* counting from right to left.
*
* See {_encodeStateBitmap}.
*/
error TimelockUnexpectedOperationState(bytes32 operationId, bytes32 expectedStates);
/**
* @dev The predecessor to an operation not yet done.
*/
error TimelockUnexecutedPredecessor(bytes32 predecessorId);
/**
* @dev The caller account is not authorized.
*/
error TimelockUnauthorizedCaller(address caller);
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when new proposal is scheduled with non-zero salt.
*/
event CallSalt(bytes32 indexed id, bytes32 salt);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with the following parameters:
*
* - `minDelay`: initial minimum delay in seconds for operations
* - `proposers`: accounts to be granted proposer and canceller roles
* - `executors`: accounts to be granted executor role
* - `admin`: optional account to be granted admin role; disable with zero address
*
* IMPORTANT: The optional admin can aid with initial configuration of roles after deployment
* without being subject to delay, but this role should be subsequently renounced in favor of
* administration through timelocked proposals. Previous versions of this contract would assign
* this admin to the deployer automatically and should be renounced as well.
*/
constructor(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) {
// self administration
_grantRole(DEFAULT_ADMIN_ROLE, address(this));
// optional admin
if (admin != address(0)) {
_grantRole(DEFAULT_ADMIN_ROLE, admin);
}
// register proposers and cancellers
for (uint256 i = 0; i < proposers.length; ++i) {
_grantRole(PROPOSER_ROLE, proposers[i]);
_grantRole(CANCELLER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_grantRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable virtual {}
/// @inheritdoc AccessControl
function supportsInterface(
bytes4 interfaceId
) public view virtual override(AccessControl, ERC1155Holder) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev Returns whether an id corresponds to a registered operation. This
* includes both Waiting, Ready, and Done operations.
*/
function isOperation(bytes32 id) public view returns (bool) {
return getOperationState(id) != OperationState.Unset;
}
/**
* @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready".
*/
function isOperationPending(bytes32 id) public view returns (bool) {
OperationState state = getOperationState(id);
return state == OperationState.Waiting || state == OperationState.Ready;
}
/**
* @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending".
*/
function isOperationReady(bytes32 id) public view returns (bool) {
return getOperationState(id) == OperationState.Ready;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view returns (bool) {
return getOperationState(id) == OperationState.Done;
}
/**
* @dev Returns the timestamp at which an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256) {
return _timestamps[id];
}
/**
* @dev Returns operation state.
*/
function getOperationState(bytes32 id) public view virtual returns (OperationState) {
uint256 timestamp = getTimestamp(id);
if (timestamp == 0) {
return OperationState.Unset;
} else if (timestamp == DONE_TIMESTAMP) {
return OperationState.Done;
} else if (timestamp > block.timestamp) {
return OperationState.Waiting;
} else {
return OperationState.Ready;
}
}
/**
* @dev Returns the minimum delay in seconds for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32) {
return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits {CallSalt} if salt is nonzero, and {CallScheduled}.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
if (salt != bytes32(0)) {
emit CallSalt(id, salt);
}
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
if (targets.length != values.length || targets.length != payloads.length) {
revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
}
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
}
if (salt != bytes32(0)) {
emit CallSalt(id, salt);
}
}
/**
* @dev Schedule an operation that is to become valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
if (isOperation(id)) {
revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Unset));
}
uint256 minDelay = getMinDelay();
if (delay < minDelay) {
revert TimelockInsufficientDelay(delay, minDelay);
}
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'canceller' role.
*/
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
if (!isOperationPending(id)) {
revert TimelockUnexpectedOperationState(
id,
_encodeStateBitmap(OperationState.Waiting) | _encodeStateBitmap(OperationState.Ready)
);
}
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute a ready operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
// thus any modifications to the operation during reentrancy should be caught.
// slither-disable-next-line reentrancy-eth
function execute(
address target,
uint256 value,
bytes calldata payload,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, payload, predecessor, salt);
_beforeCall(id, predecessor);
_execute(target, value, payload);
emit CallExecuted(id, 0, target, value, payload);
_afterCall(id);
}
/**
* @dev Execute a ready operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
// thus any modifications to the operation during reentrancy should be caught.
// slither-disable-next-line reentrancy-eth
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
if (targets.length != values.length || targets.length != payloads.length) {
revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
}
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
address target = targets[i];
uint256 value = values[i];
bytes calldata payload = payloads[i];
_execute(target, value, payload);
emit CallExecuted(id, i, target, value, payload);
}
_afterCall(id);
}
/**
* @dev Execute an operation's call.
*/
function _execute(address target, uint256 value, bytes calldata data) internal virtual {
(bool success, bytes memory returndata) = target.call{value: value}(data);
Address.verifyCallResult(success, returndata);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
if (!isOperationReady(id)) {
revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
}
if (predecessor != bytes32(0) && !isOperationDone(predecessor)) {
revert TimelockUnexecutedPredecessor(predecessor);
}
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
if (!isOperationReady(id)) {
revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
}
_timestamps[id] = DONE_TIMESTAMP;
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) public virtual {
address sender = _msgSender();
if (sender != address(this)) {
revert TimelockUnauthorizedCaller(sender);
}
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
/**
* @dev Encodes a `OperationState` into a `bytes32` representation where each bit enabled corresponds to
* the underlying position in the `OperationState` enum. For example:
*
* 0x000...1000
* ^^^^^^----- ...
* ^---- Done
* ^--- Ready
* ^-- Waiting
* ^- Unset
*/
function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) {
return bytes32(1 << uint8(operationState));
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol
// 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";
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/Clones.sol)
pragma solidity ^0.8.20;
import {Create2} from "../utils/Create2.sol";
import {Errors} from "../utils/Errors.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*/
library Clones {
error CloneArgumentsTooLong();
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
*
* This function uses the create opcode, which should never revert.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function clone(address implementation) internal returns (address instance) {
return clone(implementation, 0);
}
/**
* @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
* to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function clone(address implementation, uint256 value) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
assembly ("memory-safe") {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(value, 0x09, 0x37)
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple times will revert, since
* the clones cannot be deployed twice at the same address.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
return cloneDeterministic(implementation, salt, 0);
}
/**
* @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
* a `value` parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneDeterministic(
address implementation,
bytes32 salt,
uint256 value
) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
assembly ("memory-safe") {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(value, 0x09, 0x37, salt)
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
* immutable arguments. These are provided through `args` and cannot be changed after deployment. To
* access the arguments within the implementation, use {fetchCloneArgs}.
*
* This function uses the create opcode, which should never revert.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {
return cloneWithImmutableArgs(implementation, args, 0);
}
/**
* @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`
* parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneWithImmutableArgs(
address implementation,
bytes memory args,
uint256 value
) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
assembly ("memory-safe") {
instance := create(value, add(bytecode, 0x20), mload(bytecode))
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
* immutable arguments. These are provided through `args` and cannot be changed after deployment. To
* access the arguments within the implementation, use {fetchCloneArgs}.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same
* `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice
* at the same address.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneDeterministicWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt
) internal returns (address instance) {
return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);
}
/**
* @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],
* but with a `value` parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneDeterministicWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt,
uint256 value
) internal returns (address instance) {
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
return Create2.deploy(value, salt, bytecode);
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
*/
function predictDeterministicAddressWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
return Create2.computeAddress(salt, keccak256(bytecode), deployer);
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
*/
function predictDeterministicAddressWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));
}
/**
* @dev Get the immutable args attached to a clone.
*
* - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this
* function will return an empty array.
* - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or
* `cloneDeterministicWithImmutableArgs`, this function will return the args array used at
* creation.
* - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This
* function should only be used to check addresses that are known to be clones.
*/
function fetchCloneArgs(address instance) internal view returns (bytes memory) {
bytes memory result = new bytes(instance.code.length - 0x2d); // revert if length is too short
assembly ("memory-safe") {
extcodecopy(instance, add(result, 0x20), 0x2d, mload(result))
}
return result;
}
/**
* @dev Helper that prepares the initcode of the proxy with immutable args.
*
* An assembly variant of this function requires copying the `args` array, which can be efficiently done using
* `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using
* abi.encodePacked is more expensive but also more portable and easier to review.
*
* NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.
* With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.
*/
function _cloneCodeWithImmutableArgs(
address implementation,
bytes memory args
) private pure returns (bytes memory) {
if (args.length > 0x5fd3) revert CloneArgumentsTooLong();
return
abi.encodePacked(
hex"61",
uint16(args.length + 0x2d),
hex"3d81600a3d39f3363d3d373d3d3d363d73",
implementation,
hex"5af43d82803e903d91602b57fd5bf3",
args
);
}
}
lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC-1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.20;
import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
/**
* @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*
* @custom:stateless
*/
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens 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 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens 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 account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* 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 account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* 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 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.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 Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
bytes4 selector = IERC20Metadata.decimals.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
decimals := mul(success, mload(0x00))
}
}
/**
* @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 approve
* @param bubble Behavior switch if the approve 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)
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity >=0.5.0;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
* {IERC721-setApprovalForAll}.
*
* @custom:stateless
*/
abstract contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
return this.onERC721Received.selector;
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bool success = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
bool success = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
bool success = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Create2.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Create2.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev There's no code to deploy.
*/
error Create2EmptyBytecode();
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (bytecode.length == 0) {
revert Create2EmptyBytecode();
}
assembly ("memory-safe") {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
if (addr == address(0)) {
if (LowLevelCall.returnDataSize() == 0) {
revert Errors.FailedDeployment();
} else {
LowLevelCall.bubbleRevert();
}
}
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
assembly ("memory-safe") {
let ptr := mload(0x40) // Get free memory pointer
// | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |
// |---------------------|---------------------------------------------------------------------------|
// | bytecodeHash | CCCCCCCCCCCCC...CC |
// | salt | BBBBBBBBBBBBB...BB |
// | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |
// | 0xFF | FF |
// |---------------------|---------------------------------------------------------------------------|
// | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
// | keccak(start, 0x55) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
mstore8(start, 0xff)
addr := and(keccak256(start, 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature is invalid.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
*
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
* formats. Returns (0,0,0) for invalid signatures.
*
* For 64-byte signatures, `v` is automatically normalized to 27 or 28.
* For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
*
* Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
*/
function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch mload(signature)
// - case 65: r,s,v signature (standard)
case 65 {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Variant of {parse} that takes a signature in calldata
*/
function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch signature.length
// - case 65: r,s,v signature (standard)
case 65 {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
r := calldataload(signature.offset)
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError err, bytes32 errorArg) private pure {
if (err == RecoverError.NoError) {
return; // no error: do nothing
} else if (err == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (err == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (err == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.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) {
unchecked {
// (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 buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 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 first 16 bytes (most significant half).
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));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.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 a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a 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 A 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))
}
}
}
src/IndexFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {TimelockController} from "@openzeppelin/contracts/governance/TimelockController.sol";
import {IndexToken} from "./IndexToken.sol";
import {Types, IIndexFactory} from "./interfaces/IIndexFactory.sol";
/// @title IndexFactory
/// @notice Permissionless deployer for IndexToken. Anyone can create an index; the factory only holds the
/// protocol fee split, the protocol's own annual fee (one default for indexes a recognized Autopilot runs,
/// one for indexes the maker runs, overridable per index), the fee caps that every index must respect, and
/// the whitelist of swap targets (aggregators and AMM routers) that indexes and the zap may route through.
contract IndexFactory is IIndexFactory {
/// @notice IndexToken logic contract; every index is an EIP-1167 clone of it.
address public immutable implementation;
address public owner;
address public pendingOwner;
address public override protocolFeeRecipient;
uint16 public override protocolFeeShareBps; // share of each index's fees routed to the protocol
uint16 public override maxMintFeeBps;
uint16 public override maxTvlFeeBps;
/// @notice Annual fee every index pays the protocol as share dilution (bps of supply per year), on top of the
/// maker's own annual fee. Overridable per index by the protocol owner, up or down.
uint16 public protocolTvlFeeBps; // the manual rate: indexes whose operator is not a recognized Autopilot
/// @notice The protocol's annual fee for indexes run by a recognized Autopilot (their operator is one).
uint16 public protocolTvlFeeAutopilotBps;
mapping(address => uint32) private _protocolTvlFeeOverride; // 0 = none; otherwise bps + 1
/// @notice Autopilot contracts the protocol recognizes (every version it has placed on this chain).
mapping(address => bool) public isAutopilot;
address[] public allIndexes;
mapping(address => bool) public override isIndex;
mapping(address => bool) public override isSwapTarget;
event IndexCreated(address indexed index, address indexed creator, string name, string symbol, address[] tokens);
event TimelockDeployed(address indexed index, address indexed timelock, uint256 minDelay);
event ProtocolFeeSet(address recipient, uint16 shareBps);
event FeeCapsSet(uint16 maxMintFeeBps, uint16 maxTvlFeeBps);
event ProtocolTvlFeeSet(uint16 bps);
event ProtocolTvlFeeAutopilotSet(uint16 bps);
event AutopilotSet(address indexed autopilot, bool recognized);
event ProtocolTvlFeeOverrideSet(address indexed index, uint16 bps, bool enabled);
event SwapTargetSet(address indexed target, bool allowed);
event OwnershipTransferStarted(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
error NotOwner();
error NotAuthorized();
error ZeroAddress();
error BadBps();
error BadDelay();
error NotIndex();
uint256 public constant MIN_TIMELOCK_DELAY = 1 hours;
uint256 public constant MAX_TIMELOCK_DELAY = 30 days;
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
constructor(
address _owner,
address _protocolFeeRecipient,
uint16 _protocolFeeShareBps,
uint16 _protocolTvlFeeBps,
uint16 _protocolTvlFeeAutopilotBps
) {
if (_owner == address(0) || _protocolFeeRecipient == address(0)) {
revert ZeroAddress();
}
if (_protocolFeeShareBps > 5_000 || _protocolTvlFeeBps > 10_000 || _protocolTvlFeeAutopilotBps > 10_000) {
revert BadBps();
}
owner = _owner;
protocolFeeRecipient = _protocolFeeRecipient;
protocolFeeShareBps = _protocolFeeShareBps;
protocolTvlFeeBps = _protocolTvlFeeBps;
protocolTvlFeeAutopilotBps = _protocolTvlFeeAutopilotBps;
maxMintFeeBps = 500; // 5%
maxTvlFeeBps = 1_000; // 10% / year
implementation = address(new IndexToken());
}
/// @notice Deploy a new index owned by `p.owner`. Permissionless.
function createIndex(Types.CreateParams calldata p) external returns (address index) {
index = _create(p, p.owner);
}
/// @notice Deploy a new index owned by a fresh TimelockController. `p.owner` is its sole proposer and
/// executor, so every owner-only change (weights, fees, components, config) waits `minDelay`
/// seconds. The operator and fee recipient in `p` are unaffected.
function createIndexWithTimelock(Types.CreateParams calldata p, uint256 minDelay)
external
returns (address index, address timelock)
{
if (p.owner == address(0)) revert ZeroAddress();
if (minDelay < MIN_TIMELOCK_DELAY || minDelay > MAX_TIMELOCK_DELAY) revert BadDelay();
address[] memory who = new address[](1);
who[0] = p.owner;
timelock = address(new TimelockController(minDelay, who, who, address(0)));
index = _create(p, timelock);
emit TimelockDeployed(index, timelock, minDelay);
}
function _create(Types.CreateParams calldata p, address indexOwner) internal returns (address index) {
index = Clones.clone(implementation);
IndexToken(index).initialize(p, address(this), indexOwner);
isIndex[index] = true;
allIndexes.push(index);
emit IndexCreated(index, msg.sender, p.name, p.symbol, p.tokens);
}
function indexCount() external view returns (uint256) {
return allIndexes.length;
}
function getAllIndexes() external view returns (address[] memory) {
return allIndexes;
}
// ------------------------------------------------------------- governance
function setProtocolFee(address recipient, uint16 shareBps) external onlyOwner {
if (recipient == address(0)) revert ZeroAddress();
if (shareBps > 5_000) revert BadBps();
protocolFeeRecipient = recipient;
protocolFeeShareBps = shareBps;
emit ProtocolFeeSet(recipient, shareBps);
}
/// @notice Default annual fee an index pays the protocol when its operator is not a recognized Autopilot (the
/// maker manages it). Applies from the next fee accrual on. No cap beyond the arithmetic maximum.
function setProtocolTvlFee(uint16 bps) external onlyOwner {
if (bps > 10_000) revert BadBps();
protocolTvlFeeBps = bps;
emit ProtocolTvlFeeSet(bps);
}
/// @notice Default annual fee an index pays the protocol while a recognized Autopilot is its operator.
function setProtocolTvlFeeAutopilot(uint16 bps) external onlyOwner {
if (bps > 10_000) revert BadBps();
protocolTvlFeeAutopilotBps = bps;
emit ProtocolTvlFeeAutopilotSet(bps);
}
/// @notice Recognize (or stop recognizing) an Autopilot contract. Every version the protocol has placed should
/// stay recognized, so indexes still on an older one keep paying the autopilot rate.
function setAutopilot(address autopilot, bool recognized) external onlyOwner {
if (autopilot == address(0)) revert ZeroAddress();
isAutopilot[autopilot] = recognized;
emit AutopilotSet(autopilot, recognized);
}
/// @notice Set (`enabled`) or clear a per-index protocol annual fee, above or below the default.
function setProtocolTvlFeeFor(address index, uint16 bps, bool enabled) external onlyOwner {
if (!isIndex[index]) revert NotIndex();
if (bps > 10_000) revert BadBps();
_protocolTvlFeeOverride[index] = enabled ? uint32(bps) + 1 : 0;
emit ProtocolTvlFeeOverrideSet(index, bps, enabled);
}
/// @notice The per-index override, if any.
function protocolTvlFeeOverride(address index) external view returns (uint16 bps, bool enabled) {
uint32 v = _protocolTvlFeeOverride[index];
if (v == 0) return (0, false);
return (uint16(v - 1), true);
}
/// @inheritdoc IIndexFactory
function protocolTvlFeeFor(address index) external view override returns (uint16) {
uint32 v = _protocolTvlFeeOverride[index];
if (v != 0) return uint16(v - 1);
if (isIndex[index] && isAutopilot[IndexToken(index).operator()]) return protocolTvlFeeAutopilotBps;
return protocolTvlFeeBps;
}
/// @dev Caps apply to new fee settings. Existing indexes keep their current fees until changed.
function setFeeCaps(uint16 _maxMintFeeBps, uint16 _maxTvlFeeBps) external onlyOwner {
if (_maxMintFeeBps > 2_000 || _maxTvlFeeBps > 2_000) revert BadBps();
maxMintFeeBps = _maxMintFeeBps;
maxTvlFeeBps = _maxTvlFeeBps;
emit FeeCapsSet(_maxMintFeeBps, _maxTvlFeeBps);
}
/// @notice Allow or disallow a router or aggregator as a swap target for every index and the zap.
function setSwapTarget(address target, bool allowed) external onlyOwner {
if (target == address(0)) revert ZeroAddress();
isSwapTarget[target] = allowed;
emit SwapTargetSet(target, allowed);
}
function transferOwnership(address to) external onlyOwner {
pendingOwner = to;
emit OwnershipTransferStarted(owner, to);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotAuthorized();
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
}
src/IndexToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Types, IIndexFactory} from "./interfaces/IIndexFactory.sol";
import {IndexLib} from "./libraries/IndexLib.sol";
/// @title IndexToken
/// @notice An ERC-20 that is 1:1 redeemable for a basket of tokens held by the contract.
///
/// Design:
/// - Mint and redeem are in-kind and pro-rata. No price oracle is needed to issue or redeem.
/// - Fees are taken as share dilution (mint fee + annual TVL fee), split between the index creator and the protocol.
/// - Rebalancing is oracle-free: when a rebalance opens, the contract pairs over-weight tokens with under-weight
/// tokens and runs Dutch auctions. Each auction starts at the price most favorable to the vault (derived from
/// creator-set per-token price bounds) and decays linearly to the least favorable. Anyone can fill.
/// - The creator chooses the rebalance interval, drift threshold, auction length, and whether anyone can open a
/// rebalance once it is due (auto) or only the owner/operator can (manual).
/// - The planner, the auction bookkeeping, and swap-leg execution live in IndexLib, an external library this
/// contract DELEGATECALLs, so the whole index fits under the bytecode limit. Its events and errors are this
/// contract's own.
contract IndexToken is ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
// ------------------------------------------------------------------ types
struct Component {
address token;
uint8 decimals;
uint16 targetWeightBps; // 0 means "sell down to zero"
uint16 anchorWeightBps; // the target the operator's weight moves are measured against
uint128 priceLow; // numeraire (1e18) per whole token
uint128 priceHigh;
}
struct Auction {
address sellToken;
address buyToken;
uint128 sellRemaining; // raw sellToken units still for sale
uint128 startRate; // buy raw units per 1e18 sell raw units at start (best for vault)
uint128 endRate; // at end (worst for vault)
uint40 startTime;
uint40 endTime;
}
/// @dev One planned trade: sell `sellAmount` raw units of `sellToken` for `buyToken`.
struct RebalanceLeg {
address sellToken;
address buyToken;
uint256 sellAmount;
}
/// @dev Caller-supplied execution for one planned leg, in the shape aggregator APIs return it: the vault
/// approves `spender` for exactly `sellAmount`, calls `target` with `data`, and expects the buy token to
/// land in this contract. Both addresses must be whitelisted on the factory. `sellAmount` is how much of
/// the planned leg to execute now: 0 skips the leg, anything at or above the planned amount sells all of
/// it, anything in between is a slice (see rebalanceSwap).
struct SwapLeg {
address spender;
address target;
bytes data;
uint256 minAmountOut;
uint256 sellAmount;
}
struct Plan {
uint256 nav;
uint256 maxDrift;
uint256 count;
RebalanceLeg[] legs;
uint8[] sIdx;
uint8[] bIdx;
}
/// @dev The mid the operator's moves are measured against. Re-anchored to the live mid on the operator's first
/// move after each rebalance, and to the owner's mid whenever the owner sets a band.
struct BandAnchor {
uint128 mid;
uint40 setAt;
}
// -------------------------------------------------------------- constants
uint256 public constant BPS = 10_000;
uint256 public constant WAD = 1e18;
uint256 public constant MAX_COMPONENTS = 20;
uint256 internal constant YEAR = 365 days;
uint256 internal constant DUST_VALUE = 1e15; // 0.001 numeraire units
// ---------------------------------------------------------------- storage
IIndexFactory public factory;
bool private _initialized;
string private _tokenName;
string private _tokenSymbol;
address public owner;
address public pendingOwner;
address public operator;
address public feeRecipient;
uint16 public mintFeeBps;
uint16 public tvlFeeBps;
uint256 public lastFeeAccrual;
bool public mintPaused;
Component[] public components;
mapping(address => bool) public isComponent;
/// @dev raw units backing 1e18 shares when totalSupply == 0 (bootstraps the first mint)
mapping(address => uint256) public initialUnits;
Types.RebalanceConfig public rebalanceConfig;
uint256 public lastRebalance;
uint256 public rebalanceCount;
Auction[] public auctions;
/// @notice True while a swap rebalance has executed some of its legs but the basket is still above the drift
/// threshold: the next rebalanceSwap continues it and the clock does not reset until it completes.
bool public rebalanceOpen;
Types.OperatorLimits public operatorLimits;
mapping(address => BandAnchor) public bandAnchor;
Types.WeightPolicy public weightPolicy;
// ----------------------------------------------------------------- events
event OwnershipTransferStarted(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OperatorSet(address indexed operator);
event FeeRecipientSet(address indexed recipient);
event FeesSet(uint16 mintFeeBps, uint16 tvlFeeBps);
event MintPausedSet(bool paused);
event ComponentAdded(address indexed token);
event ComponentRemoved(address indexed token);
event TargetWeightsSet(uint16[] weightsBps);
event PriceBoundsSet(address indexed token, uint128 low, uint128 high);
event InitialUnitsSet(address indexed token, uint256 units);
event RebalanceConfigSet(Types.RebalanceConfig config);
event Minted(address indexed sender, address indexed to, uint256 shares, uint256 feeShares);
event Redeemed(address indexed sender, address indexed to, uint256 shares);
event FeesAccrued(uint256 creatorShares, uint256 protocolShares);
event RebalanceOpened(uint256 indexed round, uint256 auctionCount, uint256 navWad);
event AuctionCreated(
uint256 indexed round,
uint256 indexed id,
address sellToken,
address buyToken,
uint256 sellAmount,
uint256 startRate,
uint256 endRate
);
event AuctionFilled(
uint256 indexed id, address indexed bidder, uint256 sellAmount, uint256 buyAmount, uint256 rate
);
event AuctionsCancelled();
event RebalanceSwapped(uint256 indexed round, uint256 swapCount, uint256 navWad);
event RebalancePartial(uint256 indexed round, uint256 swapCount, uint256 navWad, uint256 maxDriftBps);
event SwapExecuted(
uint256 indexed round, address indexed sellToken, address indexed buyToken, uint256 sold, uint256 bought
);
event OperatorLimitsSet(uint16 maxBandMoveBps, uint16 maxHalfWidthBps);
event WeightPolicySet(Types.WeightPolicy policy);
// ----------------------------------------------------------------- errors
error NotOwner();
error NotAuthorized();
error ZeroAddress();
error ZeroAmount();
error Paused();
error TooManyComponents();
error DuplicateToken();
error UnknownToken();
error LengthMismatch();
error WeightsMustSumToBps();
error BadPriceBounds();
error FeeTooHigh();
error Slippage();
error ComponentNotEmpty();
error SupplyNotZero();
error NotDue();
error BelowDriftThreshold();
error AuctionsActive();
error AuctionNotActive();
error RateUnrepresentable();
error BadConfig();
error AlreadyInitialized();
error BadSwapTarget();
error Overspend();
error OperatorLimitExceeded();
error TransferShortfall();
error WeightsNotDelegated();
error WeightLimitExceeded();
// -------------------------------------------------------------- modifiers
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
modifier onlyOwnerOrOperator() {
if (msg.sender != owner && msg.sender != operator) revert NotAuthorized();
_;
}
// ------------------------------------------------------- initialization
/// @dev The implementation is deployed once and cloned (EIP-1167) by the factory. Brick the implementation.
constructor() ERC20("", "") {
_initialized = true;
}
/// @param _owner Governor of the index. The factory passes `p.owner` or a freshly deployed timelock.
function initialize(Types.CreateParams calldata p, address _factory, address _owner) external {
if (_initialized) revert AlreadyInitialized();
_initialized = true;
if (_owner == address(0) || p.feeRecipient == address(0) || _factory == address(0)) revert ZeroAddress();
_tokenName = p.name;
_tokenSymbol = p.symbol;
factory = IIndexFactory(_factory);
owner = _owner;
feeRecipient = p.feeRecipient;
operator = p.operator;
uint256 n = p.tokens.length;
if (n == 0 || n > MAX_COMPONENTS) revert TooManyComponents();
if (p.weightsBps.length != n || p.initialUnits.length != n || p.priceLow.length != n || p.priceHigh.length != n)
{
revert LengthMismatch();
}
uint256 sum;
for (uint256 i; i < n; ++i) {
_addComponent(p.tokens[i], p.weightsBps[i], p.priceLow[i], p.priceHigh[i]);
initialUnits[p.tokens[i]] = p.initialUnits[i];
sum += p.weightsBps[i];
}
if (sum != BPS) revert WeightsMustSumToBps();
_setFees(p.mintFeeBps, p.tvlFeeBps);
_setRebalanceConfig(p.rebalance);
_setWeightPolicy(p.weightPolicy);
Types.OperatorLimits memory lim = p.operatorLimits;
if (lim.maxBandMoveBps == 0 && lim.maxHalfWidthBps == 0) {
lim = Types.OperatorLimits({maxBandMoveBps: 2_000, maxHalfWidthBps: 1_000});
} else if (lim.maxHalfWidthBps == 0) {
revert BadConfig();
}
_setOperatorLimits(lim);
lastFeeAccrual = block.timestamp;
lastRebalance = block.timestamp;
}
function name() public view override returns (string memory) {
return _tokenName;
}
function symbol() public view override returns (string memory) {
return _tokenSymbol;
}
// ------------------------------------------------------------------ views
function getComponents() external view returns (Component[] memory) {
return components;
}
function getAuctions() external view returns (Auction[] memory) {
return auctions;
}
/// @notice Raw units of each component required to mint `grossShares` (before mint fee).
function requiredAmounts(uint256 grossShares) public view returns (uint256[] memory amounts) {
uint256 n = components.length;
amounts = new uint256[](n);
uint256 supply = totalSupply() + _pendingFeeShares();
for (uint256 i; i < n; ++i) {
address t = components[i].token;
if (supply == 0) {
amounts[i] = Math.mulDiv(grossShares, initialUnits[t], WAD, Math.Rounding.Ceil);
} else {
amounts[i] = Math.mulDiv(grossShares, IERC20(t).balanceOf(address(this)), supply, Math.Rounding.Ceil);
}
}
}
/// @notice Gross shares that must be issued so the minter nets `netShares` after the mint fee.
function grossSharesFor(uint256 netShares) public view returns (uint256) {
return Math.mulDiv(netShares, BPS, BPS - mintFeeBps, Math.Rounding.Ceil);
}
/// @notice Raw units of each component needed so the minter nets `netShares`.
function previewMint(uint256 netShares) external view returns (uint256[] memory) {
return requiredAmounts(grossSharesFor(netShares));
}
/// @notice Raw units of each component returned for redeeming `shares`.
function previewRedeem(uint256 shares) external view returns (uint256[] memory amounts) {
uint256 n = components.length;
amounts = new uint256[](n);
uint256 supply = totalSupply() + _pendingFeeShares();
if (supply == 0) return amounts;
for (uint256 i; i < n; ++i) {
amounts[i] = Math.mulDiv(shares, IERC20(components[i].token).balanceOf(address(this)), supply);
}
}
/// @notice Maximum net shares mintable given `amounts` of each component (same order as `components`).
function maxMintable(uint256[] calldata amounts) external view returns (uint256 netShares) {
uint256 n = components.length;
if (amounts.length != n) revert LengthMismatch();
uint256 supply = totalSupply() + _pendingFeeShares();
uint256 gross = type(uint256).max;
for (uint256 i; i < n; ++i) {
address t = components[i].token;
uint256 cap;
if (supply == 0) {
uint256 u = initialUnits[t];
if (u == 0) continue;
cap = Math.mulDiv(amounts[i], WAD, u);
} else {
uint256 bal = IERC20(t).balanceOf(address(this));
if (bal == 0) continue;
cap = Math.mulDiv(amounts[i], supply, bal);
}
if (cap < gross) gross = cap;
}
if (gross == type(uint256).max) return 0;
netShares = Math.mulDiv(gross, BPS - mintFeeBps, BPS);
// guard against ceil rounding in grossSharesFor pushing requirements above `amounts`
while (netShares > 0 && grossSharesFor(netShares) > gross) netShares--;
}
/// @notice NAV in numeraire (1e18) using mid prices, plus per-component values and current weights.
function navSnapshot()
external
view
returns (uint256 navWad, uint256[] memory values, uint256[] memory currentWeightsBps)
{
uint256 n = components.length;
values = new uint256[](n);
currentWeightsBps = new uint256[](n);
for (uint256 i; i < n; ++i) {
values[i] = _value(components[i], IERC20(components[i].token).balanceOf(address(this)));
navWad += values[i];
}
if (navWad == 0) return (navWad, values, currentWeightsBps);
for (uint256 i; i < n; ++i) {
currentWeightsBps[i] = Math.mulDiv(values[i], BPS, navWad);
}
}
/// @notice Whether a rebalance can be opened right now by `caller`.
function canOpenRebalance(address caller) public view returns (bool) {
Types.RebalanceConfig memory c = rebalanceConfig;
if (c.autoRebalance) {
if (block.timestamp < lastRebalance + c.interval) return false;
} else if (caller != owner && caller != operator) {
return false;
}
return !hasActiveAuctions();
}
function hasActiveAuctions() public view returns (bool) {
return IndexLib.hasActiveAuctions(auctions);
}
/// @notice Current rate (buy raw units per 1e18 sell raw units) of auction `id`.
function currentRate(uint256 id) public view returns (uint256) {
return IndexLib.currentRate(auctions, id);
}
/// @notice Buy amount a bidder must pay right now to take `sellAmount` from auction `id`.
function quoteBid(uint256 id, uint256 sellAmount) external view returns (uint256 buyAmount) {
return Math.mulDiv(sellAmount, currentRate(id), WAD, Math.Rounding.Ceil);
}
/// @notice The exact legs `openRebalance` or `rebalanceSwap` would execute right now, in order.
/// @dev Does not enforce the drift threshold; `maxDriftBps` lets callers decide. Empty when NAV is zero.
function previewRebalance()
external
view
returns (uint256 navWad, uint256 maxDriftBps, RebalanceLeg[] memory legs)
{
Plan memory p = _planRebalance();
legs = p.legs;
uint256 count = p.count;
assembly {
mstore(legs, count)
}
return (p.nav, p.maxDrift, legs);
}
// ------------------------------------------------------------ mint/redeem
/// @notice Mint `netShares` to `to` by depositing the required pro-rata amounts of every component.
function mint(uint256 netShares, address to) external nonReentrant returns (uint256[] memory amountsIn) {
if (mintPaused) revert Paused();
if (netShares == 0) revert ZeroAmount();
if (to == address(0)) revert ZeroAddress();
_accrueFees();
uint256 gross = grossSharesFor(netShares);
amountsIn = requiredAmounts(gross);
uint256 n = components.length;
for (uint256 i; i < n; ++i) {
if (amountsIn[i] > 0) {
IndexLib.pullExact(IERC20(components[i].token), amountsIn[i]);
}
}
_mint(to, netShares);
uint256 feeShares = gross - netShares;
_distributeFeeShares(feeShares, 0);
emit Minted(msg.sender, to, netShares, feeShares);
}
/// @notice Burn `shares` and receive the pro-rata amount of every component.
function redeem(uint256 shares, address to, uint256[] calldata minAmountsOut)
external
nonReentrant
returns (uint256[] memory amountsOut)
{
if (shares == 0) revert ZeroAmount();
if (to == address(0)) revert ZeroAddress();
_accrueFees();
uint256 n = components.length;
if (minAmountsOut.length != n) revert LengthMismatch();
uint256 supply = totalSupply();
_burn(msg.sender, shares);
amountsOut = new uint256[](n);
for (uint256 i; i < n; ++i) {
IERC20 t = IERC20(components[i].token);
amountsOut[i] = Math.mulDiv(shares, t.balanceOf(address(this)), supply);
if (amountsOut[i] < minAmountsOut[i]) revert Slippage();
if (amountsOut[i] > 0) t.safeTransfer(to, amountsOut[i]);
}
emit Redeemed(msg.sender, to, shares);
}
/// @notice Accrue the TVL fee as share dilution. Public so anyone can crystallize fees.
function accrueFees() external {
_accrueFees();
}
// -------------------------------------------------------------- rebalance
/// @notice Open a rebalance round. Pairs over-weight components with under-weight ones and starts auctions.
function openRebalance() external nonReentrant {
Types.RebalanceConfig memory c = rebalanceConfig;
if (c.autoRebalance) {
if (block.timestamp < lastRebalance + c.interval) revert NotDue();
} else if (msg.sender != owner && msg.sender != operator) {
revert NotAuthorized();
}
if (hasActiveAuctions()) revert AuctionsActive();
_accrueFees();
delete auctions;
Plan memory p = _planRebalance();
_requireActionable(p);
uint256 round = ++rebalanceCount;
IndexLib.openAuctions(
auctions, components, p, round, uint40(block.timestamp), uint40(block.timestamp + c.auctionLength)
);
lastRebalance = block.timestamp;
rebalanceOpen = false;
_anchorWeights();
emit RebalanceOpened(round, p.count, p.nav);
}
/// @notice Buy up to `sellAmount` of the auction's sell token at the current Dutch-auction rate.
/// @param maxBuyAmount Revert if the bidder would have to pay more than this.
function bid(uint256 id, uint256 sellAmount, uint256 maxBuyAmount)
external
nonReentrant
returns (uint256 filled, uint256 buyAmount)
{
(filled, buyAmount) = IndexLib.bid(auctions, id, sellAmount, maxBuyAmount);
}
/// @notice Cancel all open auctions. Owner or operator.
function cancelAuctions() external onlyOwnerOrOperator {
delete auctions;
emit AuctionsCancelled();
}
/// @notice Rebalance by executing each planned leg against a whitelisted swap target (an aggregator or
/// AMM router) instead of posting Dutch auctions. Owner or operator, no interval wait.
/// @param legs One SwapLeg per planned leg, in `previewRebalance` order. Each leg must deliver at least
/// max(minAmountOut, the Dutch-auction floor for that pair) of the buy token to this contract.
/// A leg may sell less than planned (`sellAmount`, see SwapLeg): large rebalances are then done
/// in slices across several calls. The round completes, resetting the clock and the operator's
/// anchors, once every leg was executed in full or the remaining drift is at or below the drift
/// threshold; otherwise it stays open (`rebalanceOpen`) for the next call to continue.
function rebalanceSwap(SwapLeg[] calldata legs) external nonReentrant onlyOwnerOrOperator {
if (hasActiveAuctions()) revert AuctionsActive();
_accrueFees();
delete auctions;
Plan memory p = _planRebalance();
_requireActionable(p);
uint256 round = rebalanceCount + 1;
bool complete = IndexLib.executeLegs(factory, isComponent, components, p, legs, round);
uint256 driftAfter;
if (!complete) {
driftAfter = _planRebalance().maxDrift;
complete = driftAfter <= rebalanceConfig.driftThresholdBps;
}
if (complete) {
rebalanceCount = round;
lastRebalance = block.timestamp;
rebalanceOpen = false;
_anchorWeights();
emit RebalanceSwapped(round, p.count, p.nav);
} else {
rebalanceOpen = true;
emit RebalancePartial(round, p.count, p.nav, driftAfter);
}
}
// ------------------------------------------------------------- governance
function transferOwnership(address to) external onlyOwner {
pendingOwner = to;
emit OwnershipTransferStarted(owner, to);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotAuthorized();
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
/// @dev Fees are settled first so a switch between Autopilot and a manual operator is charged at the right
/// protocol rate up to the second (see IIndexFactory.protocolTvlFeeFor).
function setOperator(address op) external onlyOwner {
_accrueFees();
operator = op;
emit OperatorSet(op);
}
function setFeeRecipient(address r) external onlyOwner {
if (r == address(0)) revert ZeroAddress();
feeRecipient = r;
emit FeeRecipientSet(r);
}
function setFees(uint16 _mintFeeBps, uint16 _tvlFeeBps) external onlyOwner {
_accrueFees();
_setFees(_mintFeeBps, _tvlFeeBps);
}
function setMintPaused(bool paused) external onlyOwnerOrOperator {
mintPaused = paused;
emit MintPausedSet(paused);
}
function setRebalanceConfig(Types.RebalanceConfig calldata c) external onlyOwner {
_setRebalanceConfig(c);
}
/// @notice Cap how far and how wide the operator may set price bands per rebalance window. Owner calls to the
/// band setters are never limited; put the owner behind the timelock instead.
function setOperatorLimits(uint16 maxBandMoveBps, uint16 maxHalfWidthBps) external onlyOwner {
_setOperatorLimits(Types.OperatorLimits({maxBandMoveBps: maxBandMoveBps, maxHalfWidthBps: maxHalfWidthBps}));
}
/// @notice Choose who may maintain target weights and how far the operator may move them per window.
function setWeightPolicy(Types.WeightPolicy calldata w) external onlyOwner {
_setWeightPolicy(w);
}
/// @notice Add a component with weight 0. Call setTargetWeights afterwards to give it a target.
function addComponent(address token, uint128 low, uint128 high) external onlyOwner {
if (components.length >= MAX_COMPONENTS) revert TooManyComponents();
_addComponent(token, 0, low, high);
}
/// @notice Remove a component whose target is 0 and whose remaining balance is dust. Dust goes to feeRecipient.
function removeComponent(uint256 idx) external onlyOwner {
Component memory c = components[idx];
if (c.targetWeightBps != 0) revert ComponentNotEmpty();
uint256 bal = IERC20(c.token).balanceOf(address(this));
if (_value(c, bal) > DUST_VALUE) revert ComponentNotEmpty();
if (bal > 0) IERC20(c.token).safeTransfer(feeRecipient, bal);
isComponent[c.token] = false;
delete bandAnchor[c.token];
uint256 last = components.length - 1;
if (idx != last) components[idx] = components[last];
components.pop();
emit ComponentRemoved(c.token);
}
/// @notice Set target weights. The owner may set anything and re-anchors every component. Under an Equal or
/// MarketCap policy the operator may also set weights, bounded per component by `maxWeightBps` (when
/// nonzero) and by `maxWeightMoveBps` against the anchor, which resets after each rebalance. Under
/// Custom only the owner sets weights.
function setTargetWeights(uint16[] calldata weightsBps) external onlyOwnerOrOperator {
uint256 n = components.length;
if (weightsBps.length != n) revert LengthMismatch();
bool isOwner = msg.sender == owner;
Types.WeightPolicy storage pol = weightPolicy;
if (!isOwner && pol.scheme == Types.WeightScheme.Custom) revert WeightsNotDelegated();
uint256 sum;
for (uint256 i; i < n; ++i) {
uint16 w = weightsBps[i];
Component storage c = components[i];
if (isOwner) {
c.anchorWeightBps = w;
} else {
if (pol.maxWeightBps != 0 && w > pol.maxWeightBps) revert WeightLimitExceeded();
uint16 a = c.anchorWeightBps;
uint256 move = w > a ? w - a : a - w;
if (move > pol.maxWeightMoveBps) revert WeightLimitExceeded();
}
c.targetWeightBps = w;
sum += w;
}
if (sum != BPS) revert WeightsMustSumToBps();
emit TargetWeightsSet(weightsBps);
}
function setPriceBounds(uint256 idx, uint128 low, uint128 high) external onlyOwnerOrOperator {
_setBounds(idx, low, high);
}
function setAllPriceBounds(uint128[] calldata low, uint128[] calldata high) external onlyOwnerOrOperator {
uint256 n = components.length;
if (low.length != n || high.length != n) revert LengthMismatch();
for (uint256 i; i < n; ++i) {
_setBounds(i, low[i], high[i]);
}
}
/// @notice Set the bootstrap backing per 1e18 shares. Only meaningful while totalSupply == 0.
function setInitialUnits(address token, uint256 units) external onlyOwner {
if (totalSupply() != 0) revert SupplyNotZero();
if (!isComponent[token]) revert UnknownToken();
initialUnits[token] = units;
emit InitialUnitsSet(token, units);
}
// --------------------------------------------------------------- internal
function _addComponent(address token, uint16 weight, uint128 low, uint128 high) internal {
if (token == address(0)) revert ZeroAddress();
if (isComponent[token]) revert DuplicateToken();
if (low == 0 || high < low) revert BadPriceBounds();
uint8 dec = IERC20Metadata(token).decimals();
// 10 ** decimals must stay far inside uint256 for the rate math; no real token needs more than 36
if (dec > 36) revert BadConfig();
components.push(
Component({
token: token,
decimals: dec,
targetWeightBps: weight,
anchorWeightBps: weight,
priceLow: low,
priceHigh: high
})
);
isComponent[token] = true;
emit ComponentAdded(token);
}
function _setFees(uint16 _mintFeeBps, uint16 _tvlFeeBps) internal {
if (_mintFeeBps > factory.maxMintFeeBps() || _tvlFeeBps > factory.maxTvlFeeBps()) revert FeeTooHigh();
mintFeeBps = _mintFeeBps;
tvlFeeBps = _tvlFeeBps;
emit FeesSet(_mintFeeBps, _tvlFeeBps);
}
function _setRebalanceConfig(Types.RebalanceConfig memory c) internal {
if (c.auctionLength < 5 minutes || c.auctionLength > 7 days) revert BadConfig();
if (c.driftThresholdBps > BPS) revert BadConfig();
rebalanceConfig = c;
emit RebalanceConfigSet(c);
}
function _setWeightPolicy(Types.WeightPolicy memory w) internal {
if (w.maxWeightBps > BPS || w.maxWeightMoveBps > BPS) revert BadConfig();
weightPolicy = w;
emit WeightPolicySet(w);
}
function _setOperatorLimits(Types.OperatorLimits memory lim) internal {
if (lim.maxBandMoveBps > BPS || lim.maxHalfWidthBps > BPS) revert BadConfig();
operatorLimits = lim;
emit OperatorLimitsSet(lim.maxBandMoveBps, lim.maxHalfWidthBps);
}
/// @dev After a rebalance the current targets become the baseline for the operator's next weight moves.
function _anchorWeights() internal {
uint256 n = components.length;
for (uint256 i; i < n; ++i) {
components[i].anchorWeightBps = components[i].targetWeightBps;
}
}
/// @dev Owner sets are unrestricted and re-anchor the band. Operator sets are measured against the anchor:
/// the mid may drift at most `maxBandMoveBps` from it per rebalance window and the half-width may not
/// exceed `maxHalfWidthBps`, so a rogue operator key is bounded to roughly one band move per window.
function _setBounds(uint256 idx, uint128 low, uint128 high) internal {
if (low == 0 || high < low) revert BadPriceBounds();
Component storage c = components[idx];
uint256 newMid = (uint256(low) + high) / 2;
if (msg.sender == owner) {
bandAnchor[c.token] = BandAnchor({mid: uint128(newMid), setAt: uint40(block.timestamp)});
} else {
Types.OperatorLimits memory lim = operatorLimits;
BandAnchor memory a = bandAnchor[c.token];
uint256 base = a.mid;
if (base == 0 || a.setAt < lastRebalance) {
base = (uint256(c.priceLow) + c.priceHigh) / 2;
bandAnchor[c.token] = BandAnchor({mid: uint128(base), setAt: uint40(block.timestamp)});
}
// a limit of 10,000 means none; below that the move is measured against the larger of the two mids,
// so a doubling and a halving read the same and an honest big move cannot strand the index
if (lim.maxBandMoveBps < BPS) {
uint256 move = newMid > base ? newMid - base : base - newMid;
uint256 ref = newMid > base ? newMid : base;
if (move * BPS > ref * lim.maxBandMoveBps) revert OperatorLimitExceeded();
}
if ((uint256(high) - low) * BPS > 2 * newMid * lim.maxHalfWidthBps) revert OperatorLimitExceeded();
}
c.priceLow = low;
c.priceHigh = high;
emit PriceBoundsSet(c.token, low, high);
}
function _mid(Component memory c) internal pure returns (uint256) {
return (uint256(c.priceLow) + uint256(c.priceHigh)) / 2;
}
function _value(Component memory c, uint256 rawAmount) internal pure returns (uint256) {
return Math.mulDiv(rawAmount, _mid(c), 10 ** c.decimals);
}
/// @dev The planner lives in IndexLib (see planRebalance there); kept as one call site so openRebalance,
/// rebalanceSwap, and previewRebalance can never diverge.
function _planRebalance() internal view returns (Plan memory) {
return IndexLib.planRebalance(components);
}
function _requireActionable(Plan memory p) internal view {
if (p.nav == 0) revert ZeroAmount();
if (p.maxDrift < rebalanceConfig.driftThresholdBps) revert BelowDriftThreshold();
}
/// @dev Annual fees pending since `lastFeeAccrual`: the maker's (`tvlFeeBps`) and the protocol's own
/// (`factory.protocolTvlFeeFor(this)`), each as shares to mint.
function _pendingFees() internal view returns (uint256 maker, uint256 protocol) {
uint256 supply = totalSupply();
if (supply == 0) return (0, 0);
uint256 elapsed = block.timestamp - lastFeeAccrual;
if (elapsed == 0) return (0, 0);
uint256 pBps = factory.protocolTvlFeeFor(address(this));
if (tvlFeeBps != 0) maker = Math.mulDiv(supply, uint256(tvlFeeBps) * elapsed, BPS * YEAR);
if (pBps != 0) protocol = Math.mulDiv(supply, pBps * elapsed, BPS * YEAR);
}
function _pendingFeeShares() internal view returns (uint256) {
(uint256 maker, uint256 protocol) = _pendingFees();
return maker + protocol;
}
function _accrueFees() internal {
(uint256 maker, uint256 protocol) = _pendingFees();
lastFeeAccrual = block.timestamp;
if (maker + protocol > 0) _distributeFeeShares(maker, protocol);
}
/// @dev `shares` is a maker-side fee (mint or annual), of which the protocol takes `protocolFeeShareBps`;
/// `protocolOwn` is the protocol's own annual fee, minted whole to the protocol recipient.
function _distributeFeeShares(uint256 shares, uint256 protocolOwn) internal {
uint256 protocolShares = Math.mulDiv(shares, factory.protocolFeeShareBps(), BPS);
uint256 creatorShares = shares - protocolShares;
protocolShares += protocolOwn;
if (protocolShares > 0) _mint(factory.protocolFeeRecipient(), protocolShares);
if (creatorShares > 0) _mint(feeRecipient, creatorShares);
emit FeesAccrued(creatorShares, protocolShares);
}
}
src/interfaces/IIndexFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Shared types for the Basket protocol.
library Types {
/// @dev Per-index rebalancing policy, set by the index creator.
struct RebalanceConfig {
uint32 interval; // seconds between rebalance windows
uint32 auctionLength; // seconds each Dutch auction runs
uint16 driftThresholdBps; // open only if max |current - target| >= threshold (bps of NAV)
bool autoRebalance; // true: anyone may open once due; false: owner/operator only
}
/// @dev How target weights are meant to be maintained. The contract never computes 1/n or market caps
/// itself; the app and the bot do and submit the result through setTargetWeights. The scheme decides who
/// may submit: under Custom only the owner; under Equal and MarketCap the operator too, bounded by the
/// caps in WeightPolicy so a bot key cannot reshape the basket in one move.
enum WeightScheme {
Custom,
Equal,
MarketCap
}
struct WeightPolicy {
WeightScheme scheme;
uint16 maxWeightBps; // operator may not set any component above this; 0 means no cap
uint16 maxWeightMoveBps; // operator may not move a component more than this from its anchor per window
}
/// @dev Caps on what the operator (not the owner) may do to a price band within one rebalance window.
struct OperatorLimits {
uint16 maxBandMoveBps; // max |newMid - anchorMid| / anchorMid since the last rebalance or owner set
uint16 maxHalfWidthBps; // max (high - low) / (2 * mid)
}
/// @dev Parameters for IndexFactory.createIndex.
struct CreateParams {
string name;
string symbol;
address owner; // governor of the index (EOA, multisig, or DAO)
address feeRecipient; // receives the creator share of fees
address operator; // optional: a bot key or the Autopilot contract; address(0) for none
uint16 mintFeeBps; // taken as share dilution on mint
uint16 tvlFeeBps; // annual, taken as share dilution over time
address[] tokens;
uint16[] weightsBps; // must sum to 10_000
uint256[] initialUnits; // raw units of each token backing 1e18 shares at inception
uint128[] priceLow; // numeraire (1e18) per whole token, lower bound
uint128[] priceHigh; // numeraire (1e18) per whole token, upper bound
RebalanceConfig rebalance;
WeightPolicy weightPolicy;
OperatorLimits operatorLimits; // both zero keeps the defaults (2,000 / 1,000)
}
}
interface IIndexFactory {
function protocolFeeRecipient() external view returns (address);
function protocolFeeShareBps() external view returns (uint16);
function maxMintFeeBps() external view returns (uint16);
function maxTvlFeeBps() external view returns (uint16);
/// @notice Annual fee (bps of supply per year) that `index` pays the protocol as share dilution, on top of
/// the maker's own annual fee: the per-index override when one is set, else the autopilot default when
/// the index's operator is a recognized Autopilot, else the manual default. Read at every accrual, so
/// a mode switch (which settles fees first) is charged exactly.
function protocolTvlFeeFor(address index) external view returns (uint16);
function isIndex(address) external view returns (bool);
/// @notice Routers and aggregators that indexes and the zap may call with an exact-amount approval.
function isSwapTarget(address) external view returns (bool);
}
src/interfaces/IUniswapV3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice The slices of Uniswap V3 that Autopilot and its library read and call. Aerodrome Slipstream pools expose
/// the same `observe`, `token0`, `token1`, `fee`, and `liquidity`; their `slot0` returns six words, so the
/// library reads it through a raw staticcall rather than this signature.
interface IUniswapV3Factory {
function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}
interface IUniswapV3Pool {
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
function liquidity() external view returns (uint128);
function token0() external view returns (address);
function token1() external view returns (address);
function fee() external view returns (uint24);
}
/// @notice SwapRouter02 exactInput (no deadline field; SwapRouter02 takes the deadline from the multicall wrapper).
interface ISwapRouter02 {
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}
src/libraries/AutopilotLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IndexToken} from "../IndexToken.sol";
import {PlanLib} from "./PlanLib.sol";
import {TwapLib} from "./TwapLib.sol";
/// @title AutopilotLib
/// @notice Autopilot's planning, band checks, and its own swap path, kept in an external library so Autopilot fits
/// under the contract size limit. It runs in Autopilot's context via DELEGATECALL, so approvals and
/// transfers are Autopilot's.
///
/// The swap path is used when a keeper brings no aggregator route: a leg is swapped hop by hop through the
/// very pools the basket prices from (token to its hub, hub to hub, hub to token), each hop on the router
/// of the venue that pool belongs to.
library AutopilotLib {
using SafeERC20 for IERC20;
/// @dev How a venue's router is called.
uint8 internal constant STYLE_ROUTER02 = 0; // exactInputSingle without a deadline (Uniswap SwapRouter02, Pancake SmartRouter)
uint8 internal constant STYLE_V3 = 1; // exactInputSingle with a deadline (Uniswap V3 periphery SwapRouter, Sushi)
uint8 internal constant STYLE_SLIPSTREAM = 2; // exactInputSingle keyed by tick spacing (Aerodrome Slipstream)
uint8 internal constant STYLE_CLASSIC = 3; // swapExactTokensForTokens over Solidly routes (Aerodrome classic)
struct Venue {
address router;
uint8 style;
}
uint256 internal constant BPS = 10_000;
/// @dev Legs executed per poke at most; the rest wait for the next poke (the plan is recomputed each time), so
/// a wide basket's rebalance always fits the gas reimbursement. An own-swap leg costs up to about 700k gas
/// when it crosses three pools, so three legs stay under the 3M cap with the planning on top.
uint256 internal constant MAX_LEGS_PER_POKE = 3;
error NoVenue(address pool);
error RouterNotAllowed(address router);
error PriceUnrepresentable();
error RoutesStale();
error BadSwapTarget();
error LegTooLarge(uint256 leg);
bytes4 internal constant SLOT0_SELECTOR = 0x3850c7bd; // slot0()
bytes4 internal constant LIQUIDITY_SELECTOR = 0x1a686502; // liquidity()
bytes4 internal constant EXECUTE_LEG_SELECTOR = bytes4(keccak256("executeLeg(address,uint256,uint256,address[])"));
/// @dev What `buildExec` and `sliceLegs` need about an index besides its legs: the pricing inputs (pools,
/// kinds, decimals, hubs) as Autopilot assembled them for TwapLib, the TWAP prices, and the config caps.
struct ExecIn {
address index;
address autopilot;
TwapLib.PriceInput p;
IndexToken.Component[] cs;
uint256[] px;
IndexToken.RebalanceLeg[] legs;
IndexToken.SwapLeg[] routes; // empty, or one per leg (target 0 = Autopilot's own swap)
uint16 slip;
uint96 maxLegValue; // numeraire per leg per poke; 0 = no cap
uint96 minLegValue; // numeraire; a leg sliced below this is not worth a swap and does not take a slot
}
// --------------------------------------------------------------- planning
/// @notice The index's own planner evaluated at `px` (see PlanLib), using its live balances.
function planAt(address index, IndexToken.Component[] memory cs, uint256[] memory px)
external
view
returns (PlanLib.Plan memory)
{
uint256 n = cs.length;
uint256[] memory bal = new uint256[](n);
for (uint256 i; i < n; ++i) {
bal[i] = IERC20(cs[i].token).balanceOf(index);
}
return PlanLib.planAt(cs, bal, px);
}
/// @notice The value (numeraire) of the largest planned leg at `px`.
function maxLegValue(IndexToken.Component[] memory cs, uint256[] memory px, IndexToken.RebalanceLeg[] memory legs)
external
pure
returns (uint256 maxV)
{
for (uint256 j; j < legs.length; ++j) {
uint256 si = type(uint256).max;
for (uint256 i; i < cs.length; ++i) {
if (cs[i].token == legs[j].sellToken) si = i;
}
if (si == type(uint256).max) revert RoutesStale();
uint256 v = Math.mulDiv(legs[j].sellAmount, px[si], 10 ** cs[si].decimals);
if (v > maxV) maxV = v;
}
}
// ------------------------------------------------------------------ bands
/// @notice Symmetric bands whose midpoint is exactly the price, so the index's planner sees the TWAP itself.
function bounds(uint256[] memory px, uint16 slip) external pure returns (uint128[] memory lo, uint128[] memory hi) {
uint256 n = px.length;
lo = new uint128[](n);
hi = new uint128[](n);
for (uint256 i; i < n; ++i) {
uint256 d = px[i] * slip / BPS;
uint256 high = px[i] + d;
if (high > type(uint128).max) revert PriceUnrepresentable();
lo[i] = uint128(px[i] - d);
hi[i] = uint128(high);
}
}
/// @notice Mirrors IndexToken._setBounds for an operator caller: would every band move be accepted?
function bandsAllowed(address index, IndexToken.Component[] memory cs, uint256[] memory px, uint16 slip)
external
view
returns (bool)
{
IndexToken t = IndexToken(index);
(uint16 maxMove, uint16 maxHalfWidth) = t.operatorLimits();
if (slip > maxHalfWidth) return false;
if (maxMove >= BPS) return true; // the owner delegated the maximum: no move limit
uint256 last = t.lastRebalance();
for (uint256 i; i < cs.length; ++i) {
(uint128 anchorMid, uint40 setAt) = t.bandAnchor(cs[i].token);
uint256 base = anchorMid;
if (base == 0 || setAt < last) base = (uint256(cs[i].priceLow) + cs[i].priceHigh) / 2;
// measured against the larger of the two, so a doubling and a halving read the same
uint256 move = px[i] > base ? px[i] - base : base - px[i];
uint256 ref = px[i] > base ? px[i] : base;
if (move * BPS > ref * maxMove) return false;
}
return true;
}
// ----------------------------------------------------------------- slicing
/// @notice The planned legs with each sell amount capped to what one poke should trade: the per-poke value cap
/// and what the leg's two pricing pools can absorb within the slippage tolerance (see poolCapacity).
/// What a keeper should build routes for, and what Autopilot's own swap executes.
function sliceLegs(ExecIn memory x) public view returns (IndexToken.RebalanceLeg[] memory legs) {
uint256 n = x.legs.length;
legs = new IndexToken.RebalanceLeg[](n);
uint256[] memory budget = _budgets(x);
uint256 taken;
for (uint256 j; j < n; ++j) {
legs[j] = IndexToken.RebalanceLeg(x.legs[j].sellToken, x.legs[j].buyToken, 0);
if (taken == MAX_LEGS_PER_POKE) continue; // this poke is full; the leg waits for the next one
uint256 amt = legCap(x, j, true, budget);
if (!worth(x, j, amt)) continue; // dust (the remainder of a filled pair) does not take a slot
legs[j].sellAmount = amt;
++taken;
}
}
/// @dev Whether `amt` of leg `j`'s sell token is worth at least the basket's minimum trade value.
function worth(ExecIn memory x, uint256 j, uint256 amt) internal pure returns (bool) {
if (amt == 0) return false;
if (x.minLegValue == 0) return true;
(uint256 si,) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
return Math.mulDiv(amt, x.px[si], 10 ** x.cs[si].decimals) >= x.minLegValue;
}
/// @dev Per-component pool budgets for one poke, in each component's raw units, unknown until first used.
function _budgets(ExecIn memory x) private pure returns (uint256[] memory budget) {
budget = new uint256[](x.cs.length);
for (uint256 i; i < budget.length; ++i) {
budget[i] = type(uint256).max;
}
}
/// @notice Over the planned legs as one poke could slice them (value cap and pool budgets, before the minimum
/// trade value is applied): the largest leg value and how many legs are not capped to zero. `isDue`
/// reads "nothing fillable" from the count and "nothing worth trading" from the value.
function legStats(ExecIn memory x) external view returns (uint256 maxV, uint256 fillable) {
uint256[] memory budget = _budgets(x);
for (uint256 j; j < x.legs.length; ++j) {
uint256 amt = legCap(x, j, true, budget);
if (amt == 0) continue;
++fillable;
(uint256 si,) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
uint256 v = Math.mulDiv(amt, x.px[si], 10 ** x.cs[si].decimals);
if (v > maxV) maxV = v;
}
}
/// @notice One SwapLeg per planned leg, ready for the index's rebalanceSwap: the caller's route when one is
/// given (its sell amount must fit the plan and the per-poke value cap; its minimum is raised to the
/// TWAP less slippage), otherwise Autopilot's own swap for the sliced amount through the leg's pricing
/// pools. A leg capped to zero is skipped (sellAmount 0).
function buildExec(ExecIn memory x) external view returns (IndexToken.SwapLeg[] memory exec, uint256 fillable) {
uint256 n = x.legs.length;
exec = new IndexToken.SwapLeg[](n);
uint256[] memory budget = _budgets(x);
for (uint256 j; j < n; ++j) {
if (fillable == MAX_LEGS_PER_POKE) break; // the remaining legs stay skipped (sellAmount 0)
(uint256 si, uint256 bi) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
bool own = x.routes.length == 0 || x.routes[j].target == address(0);
uint256 amt = legCap(x, j, own, budget);
if (own && !worth(x, j, amt)) continue;
if (!own) {
IndexToken.SwapLeg memory r = x.routes[j];
if (r.target == x.index || r.spender == x.index || r.target == x.autopilot || r.spender == x.autopilot)
{
revert BadSwapTarget();
}
// type(uint256).max means "the whole capped leg"; an explicit amount must fit within the cap
if (r.sellAmount != type(uint256).max) {
if (r.sellAmount > amt) revert LegTooLarge(j);
amt = r.sellAmount;
}
}
if (amt == 0) continue;
uint256 minOut = _minOut(amt, x.px[si], x.cs[si].decimals, x.px[bi], x.cs[bi].decimals, x.slip);
if (!own) {
exec[j] = x.routes[j];
if (exec[j].minAmountOut < minOut) exec[j].minAmountOut = minOut;
} else {
address[] memory pools = legPools(
x.cs[si].token, x.p.pools[si], x.cs[bi].token, x.p.pools[bi], x.p.weth, x.p.stable, x.p.stablePool
);
exec[j] = IndexToken.SwapLeg({
spender: x.autopilot,
target: x.autopilot,
data: abi.encodeWithSelector(EXECUTE_LEG_SELECTOR, x.cs[si].token, amt, minOut, pools),
minAmountOut: minOut,
sellAmount: amt
});
}
++fillable;
}
}
/// @dev The most of leg `j` one poke should sell, in the sell token's raw units: the planned amount, capped by
/// the per-poke value cap and, for Autopilot's own swap (`own`), by what is left of the sell token's pool
/// and the buy token's pool within the slippage tolerance (see poolCapacity). Each pool's capacity is a
/// budget shared by every leg of the poke that touches it, in either direction, so four legs selling the
/// same token cannot each take the whole pool. Caller routes trade wherever the aggregator finds depth, so
/// only the value cap applies to them; the TWAP-based minimum output bounds the rest.
function legCap(ExecIn memory x, uint256 j, bool own, uint256[] memory budget) public view returns (uint256 amt) {
(uint256 si, uint256 bi) = find(x.cs, x.legs[j].sellToken, x.legs[j].buyToken);
amt = x.legs[j].sellAmount;
uint256 dS = 10 ** x.cs[si].decimals;
if (x.maxLegValue != 0) {
uint256 capV = Math.mulDiv(x.maxLegValue, dS, x.px[si]);
if (capV < amt) amt = capV;
}
if (!own) return amt;
uint256 dB = 10 ** x.cs[bi].decimals;
if (x.p.pools[si] != address(0)) {
if (budget[si] == type(uint256).max) {
budget[si] = poolCapacity(x.p.pools[si], x.p.kinds[si], x.cs[si].token, x.slip);
}
if (budget[si] < amt) amt = budget[si];
}
uint256 amtB; // the leg's size in buy-token units at the TWAP
if (x.p.pools[bi] != address(0)) {
if (budget[bi] == type(uint256).max) {
budget[bi] = poolCapacity(x.p.pools[bi], x.p.kinds[bi], x.cs[bi].token, x.slip);
}
if (budget[bi] != type(uint256).max) {
uint256 capBS = Math.mulDiv(Math.mulDiv(budget[bi], x.px[bi], dB), dS, x.px[si]);
if (capBS < amt) amt = capBS;
amtB = Math.mulDiv(Math.mulDiv(amt, x.px[si], dS), dB, x.px[bi]);
}
}
if (x.p.pools[si] != address(0) && budget[si] != type(uint256).max) budget[si] -= amt;
if (amtB != 0) budget[bi] -= amtB > budget[bi] ? budget[bi] : amtB;
}
/// @notice About how much `token` can be sold into or bought out of `pool` before its price moves by a quarter
/// of `slip` (bps), in `token`'s raw units: an eighth of the slippage worth of the pool's in-range
/// liquidity at the current sqrt price for a concentrated pool, an eighth of the slippage worth of the
/// token's reserve for a constant-product pool (both move the price by about slip / 4). A leg touches
/// two such pools, so its own impact stays within half the tolerance and the other half is left for
/// pool fees and the hub hop, since every leg's minimum output is measured from the TWAP.
/// type(uint256).max when the pool cannot be read (then only the TWAP minimum output bounds the leg).
function poolCapacity(address pool, uint8 kind, address token, uint16 slip) public view returns (uint256) {
if (kind == TwapLib.KIND_CLASSIC) {
(bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(IClassicReserves.getReserves.selector));
if (!ok || ret.length < 96) return type(uint256).max;
(uint256 r0, uint256 r1,) = abi.decode(ret, (uint256, uint256, uint256));
uint256 r = IPoolFactoryRef(pool).token0() == token ? r0 : r1;
return r * slip / (8 * BPS);
}
(bool ok0, bytes memory s0) = pool.staticcall(abi.encodeWithSelector(SLOT0_SELECTOR));
(bool okL, bytes memory lq) = pool.staticcall(abi.encodeWithSelector(LIQUIDITY_SELECTOR));
if (!ok0 || s0.length < 32 || !okL || lq.length < 32) return type(uint256).max;
uint256 sqrtP;
int256 tick;
assembly {
sqrtP := mload(add(s0, 32))
tick := mload(add(s0, 64))
}
uint256 liq = abi.decode(lq, (uint256));
// a pool that reports only its tick (test doubles) is priced from the tick instead
if (sqrtP == 0 && s0.length >= 64) sqrtP = TwapLib.getSqrtRatioAtTick(int24(tick));
if (sqrtP == 0) return type(uint256).max;
uint256 cap;
if (IPoolFactoryRef(pool).token0() == token) {
// dx = L * d(1/sqrtP); a price move of slip/4 is a sqrtP move of about slip/8
cap = Math.mulDiv(liq << 96, slip, sqrtP * 8 * BPS);
} else {
// dy = L * d(sqrtP); about slip/8 of sqrtP
cap = Math.mulDiv(Math.mulDiv(liq, sqrtP, 1 << 96), slip, 8 * BPS);
}
// in-range liquidity says nothing about the ticks a trade may cross, so a slice is also kept to what would
// move a constant-product pool with the same holdings by slip/4; the two together are conservative
uint256 held = IERC20(token).balanceOf(pool);
if (held != 0) {
uint256 byBalance = held * slip / (8 * BPS);
if (byBalance < cap) cap = byBalance;
}
return cap;
}
function _minOut(uint256 sellAmount, uint256 pS, uint8 dS, uint256 pB, uint8 dB, uint16 slip)
internal
pure
returns (uint256)
{
uint256 fair = Math.mulDiv(Math.mulDiv(sellAmount, pS, 10 ** dS), 10 ** dB, pB);
return fair * (BPS - slip) / BPS;
}
/// @notice Component positions of a leg's sell and buy tokens.
function find(IndexToken.Component[] memory cs, address sell, address buy)
public
pure
returns (uint256 si, uint256 bi)
{
uint256 n = cs.length;
bool fs;
bool fb;
for (uint256 i; i < n; ++i) {
if (cs[i].token == sell) (si, fs) = (i, true);
if (cs[i].token == buy) (bi, fb) = (i, true);
}
if (!fs || !fb) revert RoutesStale();
}
// ------------------------------------------------------------------ swaps
/// @notice The pools a leg passes through, in order: the sell token's pricing pool (unless it is WETH or the
/// stablecoin), the WETH/stablecoin pool when the two sides sit on different hubs, then the buy token's
/// pricing pool (unless it is WETH or the stablecoin).
function legPools(
address sell,
address sellPool,
address buy,
address buyPool,
address weth,
address stable,
address stablePool
) public view returns (address[] memory pools) {
pools = new address[](3);
uint256 n;
address hubS = sell;
if (sell != weth && sell != stable) {
pools[n++] = sellPool;
hubS = _other(sellPool, sell);
}
address hubB = buy;
if (buy != weth && buy != stable) hubB = _other(buyPool, buy);
if (hubS != hubB) pools[n++] = stablePool;
if (buy != hubB) pools[n++] = buyPool;
assembly {
mstore(pools, n)
}
}
/// @notice Swap `amountIn` of `tokenIn` (held by the caller's contract) through `pools` in order, paying the
/// final output to `recipient`. Each hop uses the router registered for its pool's factory, which must
/// also be an allowed swap target on the index factory. Intermediate outputs are measured by balance
/// change, so tokens that happen to sit in the contract are never swept into a trade.
function swapThrough(
address[] memory pools,
address tokenIn,
uint256 amountIn,
uint256 minOut,
address recipient,
mapping(address => Venue) storage venues,
address indexFactory
) external returns (uint256 amountOut) {
address token = tokenIn;
uint256 amount = amountIn;
uint256 last = pools.length - 1;
for (uint256 i; i < pools.length; ++i) {
address pool = pools[i];
address out = _other(pool, token);
address fac = IPoolFactoryRef(pool).factory();
Venue memory v = venues[fac];
if (v.router == address(0)) revert NoVenue(pool);
if (!ISwapTargets(indexFactory).isSwapTarget(v.router)) revert RouterNotAllowed(v.router);
address to = i == last ? recipient : address(this);
uint256 before = IERC20(out).balanceOf(to);
IERC20(token).forceApprove(v.router, amount);
_hop(v, pool, fac, token, out, amount, i == last ? minOut : 0, to);
IERC20(token).forceApprove(v.router, 0);
amount = IERC20(out).balanceOf(to) - before;
token = out;
}
amountOut = amount;
}
function _hop(
Venue memory v,
address pool,
address fac,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOut,
address to
) private {
if (v.style == STYLE_ROUTER02) {
IRouter02(v.router)
.exactInputSingle(IRouter02.Params(tokenIn, tokenOut, IFeePool(pool).fee(), to, amountIn, minOut, 0));
} else if (v.style == STYLE_V3) {
IRouterV3(v.router)
.exactInputSingle(
IRouterV3.Params(tokenIn, tokenOut, IFeePool(pool).fee(), to, block.timestamp, amountIn, minOut, 0)
);
} else if (v.style == STYLE_SLIPSTREAM) {
ISlipstreamRouter(v.router)
.exactInputSingle(
ISlipstreamRouter.Params(
tokenIn, tokenOut, ISpacingPool(pool).tickSpacing(), to, block.timestamp, amountIn, minOut, 0
)
);
} else {
IClassicRouter.Route[] memory r = new IClassicRouter.Route[](1);
r[0] = IClassicRouter.Route(tokenIn, tokenOut, false, fac);
IClassicRouter(v.router).swapExactTokensForTokens(amountIn, minOut, r, to, block.timestamp);
}
}
function _other(address pool, address token) private view returns (address) {
address t0 = IPoolFactoryRef(pool).token0();
return t0 == token ? IPoolFactoryRef(pool).token1() : t0;
}
}
interface IPoolFactoryRef {
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
}
interface IClassicReserves {
function getReserves() external view returns (uint256 reserve0, uint256 reserve1, uint256 blockTimestampLast);
}
interface IFeePool {
function fee() external view returns (uint24);
}
interface ISpacingPool {
function tickSpacing() external view returns (int24);
}
interface ISwapTargets {
function isSwapTarget(address) external view returns (bool);
}
interface IRouter02 {
struct Params {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(Params calldata p) external payable returns (uint256);
}
interface IRouterV3 {
struct Params {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(Params calldata p) external payable returns (uint256);
}
interface ISlipstreamRouter {
struct Params {
address tokenIn;
address tokenOut;
int24 tickSpacing;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(Params calldata p) external payable returns (uint256);
}
interface IClassicRouter {
struct Route {
address from;
address to;
bool stable;
address factory;
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
src/libraries/IndexLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IndexToken} from "../IndexToken.sol";
import {IIndexFactory} from "../interfaces/IIndexFactory.sol";
/// @title IndexLib
/// @notice IndexToken's rebalance planner, Dutch-auction bookkeeping, and swap-leg execution, kept in an external
/// library (linked at deploy) so IndexToken stays under the bytecode limit. Every function runs in the
/// index's own context through DELEGATECALL: storage, token balances, approvals, and `msg.sender` are the
/// index's, and the events and errors are IndexToken's own, so logs and reverts look exactly as before.
library IndexLib {
using SafeERC20 for IERC20;
uint256 internal constant BPS = 10_000;
uint256 internal constant WAD = 1e18;
uint256 internal constant DUST_VALUE = 1e15; // 0.001 numeraire units; mirrors IndexToken
// ---------------------------------------------------------------- planner
/// @notice Values the basket at band midpoints and greedily pairs over-weight components with under-weight
/// ones. Shared by openRebalance, rebalanceSwap, and previewRebalance so the preview can never diverge
/// from execution. Never reverts; callers check `nav` and `maxDrift`.
function planRebalance(IndexToken.Component[] storage components) external view returns (IndexToken.Plan memory p) {
uint256 n = components.length;
p.legs = new IndexToken.RebalanceLeg[](n);
p.sIdx = new uint8[](n);
p.bIdx = new uint8[](n);
uint256[] memory values = new uint256[](n);
for (uint256 i; i < n; ++i) {
values[i] = value(components[i], IERC20(components[i].token).balanceOf(address(this)));
p.nav += values[i];
}
if (p.nav == 0) return p;
int256[] memory diff = new int256[](n);
for (uint256 i; i < n; ++i) {
uint256 target = Math.mulDiv(p.nav, components[i].targetWeightBps, BPS);
diff[i] = int256(values[i]) - int256(target);
uint256 d = diff[i] >= 0 ? uint256(diff[i]) : uint256(-diff[i]);
uint256 driftBps = Math.mulDiv(d, BPS, p.nav);
if (driftBps > p.maxDrift) p.maxDrift = driftBps;
}
for (uint256 s; s < n; ++s) {
if (diff[s] <= 0) continue;
// sub-dust remainders of a dropped component are left for removeComponent rather than
// emitted as swap legs no router could fill
if (components[s].targetWeightBps == 0 && values[s] <= DUST_VALUE) continue;
uint256 remaining = IERC20(components[s].token).balanceOf(address(this));
for (uint256 b; b < n && diff[s] > 0; ++b) {
if (diff[b] >= 0) continue;
uint256 v = uint256(diff[s]);
uint256 need = uint256(-diff[b]);
if (need < v) v = need;
uint256 sellRaw = Math.mulDiv(v, 10 ** components[s].decimals, mid(components[s]));
diff[s] -= int256(v);
diff[b] += int256(v);
if (sellRaw > remaining) sellRaw = remaining;
if (sellRaw == 0) {
// a zero-weight seller must never skip a buyer while it still holds balance
if (components[s].targetWeightBps != 0 || remaining == 0) continue;
sellRaw = remaining;
}
remaining -= sellRaw;
p.legs[p.count] = IndexToken.RebalanceLeg(components[s].token, components[b].token, sellRaw);
p.sIdx[p.count] = uint8(s);
p.bIdx[p.count] = uint8(b);
++p.count;
}
// Targets floor per component, so total need can fall a few wei short of a zero-weight
// component's surplus. Fold whatever is left into its last leg so it sells to exactly zero.
if (components[s].targetWeightBps == 0 && remaining > 0 && p.count > 0 && p.sIdx[p.count - 1] == s) {
p.legs[p.count - 1].sellAmount += remaining;
}
}
}
// --------------------------------------------------------------- auctions
function hasActiveAuctions(IndexToken.Auction[] storage auctions) external view returns (bool) {
uint256 n = auctions.length;
for (uint256 i; i < n; ++i) {
if (auctions[i].sellRemaining > 0 && block.timestamp < auctions[i].endTime) return true;
}
return false;
}
/// @notice Current rate (buy raw units per 1e18 sell raw units) of auction `id`.
function currentRate(IndexToken.Auction[] storage auctions, uint256 id) public view returns (uint256) {
IndexToken.Auction memory a = auctions[id];
if (block.timestamp <= a.startTime) return a.startRate;
if (block.timestamp >= a.endTime) return a.endRate;
uint256 elapsed = block.timestamp - a.startTime;
uint256 len = a.endTime - a.startTime;
return a.startRate - Math.mulDiv(a.startRate - a.endRate, elapsed, len);
}
/// @notice One Dutch auction per planned leg, from the rate best for the vault to the worst.
function openAuctions(
IndexToken.Auction[] storage auctions,
IndexToken.Component[] storage components,
IndexToken.Plan memory p,
uint256 round,
uint40 start,
uint40 end
) external {
for (uint256 i; i < p.count; ++i) {
IndexToken.Component memory s = components[p.sIdx[i]];
IndexToken.Component memory b = components[p.bIdx[i]];
uint256 sellRaw = p.legs[i].sellAmount;
if (sellRaw > type(uint128).max) revert IndexToken.RateUnrepresentable();
uint128 startRate = rate(s, b, s.priceHigh, b.priceLow);
uint128 endRate = rate(s, b, s.priceLow, b.priceHigh);
auctions.push(
IndexToken.Auction({
sellToken: s.token,
buyToken: b.token,
sellRemaining: uint128(sellRaw),
startRate: startRate,
endRate: endRate,
startTime: start,
endTime: end
})
);
emit IndexToken.AuctionCreated(round, auctions.length - 1, s.token, b.token, sellRaw, startRate, endRate);
}
}
/// @notice Buy up to `sellAmount` of the auction's sell token at the current Dutch-auction rate, paying at most
/// `maxBuyAmount` of the buy token. The bidder is `msg.sender` (preserved through DELEGATECALL).
function bid(IndexToken.Auction[] storage auctions, uint256 id, uint256 sellAmount, uint256 maxBuyAmount)
external
returns (uint256 filled, uint256 buyAmount)
{
IndexToken.Auction storage a = auctions[id];
if (a.sellRemaining == 0 || block.timestamp >= a.endTime) revert IndexToken.AuctionNotActive();
if (sellAmount == 0) revert IndexToken.ZeroAmount();
filled = sellAmount > a.sellRemaining ? a.sellRemaining : sellAmount;
uint256 r = currentRate(auctions, id);
buyAmount = Math.mulDiv(filled, r, WAD, Math.Rounding.Ceil);
if (buyAmount > maxBuyAmount) revert IndexToken.Slippage();
if (buyAmount == 0) revert IndexToken.ZeroAmount();
a.sellRemaining -= uint128(filled);
pullExact(IERC20(a.buyToken), buyAmount);
IERC20(a.sellToken).safeTransfer(msg.sender, filled);
emit IndexToken.AuctionFilled(id, msg.sender, filled, buyAmount, r);
}
// ------------------------------------------------------------------ swaps
/// @notice Execute the planned legs against the caller's routes: each leg approves exactly its sell amount to
/// a whitelisted spender, calls the whitelisted target, resets the approval, and must give up at most
/// the sell amount and receive at least max(the caller's minimum, the Dutch-auction floor). A leg's
/// `sellAmount` of 0 skips it and anything below the planned amount is a slice; the floor and the
/// minimum scale with what is actually sold.
/// @return full True when every leg was executed for its whole planned amount.
function executeLegs(
IIndexFactory factory,
mapping(address => bool) storage isComponent,
IndexToken.Component[] storage components,
IndexToken.Plan memory p,
IndexToken.SwapLeg[] calldata legs,
uint256 round
) external returns (bool full) {
if (legs.length != p.count) revert IndexToken.LengthMismatch();
full = true;
for (uint256 i; i < p.count; ++i) {
uint256 planned = p.legs[i].sellAmount;
uint256 sellAmount = legs[i].sellAmount;
if (sellAmount == 0) {
full = false;
continue;
}
uint256 callerMin = legs[i].minAmountOut;
if (sellAmount >= planned) {
// type(uint256).max means "the whole planned amount"; an explicit larger request was quoted for
// more than the plan, so its minimum scales down with the cap
if (sellAmount != type(uint256).max) callerMin = Math.mulDiv(callerMin, planned, sellAmount);
sellAmount = planned;
} else {
full = false;
}
IndexToken.Component memory s = components[p.sIdx[i]];
IndexToken.Component memory b = components[p.bIdx[i]];
uint256 floorOut = Math.mulDiv(sellAmount, rate(s, b, s.priceLow, b.priceHigh), WAD);
uint256 minOut = callerMin > floorOut ? callerMin : floorOut;
(uint256 sold, uint256 bought) =
_executeSwap(factory, isComponent, s.token, b.token, sellAmount, minOut, legs[i]);
emit IndexToken.SwapExecuted(round, s.token, b.token, sold, bought);
}
}
function _executeSwap(
IIndexFactory factory,
mapping(address => bool) storage isComponent,
address sellToken,
address buyToken,
uint256 sellAmount,
uint256 minOut,
IndexToken.SwapLeg calldata leg
) private returns (uint256 sold, uint256 bought) {
if (!factory.isSwapTarget(leg.spender) || !factory.isSwapTarget(leg.target)) {
revert IndexToken.BadSwapTarget();
}
// even a misconfigured whitelist must never let the vault call itself or one of its own holdings
if (leg.target == address(this) || isComponent[leg.target]) revert IndexToken.BadSwapTarget();
uint256 sellBefore = IERC20(sellToken).balanceOf(address(this));
uint256 buyBefore = IERC20(buyToken).balanceOf(address(this));
IERC20(sellToken).forceApprove(leg.spender, sellAmount);
(bool ok, bytes memory ret) = leg.target.call(leg.data);
if (!ok) {
assembly {
revert(add(ret, 0x20), mload(ret))
}
}
IERC20(sellToken).forceApprove(leg.spender, 0);
uint256 sellAfter = IERC20(sellToken).balanceOf(address(this));
if (sellAfter < sellBefore) {
sold = sellBefore - sellAfter;
if (sold > sellAmount) revert IndexToken.Overspend();
}
bought = IERC20(buyToken).balanceOf(address(this)) - buyBefore;
if (bought < minOut) revert IndexToken.Slippage();
}
// ---------------------------------------------------------------- helpers
/// @notice Pull exactly `amount` of `t` from msg.sender. Fee-on-transfer tokens deliver less and are rejected
/// so a minter or bidder can never dilute existing holders.
function pullExact(IERC20 t, uint256 amount) public {
uint256 before = t.balanceOf(address(this));
t.safeTransferFrom(msg.sender, address(this), amount);
if (t.balanceOf(address(this)) - before < amount) revert IndexToken.TransferShortfall();
}
function mid(IndexToken.Component memory c) internal pure returns (uint256) {
return (uint256(c.priceLow) + uint256(c.priceHigh)) / 2;
}
function value(IndexToken.Component memory c, uint256 rawAmount) internal pure returns (uint256) {
return Math.mulDiv(rawAmount, mid(c), 10 ** c.decimals);
}
/// @dev rate = buy raw units per 1e18 sell raw units, given a sell price and a buy price.
function rate(IndexToken.Component memory s, IndexToken.Component memory b, uint256 priceSell, uint256 priceBuy)
internal
pure
returns (uint128)
{
uint256 r = Math.mulDiv(priceSell * WAD, 10 ** b.decimals, priceBuy * 10 ** s.decimals);
if (r > type(uint128).max) revert IndexToken.RateUnrepresentable();
return uint128(r);
}
}
src/libraries/PlanLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IndexToken} from "../IndexToken.sol";
/// @title PlanLib
/// @notice IndexToken._planRebalance evaluated at caller-supplied prices instead of the stored band midpoints.
/// Kept identical in structure (greedy pairing, dust rules) so Autopilot's `plan` matches what the index
/// executes after `poke` sets the bands to those prices. Internal (inlined) library.
library PlanLib {
uint256 internal constant BPS = 10_000;
uint256 internal constant DUST_VALUE = 1e15; // mirrors IndexToken
struct Plan {
uint256 nav;
uint256 maxDrift;
uint256 count;
IndexToken.RebalanceLeg[] legs;
}
/// @param cs The index's components (decimals and target weights are read from them)
/// @param bal The index's raw balance of each component
/// @param px The price of each component, numeraire (1e18) per whole token
function planAt(IndexToken.Component[] memory cs, uint256[] memory bal, uint256[] memory px)
internal
pure
returns (Plan memory p)
{
uint256 n = cs.length;
int256[] memory diff = new int256[](n); // values first, then value minus target
for (uint256 i; i < n; ++i) {
uint256 v = Math.mulDiv(bal[i], px[i], 10 ** cs[i].decimals);
diff[i] = int256(v);
p.nav += v;
}
if (p.nav == 0) {
p.legs = new IndexToken.RebalanceLeg[](0);
return p;
}
for (uint256 i; i < n; ++i) {
diff[i] -= int256(Math.mulDiv(p.nav, cs[i].targetWeightBps, BPS));
uint256 d = diff[i] >= 0 ? uint256(diff[i]) : uint256(-diff[i]);
uint256 driftBps = Math.mulDiv(d, BPS, p.nav);
if (driftBps > p.maxDrift) p.maxDrift = driftBps;
}
p.legs = new IndexToken.RebalanceLeg[](n);
_pair(cs, px, bal, diff, p);
IndexToken.RebalanceLeg[] memory legs = p.legs;
uint256 count = p.count;
assembly {
mstore(legs, count)
}
}
/// @dev The greedy over-weight to under-weight pairing, writing legs into `p`.
function _pair(
IndexToken.Component[] memory cs,
uint256[] memory px,
uint256[] memory bal,
int256[] memory diff,
Plan memory p
) internal pure {
uint256 n = cs.length;
for (uint256 s; s < n; ++s) {
if (diff[s] <= 0) continue;
// for a zero-weight component the target is zero, so diff equals value
if (cs[s].targetWeightBps == 0 && uint256(diff[s]) <= DUST_VALUE) continue;
uint256 remaining = bal[s];
for (uint256 b; b < n && diff[s] > 0; ++b) {
if (diff[b] >= 0) continue;
uint256 v = uint256(diff[s]);
uint256 need = uint256(-diff[b]);
if (need < v) v = need;
uint256 sellRaw = Math.mulDiv(v, 10 ** cs[s].decimals, px[s]);
diff[s] -= int256(v);
diff[b] += int256(v);
if (sellRaw > remaining) sellRaw = remaining;
if (sellRaw == 0) {
if (cs[s].targetWeightBps != 0 || remaining == 0) continue;
sellRaw = remaining;
}
remaining -= sellRaw;
p.legs[p.count] = IndexToken.RebalanceLeg(cs[s].token, cs[b].token, sellRaw);
++p.count;
}
if (
cs[s].targetWeightBps == 0 && remaining > 0 && p.count > 0
&& p.legs[p.count - 1].sellToken == cs[s].token
) {
p.legs[p.count - 1].sellAmount += remaining;
}
}
}
}
src/libraries/TwapLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IUniswapV3Pool} from "../interfaces/IUniswapV3.sol";
/// @notice The classic (Solidly-style) pool surface read for pricing: Aerodrome classic on Base, Velodrome V2.
interface IClassicPool {
function token0() external view returns (address);
function stable() external view returns (bool);
function observationLength() external view returns (uint256);
function observations(uint256 i)
external
view
returns (uint256 timestamp, uint256 reserve0Cumulative, uint256 reserve1Cumulative);
function currentCumulativePrices()
external
view
returns (uint256 reserve0Cumulative, uint256 reserve1Cumulative, uint256 blockTimestamp);
function getReserves() external view returns (uint256 reserve0, uint256 reserve1, uint256 blockTimestampLast);
}
/// @title TwapLib
/// @notice Autopilot's pricing, as an external (linked) library to keep Autopilot under the bytecode limit. Two
/// pool kinds:
/// - KIND_CONCENTRATED (0): any pool with Uniswap V3's `observe`, `token0`, `token1`, and a `slot0` whose
/// first two words are sqrtPriceX96 and tick (Uniswap V3, PancakeSwap V3, SushiSwap V3, Aerodrome
/// Slipstream, whose `slot0` returns six words; only the leading words are read).
/// - KIND_CLASSIC (1): volatile Solidly-style pools (Aerodrome classic, Velodrome V2), which record
/// cumulative reserves roughly every 30 minutes. The average is the ratio of time-averaged reserves
/// since the newest stored observation at least `window` seconds old. Stable-curve pools are refused:
/// their price is not the reserve ratio.
library TwapLib {
int24 internal constant MIN_TICK = -887272;
int24 internal constant MAX_TICK = 887272;
uint256 internal constant WAD = 1e18;
uint8 internal constant KIND_CONCENTRATED = 0;
uint8 internal constant KIND_CLASSIC = 1;
uint256 internal constant MAX_OBSERVATION_STEPS = 400; // about 8 days of 30-minute observations
bytes4 internal constant SLOT0_SELECTOR = 0x3850c7bd; // slot0()
bytes4 internal constant TOKEN0_SELECTOR = 0x0dfe1681; // token0()
bytes4 internal constant TOKEN1_SELECTOR = 0xd21220a7; // token1()
bytes4 internal constant FACTORY_SELECTOR = 0xc45a0155; // factory()
bytes4 internal constant FEE_SELECTOR = 0xddca3f43; // fee()
bytes4 internal constant TICK_SPACING_SELECTOR = 0xd0c93a7c; // tickSpacing()
bytes4 internal constant GET_POOL_FEE = 0x1698ee82; // getPool(address,address,uint24): Uniswap, PancakeSwap, SushiSwap V3
bytes4 internal constant GET_POOL_TICK_SPACING = 0x28af8d0b; // getPool(address,address,int24): Aerodrome Slipstream
bytes4 internal constant GET_POOL_STABLE = 0x79bc57d5; // getPool(address,address,bool): Aerodrome classic
bytes4 internal constant IS_POOL = 0x5b16ebb7; // isPool(address): Aerodrome classic
error TickOutOfRange();
error ZeroWindow();
error BadPool(address token);
error PriceUnavailable(address token);
error PriceDiverged(address token);
/// @dev Everything `priceAll` needs, copied from Autopilot's storage. `pools[i]` is address(0) for the
/// stablecoin (always 1) and for WETH (priced from `stablePool`). `kinds[i]` is the pool kind.
struct PriceInput {
address[] tokens;
address[] pools;
uint8[] kinds;
uint8[] decimals;
address weth;
address stable;
uint8 wethDecimals;
uint8 stableDecimals;
address stablePool;
uint8 stablePoolKind;
uint32 window;
int24 maxDelta;
}
/// @notice Numeraire price (1e18 per whole token) of every token from the time-weighted average of its pool,
/// refusing any pool whose spot tick sits more than `maxDelta` ticks from its average.
function priceAll(PriceInput memory p) external view returns (uint256[] memory px) {
uint256 n = p.tokens.length;
px = new uint256[](n);
uint256 stablePerWeth; // raw stablecoin per whole WETH, computed once if needed
for (uint256 i; i < n; ++i) {
address token = p.tokens[i];
uint256 price;
if (token == p.stable) {
price = WAD;
} else if (token == p.weth) {
if (stablePerWeth == 0) stablePerWeth = _stablePerWeth(p);
price = Math.mulDiv(stablePerWeth, WAD, 10 ** p.stableDecimals);
} else {
address pool = p.pools[i];
address other = counterpart(pool, token);
uint256 quote =
quoteAverage(pool, p.kinds[i], p.window, p.maxDelta, token, other, uint128(10 ** p.decimals[i]));
if (other == p.weth) {
if (stablePerWeth == 0) stablePerWeth = _stablePerWeth(p);
price = Math.mulDiv(
Math.mulDiv(quote, stablePerWeth, 10 ** p.wethDecimals), WAD, 10 ** p.stableDecimals
);
} else if (other == p.stable) {
price = Math.mulDiv(quote, WAD, 10 ** p.stableDecimals);
} else {
revert BadPool(token);
}
}
if (price == 0) revert PriceUnavailable(token);
px[i] = price;
}
}
function _stablePerWeth(PriceInput memory p) internal view returns (uint256) {
return quoteAverage(
p.stablePool, p.stablePoolKind, p.window, p.maxDelta, p.weth, p.stable, uint128(10 ** p.wethDecimals)
);
}
/// @notice How much `quoteToken` (raw) `baseAmount` of `baseToken` (raw) is worth at the pool's average over
/// `window`, refusing a pool whose spot price sits more than `maxDelta` (ticks, about one bps each)
/// from that average.
function quoteAverage(
address pool,
uint8 kind,
uint32 window,
int24 maxDelta,
address baseToken,
address quoteToken,
uint128 baseAmount
) public view returns (uint256) {
if (kind == KIND_CONCENTRATED) {
return quoteAtTick(checkedTick(pool, window, maxDelta, baseToken), baseAmount, baseToken, quoteToken);
}
if (kind == KIND_CLASSIC) return classicQuote(pool, window, maxDelta, baseToken, baseAmount);
revert BadPool(baseToken);
}
/// @notice A route's pool checked for its kind: it must contain `token` (returning the other token), a classic
/// pool must be volatile, and the factory the pool names must confirm it (so a contract that merely
/// claims a whitelisted factory is refused). Returns that factory for the caller's whitelist check.
/// Concentrated pools are confirmed by fee tier (Uniswap, PancakeSwap, SushiSwap V3) or by tick
/// spacing (Aerodrome Slipstream); classic pools by `getPool(.., stable)` or `isPool`. Unknown kinds
/// are refused.
function validate(address pool, uint8 kind, address token) external view returns (address other, address fac) {
other = counterpart(pool, token);
bool ok;
(ok, fac) = _addressCall(pool, FACTORY_SELECTOR);
if (!ok || fac == address(0)) revert BadPool(token);
(, address t0) = _addressCall(pool, TOKEN0_SELECTOR);
(, address t1) = _addressCall(pool, TOKEN1_SELECTOR);
if (kind == KIND_CLASSIC) {
(bool okS, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(IClassicPool.stable.selector));
if (!okS || ret.length < 32 || abi.decode(ret, (bool))) revert BadPool(token);
if (
!_confirms(fac, abi.encodeWithSelector(GET_POOL_STABLE, t0, t1, false), pool)
&& !_flag(fac, abi.encodeWithSelector(IS_POOL, pool))
) revert BadPool(token);
} else if (kind == KIND_CONCENTRATED) {
(bool okFee, uint256 fee) = _wordCall(pool, FEE_SELECTOR);
bool confirmed = okFee && fee <= type(uint24).max
&& _confirms(fac, abi.encodeWithSelector(GET_POOL_FEE, t0, t1, uint24(fee)), pool);
if (!confirmed) {
(bool okTs, uint256 raw) = _wordCall(pool, TICK_SPACING_SELECTOR);
int256 ts = int256(raw);
confirmed = okTs && ts > 0 && ts <= type(int24).max
&& _confirms(fac, abi.encodeWithSelector(GET_POOL_TICK_SPACING, t0, t1, int24(ts)), pool);
}
if (!confirmed) revert BadPool(token);
} else {
revert BadPool(token);
}
}
/// @notice The factory a pool names, or address(0) if it does not answer.
function factoryOf(address pool) external view returns (address fac) {
(, fac) = _addressCall(pool, FACTORY_SELECTOR);
}
function _confirms(address fac, bytes memory call, address pool) internal view returns (bool) {
(bool ok, bytes memory ret) = fac.staticcall(call);
return ok && ret.length >= 32 && abi.decode(ret, (address)) == pool;
}
function _flag(address fac, bytes memory call) internal view returns (bool) {
(bool ok, bytes memory ret) = fac.staticcall(call);
return ok && ret.length >= 32 && abi.decode(ret, (uint256)) == 1;
}
function _wordCall(address target, bytes4 selector) internal view returns (bool ok, uint256 out) {
bytes memory ret;
(ok, ret) = target.staticcall(abi.encodeWithSelector(selector));
if (!ok || ret.length < 32) return (false, 0);
out = abi.decode(ret, (uint256));
}
/// @notice Average quote from a volatile classic pool: the ratio of its time-averaged reserves between now
/// and the newest stored observation at least `window` seconds old. Reverts PriceUnavailable when the
/// stored history does not reach that far back (within MAX_OBSERVATION_STEPS observations) and
/// PriceDiverged when the current reserve ratio is more than `maxDelta` bps off the average.
function classicQuote(address pool, uint32 window, int24 maxDelta, address token, uint256 baseAmount)
public
view
returns (uint256 quote)
{
if (window == 0) revert ZeroWindow();
IClassicPool cp = IClassicPool(pool);
(uint256 c0, uint256 c1, uint256 nowTs) = cp.currentCumulativePrices();
uint256 len = cp.observationLength();
if (len == 0 || nowTs <= window) revert PriceUnavailable(token);
uint256 target = nowTs - window;
uint256 i = len - 1;
uint256 steps;
uint256 t;
uint256 o0;
uint256 o1;
while (true) {
(t, o0, o1) = cp.observations(i);
if (t <= target) break;
if (i == 0 || ++steps >= MAX_OBSERVATION_STEPS) revert PriceUnavailable(token);
--i;
}
uint256 elapsed = nowTs - t;
bool isToken0 = cp.token0() == token;
uint256 rT = (isToken0 ? c0 - o0 : c1 - o1) / elapsed;
uint256 rO = (isToken0 ? c1 - o1 : c0 - o0) / elapsed;
if (rT == 0 || rO == 0) revert PriceUnavailable(token);
quote = Math.mulDiv(baseAmount, rO, rT);
(uint256 s0, uint256 s1,) = cp.getReserves();
(uint256 sT, uint256 sO) = isToken0 ? (s0, s1) : (s1, s0);
if (sT == 0) revert PriceUnavailable(token);
uint256 spot = Math.mulDiv(baseAmount, sO, sT);
uint256 d = spot > quote ? spot - quote : quote - spot;
if (d * 10_000 > quote * uint256(uint24(maxDelta))) revert PriceDiverged(token);
}
/// @notice The other token of a two-token pool, or BadPool(token) if the pool does not contain `token` or
/// does not answer `token0`/`token1`.
function counterpart(address pool, address token) public view returns (address other) {
(bool ok0, address t0) = _addressCall(pool, TOKEN0_SELECTOR);
(bool ok1, address t1) = _addressCall(pool, TOKEN1_SELECTOR);
if (!ok0 || !ok1) revert BadPool(token);
if (t0 == token) return t1;
if (t1 == token) return t0;
revert BadPool(token);
}
/// @notice Mean tick over `window`, reverting PriceDiverged(token) when the pool's current tick has drifted
/// more than `maxDelta` ticks (about one bps each) from it: the signature of an in-progress
/// manipulation or a price still moving.
function checkedTick(address pool, uint32 window, int24 maxDelta, address token) public view returns (int24 mean) {
int24 spot;
(mean, spot) = consultWithSpot(pool, window);
int24 d = spot > mean ? spot - mean : mean - spot;
if (d > maxDelta) revert PriceDiverged(token);
}
/// @notice Arithmetic mean tick of `pool` over the last `window` seconds.
/// @dev Reverts with the pool's own error ("OLD") when its observation history does not reach back far
/// enough. Pools extrapolate from their latest observation, so a quiet pool is fine as long as its
/// last trade is at least `window` seconds old or an older observation exists.
function consult(address pool, uint32 window) public view returns (int24 meanTick) {
if (window == 0) revert ZeroWindow();
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = window;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgos);
int56 delta = tickCumulatives[1] - tickCumulatives[0];
int56 w = int56(uint56(window));
meanTick = int24(delta / w);
// round toward negative infinity, as the pool does
if (delta < 0 && (delta % w != 0)) meanTick--;
}
/// @notice Mean tick over `window` plus the pool's current tick.
function consultWithSpot(address pool, uint32 window) public view returns (int24 meanTick, int24 spotTick) {
meanTick = consult(pool, window);
spotTick = spotTickOf(pool);
}
/// @notice The pool's current tick, read as the second word of `slot0()` so both the seven-word (Uniswap V3)
/// and six-word (Aerodrome Slipstream) layouts decode.
function spotTickOf(address pool) public view returns (int24 spotTick) {
(bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(SLOT0_SELECTOR));
if (!ok || ret.length < 64) revert BadPool(pool);
assembly {
spotTick := mload(add(ret, 64))
}
}
/// @notice The pool's observation cardinality, the fourth word of `slot0()`; both layouts agree.
function cardinalityOf(address pool) public view returns (uint16 cardinality) {
(bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSelector(SLOT0_SELECTOR));
if (!ok || ret.length < 128) revert BadPool(pool);
assembly {
cardinality := mload(add(ret, 128))
}
}
/// @notice How much `quoteToken` (raw) `baseAmount` of `baseToken` (raw) is worth at `tick`.
function quoteAtTick(int24 tick, uint128 baseAmount, address baseToken, address quoteToken)
public
pure
returns (uint256 quoteAmount)
{
uint160 sqrtRatioX96 = getSqrtRatioAtTick(tick);
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? Math.mulDiv(ratioX192, baseAmount, 1 << 192)
: Math.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = Math.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? Math.mulDiv(ratioX128, baseAmount, 1 << 128)
: Math.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
/// @notice sqrt(1.0001^tick) as a Q64.96, exactly as Uniswap V3 computes it.
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
if (absTick > uint256(int256(MAX_TICK))) revert TickOutOfRange();
uint256 ratio =
absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// Q128.128 to Q64.96, rounding up
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
function _addressCall(address target, bytes4 selector) internal view returns (bool ok, address out) {
bytes memory ret;
(ok, ret) = target.staticcall(abi.encodeWithSelector(selector));
if (!ok || ret.length < 32) return (false, address(0));
out = abi.decode(ret, (address));
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/libraries/TwapLib.sol": {
"TwapLib": "0x7Cf68E47f141a9166bA1053114B17987dF6a2fC5"
},
"src/libraries/AutopilotLib.sol": {
"AutopilotLib": "0x57Cfd38B08a111dd2A1979e19B79afB07361e182"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.