Verified contractPartialUNLICENSED
Zap
Address0xd8797eb223e89464045b32cfaf23148bad7caaff
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,184,231
- Creation transaction
- 0x59079dfdd3…710f50a563
34 files
- src/Zap.solmain11.04 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol739 B
- lib/openzeppelin-contracts/contracts/proxy/Clones.sol5.51 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.81 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.38 KB
- lib/openzeppelin-contracts/contracts/utils/ShortStrings.sol4.28 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol3.93 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.82 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol6.61 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol3.7 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol28.31 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- src/CommitRegistry.sol1.74 KB
- src/FeePolicy.sol8.52 KB
- src/HybridWallet.sol34.39 KB
- src/QuantumCanary.sol5.53 KB
- src/WOTS.sol3.35 KB
- src/WintergateFactory.sol4.21 KB
- src/interfaces/IStockereum.sol1.9 KB
- src/interfaces/IUniswapV4.sol1.91 KB
- src/vendor/BitMath.sol2.61 KB
- src/vendor/CustomRevert.sol5.17 KB
- src/vendor/TickMath.sol12.38 KB
src/Zap.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {TickMath} from "./vendor/TickMath.sol";
import {PoolKey, SwapParams, IPoolManager, IUnlockCallback, V4} from "./interfaces/IUniswapV4.sol";
import {IStockereumHook} from "./interfaces/IStockereum.sol";
import {WintergateFactory} from "./WintergateFactory.sol";
import {FeePolicy} from "./FeePolicy.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
/// @dev The subset of a Uniswap v3 pool the zap uses (the WETH/USDC hop for USDC-quoted fee tokens).
interface IUniswapV3PoolLike {
function token0() external view returns (address);
function token1() external view returns (address);
function swap(address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data)
external
returns (int256 amount0, int256 amount1);
}
/// @notice Pay with ETH: swaps ALL the ETH sent (exact input, the only kind Stockereum pools allow) into the fee token
/// through the Stockereum pool the fee policy names, then creates the vault or tops up its protection credit. The fee
/// is a fixed token amount, so no on-chain price is needed: the app quotes the swap off chain and the user's minimum
/// output and deadline bound it (the creation fee plus `minCredit`, or `minOut`). Any surplus is extra protection
/// credit for the vault. Disabled until the fee token is set. Refuses Stockereum's 20-second anti-snipe window. Holds
/// nothing between transactions; periphery, never in the wallet's trust path.
///
/// Convenience premium (owner, 2026-10-08): a caller of the ETH paths may add `premiumBps` (at most MAX_PREMIUM_BPS) on
/// top of what it buys: that many extra tokens are bought and split like a fee, half burned and half to the canary
/// bounty, in the same transaction. Our app passes the premium from its config (20% at launch); a direct caller may
/// pass 0. It is a front-end convenience charge, not a protocol fee: paying in the fee token directly never carries it.
///
/// Routes: WETH-quoted pool: ETH -> WETH -> token on the PoolManager.
/// USDC-quoted pool: ETH -> USDC on the Uniswap v3 WETH/USDC pool, then USDC -> token on the PoolManager.
contract Zap is ReentrancyGuard, IUnlockCallback {
using SafeERC20 for IERC20;
IWETH public immutable WETH;
IERC20 public immutable USD;
IPoolManager public immutable POOL_MANAGER;
IUniswapV3PoolLike public immutable POOL_ETH; // Uniswap v3 WETH/USD, for USDC-quoted fee tokens
bool public immutable WETH_IS_TOKEN0_ETH;
WintergateFactory public immutable FACTORY;
FeePolicy public immutable FEES;
/// @dev Hard cap on the convenience premium a caller may ask for: a buggy front end can never charge more.
uint16 public constant MAX_PREMIUM_BPS = 5_000;
bool private _inV3; // inside the swap on POOL_ETH
event Bought(address indexed payer, uint256 ethIn, uint256 tokensOut);
event Created(address indexed wallet, address indexed payer, uint256 fee, uint256 credit, uint256 ethIn);
event ToppedUp(address indexed wallet, address indexed payer, uint256 credit, uint256 ethIn);
event Premium(address indexed payer, uint256 tokens);
constructor(IWETH weth_, IERC20 usd_, IPoolManager poolManager_, IUniswapV3PoolLike poolEth_, WintergateFactory factory_) {
WETH = weth_;
USD = usd_;
POOL_MANAGER = poolManager_;
POOL_ETH = poolEth_;
FACTORY = factory_;
FEES = FeePolicy(address(factory_.FEES()));
(address b0, address b1) = (poolEth_.token0(), poolEth_.token1());
bool weth0 = b0 == address(weth_);
require(weth0 ? b1 == address(usd_) : (b0 == address(usd_) && b1 == address(weth_)), "zap: eth pool");
WETH_IS_TOKEN0_ETH = weth0;
}
receive() external payable {} // WETH.withdraw refunds
// ------------------------------------------------------------------ entry points
/// @notice Create a vault with ETH: the fixed creation fee plus at least `minCredit` of protection credit, plus the
/// premium (`premiumBps` of fee + minCredit, split like a fee), all from msg.value. Surplus is the vault's credit.
function createWithEth(WintergateFactory.CreateParams calldata p, uint256 minCredit, uint16 premiumBps, uint256 deadline)
external
payable
nonReentrant
returns (address wallet)
{
require(block.timestamp <= deadline, "zap: expired");
require(premiumBps <= MAX_PREMIUM_BPS, "zap: premium above cap");
IERC20 token = _token();
uint256 fee = FEES.createFee();
uint256 premium = ((fee + minCredit) * premiumBps) / 10_000;
uint256 out = _buy(msg.value);
require(out >= fee + minCredit + premium, "zap: min out");
if (premium > 0) _payPremium(token, premium); // split by the factory's settle together with the fee
token.forceApprove(address(FACTORY), fee);
wallet = FACTORY.createWallet(p, fee);
if (premium > 0) FEES.settle(); // a no-op when the factory already split it; covers a zero creation fee
uint256 credit = out - fee - premium;
if (credit > 0) token.safeTransfer(wallet, credit);
_refund();
emit Created(wallet, msg.sender, fee, credit, msg.value);
}
/// @notice Add at least `minOut` of protection credit to a vault, plus the premium (`premiumBps` of minOut, split like
/// a fee), paid with all of msg.value. Surplus is credit.
function topUpWithEth(address wallet, uint256 minOut, uint16 premiumBps, uint256 deadline) external payable nonReentrant {
require(block.timestamp <= deadline, "zap: expired");
require(premiumBps <= MAX_PREMIUM_BPS, "zap: premium above cap");
require(FACTORY.isWallet(wallet), "zap: not a wallet");
IERC20 token = _token();
uint256 premium = (minOut * premiumBps) / 10_000;
uint256 out = _buy(msg.value);
require(out >= minOut + premium && out > premium, "zap: min out");
if (premium > 0) {
_payPremium(token, premium);
FEES.settle();
}
uint256 credit = out - premium;
token.safeTransfer(wallet, credit);
_refund();
emit ToppedUp(wallet, msg.sender, credit, msg.value);
}
/// @dev The premium goes to the fee policy, whose settle() splits it half burned, half to the canary bounty.
function _payPremium(IERC20 token, uint256 premium) internal {
token.safeTransfer(address(FEES), premium);
emit Premium(msg.sender, premium);
}
function _token() internal view returns (IERC20 token) {
token = FEES.feeToken();
require(address(token) != address(0), "zap: no fee token yet");
}
// ------------------------------------------------------------------ the swap
function _buy(uint256 ethIn) internal returns (uint256 out) {
require(ethIn > 0, "zap: zero");
IERC20 token = FEES.feeToken();
bool quoteIsEth = FEES.quoteIsEth();
bool quoteIsToken0 = FEES.quoteIsToken0();
IStockereumHook hook = FEES.STOCKEREUM_HOOK();
IStockereumHook.Launch memory l = hook.getLaunch(FEES.v4PoolId());
require(block.timestamp >= uint256(l.openedAt) + hook.ANTI_SNIPE_DURATION(), "zap: anti-snipe window");
uint256 before = token.balanceOf(address(this));
WETH.deposit{value: ethIn}();
uint256 quoteAmount = ethIn;
if (!quoteIsEth) quoteAmount = _ethToUsd(ethIn); // all the WETH -> USDC on the v3 WETH/USDC pool
// no price limit: the whole input is spent, and the caller's minimum output bounds the fill
POOL_MANAGER.unlock(abi.encode(_key(), quoteIsToken0, quoteAmount, _noLimit(quoteIsToken0)));
out = token.balanceOf(address(this)) - before;
emit Bought(msg.sender, ethIn, out);
}
function _key() internal view returns (PoolKey memory k) {
(k.currency0, k.currency1, k.fee, k.tickSpacing, k.hooks) = FEES.v4Key();
}
function _noLimit(bool zeroForOne) internal pure returns (uint160) {
return zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1;
}
/// @dev All the WETH -> USDC on the v3 WETH/USDC pool (exact input, no price limit; the final minimum output
/// bounds the whole route).
function _ethToUsd(uint256 wethIn) internal returns (uint256 usdOut) {
uint256 before = USD.balanceOf(address(this));
_inV3 = true;
POOL_ETH.swap(address(this), WETH_IS_TOKEN0_ETH, int256(wethIn), _noLimit(WETH_IS_TOKEN0_ETH), "");
_inV3 = false;
usdOut = USD.balanceOf(address(this)) - before;
}
function uniswapV3SwapCallback(int256 d0, int256 d1, bytes calldata) external {
require(_inV3 && msg.sender == address(POOL_ETH), "zap: callback");
int256 owed = WETH_IS_TOKEN0_ETH ? d0 : d1;
if (owed > 0) IERC20(address(WETH)).safeTransfer(msg.sender, uint256(owed));
}
/// @dev Uniswap v4: exact-input swap of the quote currency for the fee token, settled from this contract's balance.
function unlockCallback(bytes calldata data) external returns (bytes memory) {
require(msg.sender == address(POOL_MANAGER), "zap: callback");
(PoolKey memory key, bool zeroForOne, uint256 amountIn, uint160 limit) =
abi.decode(data, (PoolKey, bool, uint256, uint160));
int256 delta = POOL_MANAGER.swap(key, SwapParams(zeroForOne, -int256(amountIn), limit), "");
int128 dIn = zeroForOne ? V4.amount0(delta) : V4.amount1(delta);
int128 dOut = zeroForOne ? V4.amount1(delta) : V4.amount0(delta);
require(dIn <= 0 && dOut >= 0, "zap: delta");
address inCur = zeroForOne ? key.currency0 : key.currency1;
address outCur = zeroForOne ? key.currency1 : key.currency0;
uint256 spent = uint256(uint128(-dIn));
POOL_MANAGER.sync(inCur);
IERC20(inCur).safeTransfer(address(POOL_MANAGER), spent);
POOL_MANAGER.settle();
uint256 got = uint256(uint128(dOut));
if (got > 0) POOL_MANAGER.take(outCur, address(this), got);
return abi.encode(spent, got);
}
/// @dev Anything not spent (a v4 swap that ran out of liquidity) goes back to the payer as ETH.
function _refund() internal {
uint256 wethLeft = WETH.balanceOf(address(this));
if (wethLeft > 0) WETH.withdraw(wethLeft);
uint256 usdLeft = USD.balanceOf(address(this));
if (usdLeft > 0) USD.safeTransfer(msg.sender, usdLeft);
uint256 bal = address(this).balance;
if (bal > 0) {
(bool ok,) = msg.sender.call{value: bal}("");
require(ok, "zap: refund");
}
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
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.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
lib/openzeppelin-contracts/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/Clones.sol)
pragma solidity ^0.8.20;
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 {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
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.
*
* 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(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, 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 behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
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.
*
* 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(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, 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));
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.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);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
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, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @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, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @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, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @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.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// 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 (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @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) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
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/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.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
lib/openzeppelin-contracts/contracts/utils/ShortStrings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
assembly ("memory-safe") {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
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/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 derives the `address(0)`.
*/
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.
*
* 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 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.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Name() internal view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Version() internal view returns (string memory) {
return _version.toStringWithFallback(_versionFallback);
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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.1.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 Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @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 {
if (b == 0) return (false, 0);
return (true, 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 {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = 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 = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 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 prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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 {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, 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 prod1 into prod0.
prod0 |= prod1 * 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 prod1
// is no longer required.
result = prod0 * 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 Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @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 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @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;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/CommitRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @notice Commit-now registry: timestamped commitments to a hash-key root, written by the factory for every wallet it
/// creates. The first commitment of an account is immutable; later ones append. Evidence for a future chain-level
/// quantum recovery scheme (proof of when a key was committed). It plays no part in leaf safety: the per-leaf commit
/// lives inside HybridWallet. Personal build: factory path only (the co-signed `commitFor` of rc3 is gone), and the
/// factory deploys this registry itself, so there is no wiring step and no deployer right.
contract CommitRegistry {
struct Commit {
bytes32 commitment;
uint64 at;
}
address public immutable FACTORY;
mapping(address => Commit[]) internal _commits;
event Committed(address indexed account, bytes32 commitment, uint256 index);
constructor(address factory_) {
require(factory_ != address(0), "commit: zero");
FACTORY = factory_;
}
function count(address account) external view returns (uint256) {
return _commits[account].length;
}
function get(address account, uint256 i) external view returns (Commit memory) {
return _commits[account][i];
}
function first(address account) external view returns (Commit memory) {
return _commits[account][0];
}
function recordFor(address account, bytes32 commitment) external {
require(msg.sender == FACTORY, "commit: factory");
require(commitment != bytes32(0), "commit: zero");
_commits[account].push(Commit(commitment, uint64(block.timestamp)));
emit Committed(account, commitment, _commits[account].length - 1);
}
}
src/FeePolicy.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {PoolKey, IStateView, V4} from "./interfaces/IUniswapV4.sol";
import {IStockereumHook, IStockereumFactory} from "./interfaces/IStockereum.sol";
import {QuantumCanary, IFeeTokenSource} from "./QuantumCanary.sol";
interface ICanary {
function fired() external view returns (bool);
function bounty() external view returns (uint256);
}
interface IBurnable {
function burn(uint256 amount) external;
function totalSupply() external view returns (uint256);
}
/// @notice The WGATE protection fee: FIXED token amounts, set at deploy and never changed. Creating a vault costs
/// CREATE_FEE, each protected action ACTION_FEE (both in fee-token wei, 18 decimals). Exits never touch this contract.
///
/// The fee token arrives AFTER deploy (the team launches WGATE through Stockereum on Uniswap v4): until it is set every
/// vault creation and protected action is FREE and fully usable, and the zap is disabled. `setFeeTokenV4` is the ONE
/// post-deploy setting in the whole system: callable only by the immutable-at-deploy `feeTokenSetter` (a throwaway
/// launch key), it succeeds once, clears the setter and can never run again. It can never move anyone's funds: it only
/// names the token and its Stockereum pool (the zap buys through it), and every exit of every vault ignores this
/// contract entirely. There is no price, no average, no oracle: the fee in the fee token is the same forever.
///
/// Split, in the same transaction as the payment (`settle`, called by the factory and every vault right after paying):
/// half to the quantum canary bounty, the rest burned (token `burn()` when it really burns, else 0x...dEaD). Once the
/// canary has fired its half is burned too (a fired canary can never pay out again). This contract holds no fees
/// between transactions.
contract FeePolicy is ReentrancyGuard {
using SafeERC20 for IERC20;
address public constant DEAD = 0x000000000000000000000000000000000000dEaD;
struct Params {
IERC20 usd; // USDC: an allowed Stockereum quote asset
address weth; // WETH: the other allowed quote asset
IStateView stateView; // Uniswap v4 lens (pool initialised check)
IStockereumHook stockereumHook;
IStockereumFactory stockereumFactory;
address feeTokenSetter; // the throwaway launch key; zero = fee token never set (free forever)
bytes32 canarySeed; // the quantum canary is deployed here (its bounty is the fee token)
uint256 createFee; // fee-token wei: 1_000e18 = 1,000 WGATE
uint256 actionFee; // fee-token wei: 50e18 = 50 WGATE
}
IERC20 public immutable USD;
address public immutable WETH;
IStateView public immutable STATE_VIEW;
IStockereumHook public immutable STOCKEREUM_HOOK;
IStockereumFactory public immutable STOCKEREUM_FACTORY;
ICanary public immutable CANARY;
uint256 public immutable CREATE_FEE;
uint256 public immutable ACTION_FEE;
// ---- the one write-once setting
address public feeTokenSetter; // cleared after the one call
IERC20 public feeToken; // zero until set: everything is free
bool public quoteIsToken0; // in the Stockereum pool: is the quote asset (USDC or WETH) currency0
bool public quoteIsEth; // quote is WETH rather than USDC
PoolKey public v4Key;
bytes32 public v4PoolId;
uint256 public totalSettled;
uint256 public totalBurned;
uint256 public totalToCanary;
event FeeTokenSet(address indexed token, address pool, bytes32 poolId, bool quoteIsEth);
event Settled(uint256 amount, uint256 burned, uint256 toCanary);
constructor(Params memory p) {
require(address(p.usd) != address(0) && p.weth != address(0), "fee: zero");
require(address(p.stateView) != address(0) && address(p.stockereumHook) != address(0), "fee: v4");
require(p.createFee <= 1e30 && p.actionFee <= 1e30, "fee: amount"); // at most 1e12 tokens: a typo guard
USD = p.usd;
WETH = p.weth;
STATE_VIEW = p.stateView;
STOCKEREUM_HOOK = p.stockereumHook;
STOCKEREUM_FACTORY = p.stockereumFactory;
feeTokenSetter = p.feeTokenSetter;
CANARY = ICanary(address(new QuantumCanary(IFeeTokenSource(address(this)), p.canarySeed)));
CREATE_FEE = p.createFee;
ACTION_FEE = p.actionFee;
}
// ------------------------------------------------------------------ the one write-once setting
/// @notice Name the fee token and its Stockereum pool (Uniswap v4). Once. Verified on chain: the pool belongs to
/// the Stockereum hook and records exactly this token, the quote is WETH or USDC, the pool is initialised.
function setFeeTokenV4(address token, PoolKey calldata key) external {
require(msg.sender == feeTokenSetter && msg.sender != address(0), "fee: not the setter");
require(address(feeToken) == address(0), "fee: already set");
require(token.code.length > 0, "fee: token not a contract");
require(key.hooks == address(STOCKEREUM_HOOK), "fee: not a Stockereum pool");
bytes32 id = V4.poolId(key);
IStockereumHook.Launch memory l = STOCKEREUM_HOOK.getLaunch(id);
require(l.token == token && l.liquidity > 0, "fee: not this token's launch");
require(l.quote == WETH || l.quote == address(USD), "fee: quote must be WETH or USDC");
address other = key.currency0 == token ? key.currency1 : key.currency0;
require((key.currency0 == token || key.currency1 == token) && other == l.quote, "fee: key mismatch");
(uint160 sqrtP,,,) = STATE_VIEW.getSlot0(id);
require(sqrtP != 0, "fee: pool not initialised");
feeToken = IERC20(token);
v4Key = key;
v4PoolId = id;
quoteIsToken0 = key.currency0 == l.quote;
quoteIsEth = l.quote == WETH;
feeTokenSetter = address(0);
emit FeeTokenSet(token, address(STOCKEREUM_HOOK), id, quoteIsEth);
}
// ------------------------------------------------------------------ fees
/// @notice The fee to create a vault: CREATE_FEE, or 0 before the fee token is set.
function createFee() external view returns (uint256) {
return address(feeToken) == address(0) ? 0 : CREATE_FEE;
}
/// @notice The fee for one protected action: ACTION_FEE, or 0 before the fee token is set.
function actionFee() external view returns (uint256) {
return address(feeToken) == address(0) ? 0 : ACTION_FEE;
}
// ------------------------------------------------------------------ split
/// @notice Split everything held: half to the canary bounty, the rest burned. The factory and every vault call it
/// in the same transaction right after paying, so nothing waits here. Anyone may call it; conservation is exact.
function settle() external nonReentrant returns (uint256 burned, uint256 toCanary) {
IERC20 token = feeToken;
if (address(token) == address(0)) return (0, 0);
uint256 amt = token.balanceOf(address(this));
if (amt == 0) return (0, 0);
toCanary = CANARY.fired() ? 0 : amt / 2;
burned = amt - toCanary;
if (toCanary > 0) token.safeTransfer(address(CANARY), toCanary); // the bounty is the canary's balance
_burn(token, burned);
totalSettled += amt;
totalBurned += burned;
totalToCanary += toCanary;
emit Settled(amt, burned, toCanary);
}
/// @dev `burn()` when the token has one that really reduces the supply (WGToken does); otherwise the dead address
/// (Stockereum launch tokens have no burn function).
function _burn(IERC20 token, uint256 amount) internal {
uint256 s0 = IBurnable(address(token)).totalSupply();
uint256 b0 = token.balanceOf(address(this));
try IBurnable(address(token)).burn(amount) {
if (IBurnable(address(token)).totalSupply() == s0 - amount && token.balanceOf(address(this)) == b0 - amount) return;
} catch {}
// the attempt either reverted or did not burn: nothing left this contract (checked), so send to the dead address
require(token.balanceOf(address(this)) == b0, "fee: burn moved funds");
token.safeTransfer(DEAD, amount);
}
}
src/HybridWallet.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {WOTS} from "./WOTS.sol";
interface ICanaryFlag {
function fired() external view returns (bool);
}
interface IActionFee {
function actionFee() external view returns (uint256);
function feeToken() external view returns (IERC20);
function settle() external returns (uint256 burned, uint256 toCanary);
}
/// @notice Wintergate hybrid wallet, Personal build (deployed only as a clone by the factory). Server-free.
///
/// Authorisation of an action = the owner's factors, and nothing else:
/// - Mode A: owner ECDSA AND one-time hash-key (WOTS leaf) signature, always.
/// Mode B: owner ECDSA until the canary fires, hash key after. Changing the hash-key root, the recovery
/// commitment or the exit address always needs the hash key under the current root.
/// - Commit-then-sign (replaces the co-signing service of rc3): before a leaf signs anything, the owner records on
/// chain which digest that leaf will sign (`commitLeaf`). The record is write-once per (root, leaf) and never
/// cleared (C1). A commit needs the owner's ECDSA signature over Pledge(root, leaf, digest), the SAME signature
/// the action itself uses, so the user signs once per action, plus a Merkle proof that the submitter knows the
/// leaf's WOTS public key (C2). A hash-key signature is accepted only for the committed digest, unless the
/// owner's escape hatch is active (C3), or it is the owner's cancel of a pending recovery (rc6: the owner's veto
/// must not be blockable by junk commits). The escape (7 days) is the way out of commit griefing; it is started by
/// the owner factors (with a commit), by the recovery key (no commit; rc6), and by the vault itself when a recovery
/// is cancelled or an exit uses the last exit leaf (rc6), so junk commits can never freeze a vault for good.
/// - Fee: every protected `execute` pays the fixed action fee (in the fee token the policy names; zero and free until
/// the token is set after launch) from the vault's own balance to the fee policy, which splits it at once (half
/// burned, half to the canary bounty), before the inner call, bounded by the user-signed `maxFee`. The vault holds no token address of its own. Exits are ALWAYS fee-free: requestEscape,
/// escapeWithRecoveryKey, cancelRecoveryByOwner, initiateRecovery, finalizeRecovery, evacuate, every action once
/// the escape is active, and the hash-key rotation made when no exit leaf is left. None of them reads the fee
/// policy at all.
///
/// Nothing anyone else runs is in the path of any action, exit or recovery. Recovery with the recovery key takes
/// RECOVERY_DELAY (deploy-time constant); the owner can cancel it within the delay with the hash key.
///
/// The recovery key is a ONE-TIME HASH-BASED key (rc6, AI audit G-2): a single WOTS key (the same scheme as the hash
/// key, tweak index RECOVERY_LEAF), and `recoveryCommit = keccak256(abi.encode(seed, publicKey))`. Its signature
/// on one recovery (or one recovery-key escape) shows nothing that lets anyone sign anything else, so watching the
/// mempool, a relay or a block builder gives no way to take the recovery over, whatever ECDSA break exists. (rc5 and
/// earlier used an ECDSA recovery key, whose first signature showed its public key.) A one-time key must sign once:
/// the first accepted signature marks the commitment spent for good, and a spent commitment can never be installed
/// again (setRecoveryCommit, a recovery's new commitment).
contract HybridWallet is EIP712, ReentrancyGuard {
using SafeERC20 for IERC20;
bytes32 public constant EXECUTE_TYPEHASH = keccak256(
"Execute(address to,uint256 value,bytes32 dataHash,uint256 gasLimit,uint256 nonce,uint32 leaf,uint256 deadline,uint256 maxFee)"
);
bytes32 public constant ESCAPE_TYPEHASH = keccak256("Escape(uint256 nonce,uint32 leaf)");
/// @dev The delay the recovery key holder consents to is part of what they sign (Fable FR2-I1): a signature made
/// for a deployment with another delay is invalid here.
bytes32 public constant RECOVERY_TYPEHASH = keccak256(
"Recovery(address newOwner,bytes32 newRoot,bytes32 newSeed,bytes32 newRecoveryCommit,uint256 nonce,uint256 deadline,uint256 delay)"
);
/// @notice What the recovery key signs to start the 7-day escape without the owner factors (rc6).
bytes32 public constant RECOVERY_ESCAPE_TYPEHASH = keccak256("RecoveryEscape(uint256 nonce,uint256 delay)");
/// @notice WOTS tweak index of the recovery key: outside the hash-key tree (leaves 0..1023), so a recovery key and
/// a hash key can never share a chain value.
uint32 public constant RECOVERY_LEAF = type(uint32).max;
/// @dev rc6: the cancel names the recovery it cancels (its recoveryNonce), not the owner nonce, so devices that
/// cancel the same recovery at the same leaf sign the same digest even if the owner nonce moved (council v4 G-7).
bytes32 public constant CANCEL_RECOVERY_TYPEHASH = keccak256("CancelRecovery(uint256 recoveryNonce,uint32 leaf)");
bytes32 public constant EVACUATE_TYPEHASH = keccak256("Evacuate(uint256 nonce,uint32 leaf,bytes32 tokensHash)");
/// @notice What the owner's ECDSA key signs for every hash-key action: the leaf and the digest it will sign.
bytes32 public constant PLEDGE_TYPEHASH = keccak256("Pledge(bytes32 root,uint32 leaf,bytes32 digest)");
uint8 public constant MODE_A = 1;
uint8 public constant MODE_B = 2;
uint256 public constant ESCAPE_DELAY = 7 days;
uint256 internal constant GAS_RESERVE = 20_000;
/// @notice The top TAIL leaves are reserved for emergency and rotation actions (rotateHashKey executes,
/// requestEscape, cancelRecoveryByOwner, evacuate). Ordinary actions stop at NORMAL_LEAVES, so a wallet can
/// never be pushed into a state where it cannot rotate its hash key or leave.
uint32 public constant TAIL = 16;
uint32 public constant NORMAL_LEAVES = uint32(WOTS.LEAVES) - TAIL;
/// @notice Escape, owner-cancel and evacuate may not use the last 4 tail leaves, which only rotation can use, so
/// an exit can never leave a wallet unable to rotate (audit r2 M2).
uint32 public constant EMERGENCY_LEAVES = uint32(WOTS.LEAVES) - 4;
/// @notice An ordinary action (or commit) may skip at most this many leaves past `nextLeaf` (dropped
/// transactions leave gaps). Stops one action from burning the whole ordinary range (Fable FR1-L3). Tail
/// actions (rotation, escape, cancel, evacuate) are not bounded.
uint32 public constant MAX_LEAF_GAP = 64;
/// @notice Every asset call of evacuate (balanceOf, transfer, the ETH send) starts with exactly this much gas
/// (the 2,300 value stipend included), or the whole evacuate reverts. So the relayer's gas limit can never cut
/// what an asset gets (AI audit G-4), and one asset can burn at most this much (AI audit G-5). Not covered (AI
/// audit G-8): the submitter can change what an asset's call costs, by warming storage with an access list or by
/// changing the token's state earlier in the same transaction (a swap-back threshold, a rebase, a hook), so an
/// asset whose cost can come near the limit may land differently. The asset then stays in the vault, never lost.
/// An asset that needs more cannot be evacuated; the owner moves it with an ordinary action (signed gas limit).
uint256 public constant ASSET_CALL_GAS = 300_000;
address public immutable FACTORY;
ICanaryFlag public immutable CANARY;
IActionFee public immutable FEES;
/// @notice Solo recovery delay, fixed at deploy (owner decision; 30 days by default).
uint256 public immutable RECOVERY_DELAY;
struct Call {
address to;
uint256 value;
bytes data;
uint256 gasLimit;
uint256 nonce;
uint32 leaf;
uint256 deadline;
/// @dev The most WGATE the owner agrees to pay for this action (user-signed maximum fee).
uint256 maxFee;
}
struct HashSig {
bytes32[67] sig;
bytes32[10] auth;
}
struct PendingRecovery {
address newOwner;
bytes32 newRoot;
bytes32 newSeed;
bytes32 newRecoveryCommit;
uint64 readyAt;
}
bool public initialized;
address public owner;
bytes32 public hashRoot;
bytes32 public pubSeed;
bytes32 public recoveryCommit;
uint8 public mode;
uint256 public nonce;
uint32 public nextLeaf;
uint64 public escapeAt; // 0 = not requested
uint256 public recoveryNonce;
PendingRecovery public pendingRecovery;
mapping(bytes32 => bool) public usedRoot;
/// @notice (root, leaf) -> the one digest that leaf may sign. Write-once; never cleared, never expires (C1).
mapping(bytes32 => mapping(uint32 => bytes32)) public committed;
/// @notice Pre-set exit address for the fee-free evacuate path (zero = not set).
address public exitAddress;
/// @notice Recovery commitments whose one-time key has signed (rc6). Spent for good: never usable or installable again.
mapping(bytes32 => bool) public spentRecoveryCommit;
event LeafCommitted(bytes32 indexed root, uint32 indexed leaf, bytes32 digest);
event Executed(uint256 indexed nonce, uint32 leaf, address indexed to, uint256 value, uint256 fee, bool success, bytes returnData);
event EscapeRequested(uint64 at);
event EscapeCancelled();
event RecoveryStarted(address newOwner, bytes32 newRoot, uint64 readyAt);
event RecoveryCancelled();
event RecoveryFinalized(address newOwner, bytes32 newRoot);
event OwnerRotated(address newOwner);
event HashKeyRotated(bytes32 newRoot, bytes32 newSeed);
event RecoveryCommitSet(bytes32 commit);
event RecoveryKeySpent(bytes32 commit);
event ExitAddressSet(address exit);
event Evacuated(uint256 indexed nonce, address indexed token, address indexed to, uint256 amount, bool success);
constructor(address factory_, ICanaryFlag canary_, IActionFee fees_, uint256 recoveryDelay_) EIP712("Wintergate", "2") {
// longer than the escape, so an escape armed when the exits run out is active before any recovery can finish
// (council a-wg-rc6-g2-v4 G-6)
require(recoveryDelay_ >= ESCAPE_DELAY + 1 days && recoveryDelay_ <= 365 days, "wallet: recovery delay");
FACTORY = factory_;
CANARY = canary_;
FEES = fees_;
RECOVERY_DELAY = recoveryDelay_;
initialized = true; // the implementation itself is never usable
}
receive() external payable {}
function initialize(address owner_, bytes32 root_, bytes32 seed_, bytes32 recoveryCommit_, uint8 mode_, address exit_)
external
{
require(msg.sender == FACTORY && !initialized, "wallet: init");
require(owner_ != address(0) && root_ != bytes32(0) && (mode_ == MODE_A || mode_ == MODE_B), "wallet: params");
// rc6 invariant (council v4 G-5): without an escape timer, a vault always has a usable recovery key, so the
// commit-free recovery-key escape can always start the escape, whatever junk commits anyone sends
require(recoveryCommit_ != bytes32(0), "wallet: recovery key");
initialized = true;
owner = owner_;
hashRoot = root_;
pubSeed = seed_;
recoveryCommit = recoveryCommit_;
mode = mode_;
exitAddress = exit_;
usedRoot[root_] = true;
}
// ------------------------------------------------------------------ views
function executeDigest(Call calldata c) public view returns (bytes32) {
return _hashTypedDataV4(
keccak256(
abi.encode(EXECUTE_TYPEHASH, c.to, c.value, keccak256(c.data), c.gasLimit, c.nonce, c.leaf, c.deadline, c.maxFee)
)
);
}
function escapeDigest(uint256 n, uint32 leaf) public view returns (bytes32) {
return _hashTypedDataV4(keccak256(abi.encode(ESCAPE_TYPEHASH, n, leaf)));
}
function recoveryDigest(
address newOwner,
bytes32 newRoot,
bytes32 newSeed,
bytes32 newRecoveryCommit,
uint256 n,
uint256 deadline
) public view returns (bytes32) {
return _hashTypedDataV4(
keccak256(abi.encode(RECOVERY_TYPEHASH, newOwner, newRoot, newSeed, newRecoveryCommit, n, deadline, RECOVERY_DELAY))
);
}
function recoveryEscapeDigest(uint256 n) public view returns (bytes32) {
return _hashTypedDataV4(keccak256(abi.encode(RECOVERY_ESCAPE_TYPEHASH, n, ESCAPE_DELAY)));
}
/// @notice The recovery commitment of a one-time recovery key: its tweak seed and WOTS public key (the keccak of
/// seed, RECOVERY_LEAF and the 67 chain ends, as WOTS.leafFromSig computes it).
function recoveryCommitOf(bytes32 recoverySeed, bytes32 recoveryPk) public pure returns (bytes32) {
return keccak256(abi.encode(recoverySeed, recoveryPk));
}
function cancelRecoveryDigest(uint256 rn, uint32 leaf) public view returns (bytes32) {
return _hashTypedDataV4(keccak256(abi.encode(CANCEL_RECOVERY_TYPEHASH, rn, leaf)));
}
function evacuateDigest(uint256 n, uint32 leaf, address[] calldata tokens) public view returns (bytes32) {
return _hashTypedDataV4(keccak256(abi.encode(EVACUATE_TYPEHASH, n, leaf, keccak256(abi.encodePacked(tokens)))));
}
function pledgeDigest(bytes32 root, uint32 leaf, bytes32 digest) public view returns (bytes32) {
return _hashTypedDataV4(keccak256(abi.encode(PLEDGE_TYPEHASH, root, leaf, digest)));
}
function escapeActive() public view returns (bool) {
return escapeAt != 0 && block.timestamp >= escapeAt;
}
/// @notice Which owner factors the next action needs: (ecdsa, hashKey).
function requirements(bool rootChange) public view returns (bool needEcdsa, bool needHash) {
bool flag = CANARY.fired();
if (mode == MODE_A) return (true, true);
needEcdsa = !flag;
needHash = flag || rootChange;
}
// ------------------------------------------------------------------ commit (step 1 of every hash-key action)
/// @notice Bind leaf `leaf` of the current root to `digest`, for good. Anyone may submit it; it carries no secret
/// and no hash-key signature. Gas only, no WGATE.
/// @param leafPk the WOTS public key of the leaf (keccak of its 67 chain ends): hash-key possession without
/// spending the leaf, so that after an ECDSA break nobody can burn leaves with junk commits
/// @param auth the Merkle authentication path of the leaf (the same path the signature will use)
/// @param ownerSig the owner's signature over Pledge(root, leaf, digest); the action reuses the same signature
function commitLeaf(uint32 leaf, bytes32 digest, bytes32 leafPk, bytes32[10] calldata auth, bytes calldata ownerSig)
external
{
bytes32 root = hashRoot;
require(leaf >= nextLeaf && leaf < WOTS.LEAVES, "wallet: leaf");
if (leaf < NORMAL_LEAVES) require(leaf <= nextLeaf + MAX_LEAF_GAP, "wallet: leaf gap");
require(digest != bytes32(0) && committed[root][leaf] == bytes32(0), "wallet: leaf committed");
require(ECDSA.recover(pledgeDigest(root, leaf, digest), ownerSig) == owner, "wallet: owner sig");
require(WOTS.rootFromLeaf(pubSeed, leaf, leafPk, auth) == root, "wallet: leaf proof");
committed[root][leaf] = digest;
emit LeafCommitted(root, leaf, digest);
}
// ------------------------------------------------------------------ core
/// @param limit exclusive upper bound for the leaf: NORMAL_LEAVES, EMERGENCY_LEAVES or LEAVES (rotation)
/// @param commitFree the owner's cancel of a pending recovery: no commit needed (see cancelRecoveryByOwner)
function _ownerAuth(
bytes32 d,
uint32 leaf,
bytes calldata ownerSig,
HashSig calldata h,
bool rootChange,
uint32 limit,
bool commitFree
) internal {
require(leaf >= nextLeaf && leaf < limit, "wallet: leaf");
if (limit == NORMAL_LEAVES) require(leaf <= nextLeaf + MAX_LEAF_GAP, "wallet: leaf gap");
(bool needEcdsa, bool needHash) = requirements(rootChange);
bytes32 root = hashRoot;
if (needEcdsa) require(ECDSA.recover(pledgeDigest(root, leaf, d), ownerSig) == owner, "wallet: owner sig");
if (needHash) {
// The leaf may only ever sign the digest it was committed to, unless the owner escaped the rule (C3).
if (!commitFree && !escapeActive()) require(committed[root][leaf] == d, "wallet: not committed");
require(WOTS.verify(root, pubSeed, leaf, d, h.sig, h.auth), "wallet: hash sig");
}
// Burn the leaf before anything external happens: a leaf lands at most once.
nextLeaf = leaf + 1;
}
/// @dev Is there a leaf an exit could still commit and use? Exits take any leaf from nextLeaf below
/// EMERGENCY_LEAVES, but an ordinary-range leaf can only be committed within MAX_LEAF_GAP of nextLeaf, so at most
/// 65 + 12 leaves are read. Called only for a rotation from the reserve.
function _freeExitLeafLeft() internal view returns (bool) {
bytes32 root = hashRoot;
uint32 from = nextLeaf;
uint32 normalEnd = from + MAX_LEAF_GAP + 1;
if (normalEnd > NORMAL_LEAVES) normalEnd = NORMAL_LEAVES;
for (uint32 l = from; l < normalEnd; ++l) {
if (committed[root][l] == bytes32(0)) return true;
}
for (uint32 l = from > NORMAL_LEAVES ? from : NORMAL_LEAVES; l < EMERGENCY_LEAVES; ++l) {
if (committed[root][l] == bytes32(0)) return true;
}
return false;
}
function _selfSelector(address to, bytes calldata data) internal view returns (bytes4) {
if (to != address(this) || data.length < 4) return bytes4(0);
return bytes4(data[:4]);
}
/// @dev The action fee, paid from the vault's own balance before the inner call. Zero once the escape is active
/// (every action is then an exit) and zero while no fee token is set. A short balance reverts the whole
/// transaction: nothing is written, the commit still binds the digest, the same signature is re-sent after a top-up.
function _chargeFee(uint256 maxFee) internal returns (uint256 fee) {
if (escapeActive()) return 0;
fee = FEES.actionFee();
require(fee <= maxFee, "wallet: fee above max");
if (fee > 0) {
IERC20 token = FEES.feeToken();
require(token.balanceOf(address(this)) >= fee, "wallet: fee unpaid");
token.safeTransfer(address(FEES), fee);
FEES.settle();
}
}
function execute(Call calldata c, bytes calldata ownerSig, HashSig calldata h)
external
nonReentrant
returns (bool success, bytes memory ret)
{
require(block.timestamp <= c.deadline, "wallet: expired");
require(c.nonce == nonce, "wallet: nonce");
bytes32 d = executeDigest(c);
bytes4 sel = _selfSelector(c.to, c.data);
bool rotation = sel == this.rotateHashKey.selector;
// Changing the recovery commitment is a path to a new root (via recovery), and the exit address is where
// evacuate sends everything: both need the hash key too.
bool rootChange = rotation || sel == this.setRecoveryCommit.selector || sel == this.setExitAddress.selector;
// No exit leaf left (nextLeaf at the rotation reserve): the rotation that gives the exits back is itself an exit,
// so it is fee-free. Otherwise escape, owner cancel and evacuate would need the fee token first (Opus P6 M-1).
// Also when exit leaves remain but every one of them is already bound to a digest (dead commits): then a
// rotation from the reserve (1020..1023) is the only way out, so it is fee-free too (AI audit G-1). With a
// free exit leaf left it still pays, as before.
bool exitsGone =
rotation && (nextLeaf >= EMERGENCY_LEAVES || (c.leaf >= EMERGENCY_LEAVES && !_freeExitLeafLeft()));
_ownerAuth(d, c.leaf, ownerSig, h, rootChange, rotation ? uint32(WOTS.LEAVES) : NORMAL_LEAVES, false);
nonce = c.nonce + 1;
uint256 fee = exitsGone ? 0 : _chargeFee(c.maxFee);
// The signed gas limit must be available to the call, so a relayer cannot starve it.
// margin covers copying the calldata into memory for the call (L1)
require(gasleft() >= (c.gasLimit * 64) / 63 + GAS_RESERVE + c.data.length * 2, "wallet: gas");
(success, ret) = c.to.call{value: c.value, gas: c.gasLimit}(c.data);
// A rotation lands whole or not at all: a failed one (a gas limit too small, a used root) must not burn a
// reserve leaf while keeping the old root, or a failure on leaf 1023 leaves no leaf at all (AI audit NEW-3).
require(!rotation || success, "wallet: rotation failed");
emit Executed(c.nonce, c.leaf, c.to, c.value, fee, success, ret);
}
// ------------------------------------------------------------------ exits (always fee-free)
/// @notice Start the 7 day escape hatch. Owner factors only; no fee.
function requestEscape(uint256 n, uint32 leaf, bytes calldata ownerSig, HashSig calldata h) external nonReentrant {
require(n == nonce, "wallet: nonce");
require(escapeAt == 0, "wallet: escape pending");
_ownerAuth(escapeDigest(n, leaf), leaf, ownerSig, h, false, EMERGENCY_LEAVES, false);
nonce = n + 1;
escapeAt = uint64(block.timestamp + ESCAPE_DELAY);
emit EscapeRequested(escapeAt);
}
/// @notice Cancel a pending recovery (M2). Owner factors only; no fee. NO COMMIT NEEDED (rc6, council a-wg-rc6-g2-v2
/// G-1): the owner's veto must not depend on a write-once commit that someone who forges the owner's ECDSA pledges
/// can poison first (the recovery key that started the recovery is spent, so the recovery-key escape cannot help
/// then). It still needs the owner factors (Mode A: the pledge and the one-time hash key). The digest names the
/// recovery (`rn` = recoveryNonce) and the leaf; the app signs it only with a leaf that has no commit and that this
/// device never signed. Any leaf up to 1022 (council v4 G-6: the veto must work when the exit leaves are gone; 1023
/// stays for rotation). A cancel also ARMS THE 7-DAY ESCAPE (council v3): the recovery key was in someone else's hands
/// and is cleared, and junk commits must never freeze the vault afterwards. The owner can cancel the escape later,
/// once a fresh recovery key is set.
function cancelRecoveryByOwner(uint256 rn, uint32 leaf, bytes calldata ownerSig, HashSig calldata h) external nonReentrant {
require(rn == recoveryNonce, "wallet: nonce");
require(pendingRecovery.readyAt != 0, "wallet: no recovery");
_ownerAuth(cancelRecoveryDigest(rn, leaf), leaf, ownerSig, h, false, uint32(WOTS.LEAVES) - 1, true);
// the owner nonce does not move (council a-wg-rc6-g2-v8 G-10): the digest does not use it and the burned leaf
// stops any replay, so moves the owner already signed (a reserve rotation above all) stay valid after the veto
_rejectRecovery();
}
/// @notice Move the whole balance of each listed asset (address(0) = ETH) to the pre-set exit address. Owner
/// factors only; no fee; best effort per asset (one asset that cannot move never blocks the rest).
function evacuate(uint256 n, uint32 leaf, address[] calldata tokens, bytes calldata ownerSig, HashSig calldata h)
external
nonReentrant
{
require(n == nonce, "wallet: nonce");
address exit = exitAddress;
require(exit != address(0), "wallet: no exit address");
_ownerAuth(evacuateDigest(n, leaf, tokens), leaf, ownerSig, h, false, EMERGENCY_LEAVES, false);
nonce = n + 1;
// the last exit leaf is gone: the vault arms its own escape, so a rotation from the reserve never needs a
// commit that may be stale or junk (council a-wg-rc6-g2-v3 G-2)
if (nextLeaf >= EMERGENCY_LEAVES) _armEscape();
for (uint256 i; i < tokens.length; ++i) {
address t = tokens[i];
if (t == address(0)) {
uint256 bal = address(this).balance;
if (bal == 0) continue;
(bool sent,,) = _assetCall(exit, bal, "", false);
emit Evacuated(n, t, exit, bal, sent);
continue;
}
(bool read, uint256 len, uint256 word) = _assetCall(t, 0, abi.encodeCall(IERC20.balanceOf, (address(this))), true);
if (!read || len < 32) {
emit Evacuated(n, t, exit, 0, false);
continue;
}
if (word == 0) continue;
(bool called, uint256 rlen, uint256 rword) = _assetCall(t, 0, abi.encodeCall(IERC20.transfer, (exit, word)), false);
// never decode as bool: a token returning a short or non-boolean word must not revert the rest (Opus P1 L-2)
emit Evacuated(n, t, exit, word, called && (rlen == 0 || (rlen >= 32 && rword == 1)));
}
}
/// @dev One asset call of evacuate: exactly ASSET_CALL_GAS (the check covers the EIP-150 1/64, the cold access,
/// the value transfer and a new account), and at most one word of return data is copied, so a huge answer costs
/// nothing here (AI audit G-4, G-5).
function _assetCall(address to, uint256 value, bytes memory data, bool readOnly)
internal
returns (bool ok, uint256 len, uint256 word)
{
require(gasleft() >= (ASSET_CALL_GAS * 64) / 63 + 50_000, "wallet: gas");
uint256 g = value > 0 ? ASSET_CALL_GAS - 2_300 : ASSET_CALL_GAS; // the EVM adds the stipend (AI audit G-7)
assembly ("memory-safe") {
switch readOnly
case 1 { ok := staticcall(g, to, add(data, 32), mload(data), 0, 0) }
default { ok := call(g, to, value, add(data, 32), mload(data), 0, 0) }
len := returndatasize()
if gt(len, 31) {
returndatacopy(0, 0, 32)
word := mload(0)
}
}
}
/// @dev The owner rejected a recovery that the recovery key started, so that key may be held by someone else (and
/// it is spent anyway): clear the commitment (Fable FR1-I3, FR2-I4). The owner sets a fresh one with
/// setRecoveryCommit (hash key).
function _rejectRecovery() internal {
delete pendingRecovery;
recoveryCommit = bytes32(0);
emit RecoveryCancelled();
emit RecoveryCommitSet(bytes32(0));
_armEscape(); // rc6: every cancel (owner factors or execute) leaves a commit-free way out (council v3 G-3)
}
/// @dev Start the 7-day escape unless one is pending or active already.
function _armEscape() internal {
if (escapeAt != 0) return;
escapeAt = uint64(block.timestamp + ESCAPE_DELAY);
emit EscapeRequested(escapeAt);
}
/// @dev Accept the recovery key's one-time signature on `d` and spend the key: a valid WOTS signature under the
/// current, unspent recovery commitment. After this the key never signs for this vault again (G-2, crosscheck G-3).
function _spendRecoveryKey(bytes32 d, bytes32 recoverySeed, bytes32[67] calldata recoverySig) internal {
bytes32 rc = recoveryCommit;
require(rc != bytes32(0) && !spentRecoveryCommit[rc], "wallet: recovery key");
require(
recoveryCommitOf(recoverySeed, WOTS.leafFromSig(recoverySeed, RECOVERY_LEAF, d, recoverySig)) == rc,
"wallet: recovery sig"
);
spentRecoveryCommit[rc] = true;
emit RecoveryKeySpent(rc);
}
/// @notice Solo recovery with the recovery key: RECOVERY_DELAY, then anyone may finalize. No fee. The signature
/// is one-time and hash-based, so seeing it lets nobody start a different recovery (AI audit G-2). The new
/// recovery commitment must be a fresh key (never spent here; not the key signing now).
function initiateRecovery(
address newOwner,
bytes32 newRoot,
bytes32 newSeed,
bytes32 newRecoveryCommit,
uint256 deadline,
bytes32 recoverySeed,
bytes32[67] calldata recoverySig
) external nonReentrant {
require(pendingRecovery.readyAt == 0, "wallet: recovery pending");
bytes32 d = recoveryDigest(newOwner, newRoot, newSeed, newRecoveryCommit, recoveryNonce, deadline);
// A signed recovery that can never execute (expired, a used or empty root, no owner, a new key that is spent or
// is the key signing now) still spent its one-time key by signing: it can never sign a replacement. So it
// retires the key and arms the escape; no recovery starts, nothing else moves (council a-wg-rc6-g2-v5 G-5,
// -v6 G-8). A recovery that can still execute always starts exactly as signed.
bool executable = block.timestamp <= deadline && newOwner != address(0) && newRoot != bytes32(0)
&& !usedRoot[newRoot] && newRecoveryCommit != recoveryCommit && !spentRecoveryCommit[newRecoveryCommit];
_spendRecoveryKey(d, recoverySeed, recoverySig);
recoveryNonce += 1;
if (!executable) {
recoveryCommit = bytes32(0);
emit RecoveryCommitSet(bytes32(0));
_armEscape();
return;
}
uint64 readyAt = uint64(block.timestamp + RECOVERY_DELAY);
pendingRecovery = PendingRecovery(newOwner, newRoot, newSeed, newRecoveryCommit, readyAt);
emit RecoveryStarted(newOwner, newRoot, readyAt);
}
function finalizeRecovery() external nonReentrant {
PendingRecovery memory p = pendingRecovery;
require(p.readyAt != 0 && block.timestamp >= p.readyAt, "wallet: recovery not ready");
require(!usedRoot[p.newRoot], "wallet: root used");
delete pendingRecovery;
owner = p.newOwner;
hashRoot = p.newRoot;
pubSeed = p.newSeed;
// fresh when the recovery started; if it was installed and spent meanwhile, install none instead
bytes32 rc = spentRecoveryCommit[p.newRecoveryCommit] ? bytes32(0) : p.newRecoveryCommit;
recoveryCommit = rc;
usedRoot[p.newRoot] = true;
nextLeaf = 0;
escapeAt = 0;
emit RecoveryFinalized(p.newOwner, p.newRoot);
if (rc == bytes32(0)) _armEscape(); // no usable recovery key: keep a commit-free way out (council v4 G-5)
}
/// @notice Start the 7-day escape hatch with the recovery key instead of the owner factors (rc6). No commit, so
/// junk commits cannot block it (crosscheck G-2: an attacker who forges the owner's ECDSA pledges can poison
/// every commit, including the owner's own escape). Spends the recovery key; once the escape is active the owner
/// installs a fresh one with an escaped setRecoveryCommit. It only lifts the commit rule and the fee: every move
/// still needs the owner factors (Mode A: ECDSA and the hash key), and the owner can cancel the escape. No fee.
function escapeWithRecoveryKey(bytes32 recoverySeed, bytes32[67] calldata recoverySig) external nonReentrant {
require(escapeAt == 0, "wallet: escape pending");
// a pending recovery keeps its recoveryNonce (the cancel names it) and has the commit-free owner cancel
// (council a-wg-rc6-g2-v5 G-7)
require(pendingRecovery.readyAt == 0, "wallet: recovery pending");
_spendRecoveryKey(recoveryEscapeDigest(recoveryNonce), recoverySeed, recoverySig);
recoveryNonce += 1;
recoveryCommit = bytes32(0);
escapeAt = uint64(block.timestamp + ESCAPE_DELAY);
emit RecoveryCommitSet(bytes32(0));
emit EscapeRequested(escapeAt);
}
// ------------------------------------------------------------------ self-calls (via execute)
modifier onlySelf() {
require(msg.sender == address(this), "wallet: only self");
_;
}
function rotateHashKey(bytes32 newRoot, bytes32 newSeed) external onlySelf {
require(newRoot != bytes32(0) && !usedRoot[newRoot], "wallet: root");
// a pending recovery's target root is reserved: a rotation landing first would make the recovery unfinishable
// (council a-wg-rc6-g2-v7 G-9); cancel the recovery first to rotate to that root
require(pendingRecovery.readyAt == 0 || newRoot != pendingRecovery.newRoot, "wallet: root");
usedRoot[newRoot] = true;
hashRoot = newRoot;
pubSeed = newSeed;
nextLeaf = 0;
emit HashKeyRotated(newRoot, newSeed);
}
function rotateOwner(address newOwner) external onlySelf {
require(newOwner != address(0), "wallet: owner");
owner = newOwner;
emit OwnerRotated(newOwner);
}
function setRecoveryCommit(bytes32 c) external onlySelf {
// a recovery key can be replaced, never removed (council v4 G-5)
require(c != bytes32(0) && !spentRecoveryCommit[c], "wallet: recovery key spent");
recoveryCommit = c;
emit RecoveryCommitSet(c);
}
function setExitAddress(address exit) external onlySelf {
exitAddress = exit;
emit ExitAddressSet(exit);
}
function cancelRecovery() external onlySelf {
require(pendingRecovery.readyAt != 0, "wallet: no recovery");
_rejectRecovery();
}
function cancelEscape() external onlySelf {
// the escape may only stop when a usable recovery key is back (council v4 G-5)
require(recoveryCommit != bytes32(0) && !spentRecoveryCommit[recoveryCommit], "wallet: set a recovery key first");
escapeAt = 0;
emit EscapeCancelled();
}
}
src/QuantumCanary.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
interface IFeeTokenSource {
function feeToken() external view returns (IERC20);
}
/// @notice Quantum canary. The puzzle key Q is derived in the constructor by hash-to-curve from a public
/// seed (try-and-increment, even y), so nobody knows its private key. Producing an ECDSA signature under Q
/// means secp256k1 has been broken. The first valid claim takes the whole WGATE bounty and sets `fired`
/// forever. The signed message binds msg.sender, so a watcher cannot front-run the claim.
/// No admin, no withdraw: the only way tokens leave is a valid claim.
/// Personal build: the bounty token is the fee token the fee policy names (it arrives after deploy, so the canary
/// reads it from the policy instead of holding its own copy); the puzzle and the claim are unchanged from rc3.
contract QuantumCanary is ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 internal constant P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 internal constant SQRT_EXP = (P + 1) / 4;
IFeeTokenSource public immutable FEES;
bytes32 public immutable seed;
uint256 public immutable qx;
uint256 public immutable qy;
uint32 public immutable counter;
address public immutable canaryAddress;
bool public fired;
uint64 public firedAt;
address public claimer;
event Funded(address indexed from, uint256 amount);
event CanaryFired(address indexed claimer, uint256 bounty);
constructor(IFeeTokenSource fees_, bytes32 seed_) {
FEES = fees_;
seed = seed_;
(uint256 x, uint256 y, uint32 i) = deriveQ(seed_);
qx = x;
qy = y;
counter = i;
canaryAddress = address(uint160(uint256(keccak256(abi.encodePacked(x, y)))));
}
function deriveQ(bytes32 s) public view returns (uint256 x, uint256 y, uint32 i) {
for (i = 0; ; ++i) {
x = uint256(keccak256(abi.encodePacked("wintergate.canary", s, i))) % P;
uint256 rhs = addmod(mulmod(mulmod(x, x, P), x, P), 7, P);
y = _modexp(rhs, SQRT_EXP);
if (mulmod(y, y, P) == rhs) {
if (y & 1 == 1) y = P - y;
return (x, y, i);
}
}
}
function _modexp(uint256 b, uint256 e) internal view returns (uint256 r) {
(bool ok, bytes memory out) = address(0x05).staticcall(abi.encode(uint256(32), uint256(32), uint256(32), b, e, P));
require(ok, "canary: modexp");
r = abi.decode(out, (uint256));
}
/// @notice The bounty token: the fee token (zero until the policy's one-time switch).
function token() public view returns (IERC20) {
return FEES.feeToken();
}
function bounty() external view returns (uint256) {
IERC20 t = token();
return address(t) == address(0) ? 0 : t.balanceOf(address(this));
}
function claimDigest(address who) public view returns (bytes32) {
bytes32 inner = keccak256(abi.encode("wintergate.canary.claim", address(this), block.chainid, who));
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", inner));
}
function fund(uint256 amount) external nonReentrant {
require(!fired, "canary: fired"); // a fired canary never pays again: refuse instead of stranding (AI audit G-6)
IERC20 t = token();
require(address(t) != address(0), "canary: no fee token yet");
t.safeTransferFrom(msg.sender, address(this), amount);
emit Funded(msg.sender, amount);
}
function claim(uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(!fired, "canary: fired");
address signer = ecrecover(claimDigest(msg.sender), v, r, s);
require(signer != address(0) && signer == canaryAddress, "canary: bad proof");
fired = true;
firedAt = uint64(block.timestamp);
claimer = msg.sender;
// the alarm never depends on the fee token: a token that cannot pay now leaves the bounty for collect()
// (AI audit G-3)
// The payout gets a bounded budget that always leaves enough to finish recording the alarm, even if the token
// burns all the gas it is given (AI audit G-9). Too little gas: no payout now, collect() later.
uint256 b;
uint256 g = gasleft();
if (g > 100_000) {
try this.payClaimer{gas: g - 60_000}() returns (uint256 paid) {
b = paid;
} catch {}
}
emit CanaryFired(msg.sender, b);
}
/// @notice After the canary fired: the claimer (or anyone, for the claimer) moves whatever bounty is still here to
/// the claimer. Used when the payout failed at claim time.
function collect() external nonReentrant returns (uint256) {
require(fired, "canary: not fired");
return this.payClaimer();
}
/// @dev Self-call only, so claim() can catch its failure without rolling back `fired`.
function payClaimer() external returns (uint256 b) {
require(msg.sender == address(this), "canary: self");
IERC20 t = token();
if (address(t) == address(0)) return 0;
b = t.balanceOf(address(this));
if (b > 0) t.safeTransfer(claimer, b);
}
}
src/WOTS.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @notice WOTS (n = 32, w = 16, l = 67) with a tweakable keccak256 hash, under a height-10 Merkle tree.
/// chain step: F = keccak256(seed || uint32 leaf || uint16 chain || uint16 step || x)
/// leaf key: keccak256(seed || uint32 leaf || pk_0 .. pk_66)
/// tree node: keccak256(seed || uint8 level || uint32 index || left || right), level 1..10
library WOTS {
uint256 internal constant L = 67;
uint256 internal constant H = 10;
uint256 internal constant LEAVES = 1 << H;
/// @dev Base-16 digits of the digest (64, big-endian nibbles) followed by the 3-digit checksum.
function digits(bytes32 d) internal pure returns (uint8[67] memory out) {
uint256 csum;
for (uint256 i; i < 32; ++i) {
uint8 b = uint8(d[i]);
out[2 * i] = b >> 4;
out[2 * i + 1] = b & 15;
csum += (15 - (b >> 4)) + (15 - (b & 15));
}
out[64] = uint8((csum >> 8) & 15);
out[65] = uint8((csum >> 4) & 15);
out[66] = uint8(csum & 15);
}
/// @dev Runs chain `chain` of leaf `leaf` from step `start` up to step 15.
function chainUp(bytes32 seed, uint32 leaf, uint256 chain, uint256 start, bytes32 x) internal pure returns (bytes32 r) {
assembly {
let p := mload(0x40)
mstore(p, seed)
for { let j := start } lt(j, 15) { j := add(j, 1) } {
mstore(add(p, 32), or(or(shl(224, leaf), shl(208, chain)), shl(192, j)))
mstore(add(p, 40), x)
x := keccak256(p, 72)
}
r := x
}
}
/// @notice Recomputes the leaf public key from a signature on `d`.
function leafFromSig(bytes32 seed, uint32 leaf, bytes32 d, bytes32[67] calldata sig) internal pure returns (bytes32) {
uint8[67] memory m = digits(d);
bytes memory buf = new bytes(36 + 32 * L);
assembly {
mstore(add(buf, 32), seed)
mstore(add(buf, 64), shl(224, leaf))
}
for (uint256 i; i < L; ++i) {
bytes32 pk = chainUp(seed, leaf, i, m[i], sig[i]);
assembly {
mstore(add(add(buf, 68), mul(i, 32)), pk)
}
}
return keccak256(buf);
}
function node(bytes32 seed, uint256 level, uint256 index, bytes32 left, bytes32 right) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(seed, uint8(level), uint32(index), left, right));
}
function rootFromLeaf(bytes32 seed, uint32 leaf, bytes32 leafPk, bytes32[10] calldata auth) internal pure returns (bytes32 n) {
n = leafPk;
uint256 idx = leaf;
for (uint256 lvl; lvl < H; ++lvl) {
n = (idx & 1) == 0 ? node(seed, lvl + 1, idx >> 1, n, auth[lvl]) : node(seed, lvl + 1, idx >> 1, auth[lvl], n);
idx >>= 1;
}
}
/// @notice True iff `sig`/`auth` is a valid one-time signature on `d` by leaf `leaf` under `root`.
function verify(bytes32 root, bytes32 seed, uint32 leaf, bytes32 d, bytes32[67] calldata sig, bytes32[10] calldata auth)
internal
pure
returns (bool)
{
if (leaf >= LEAVES) return false;
return rootFromLeaf(seed, leaf, leafFromSig(seed, leaf, d, sig), auth) == root;
}
}
src/WintergateFactory.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {HybridWallet, ICanaryFlag, IActionFee} from "./HybridWallet.sol";
import {CommitRegistry} from "./CommitRegistry.sol";
interface ICreateFee is IActionFee {
function createFee() external view returns (uint256);
}
/// @notice The ONLY way to create a Wintergate wallet. Personal build: no co-signature, no integrator, no credits.
/// Anyone may submit a creation for a given set of keys by paying the fixed creation fee in the fee token the policy
/// names (zero and free until the token is set after launch); a copied creation still pays the fee and deploys the
/// user's own keys at the address the user predicted, so it is harmless. The CREATE2 salt binds every key parameter
/// and the exit address (H1). The implementation refuses initialisation from anyone else. No admin: nothing here can
/// be paused or changed.
contract WintergateFactory {
using SafeERC20 for IERC20;
struct CreateParams {
address owner;
bytes32 hashRoot;
bytes32 pubSeed;
bytes32 recoveryCommit;
uint8 mode;
address exitAddress;
bytes32 salt;
}
ICreateFee public immutable FEES;
CommitRegistry public immutable commits;
address public immutable implementation;
mapping(address => bool) public isWallet;
uint256 public walletCount;
event WalletCreated(address indexed wallet, address indexed owner, uint8 mode, bytes32 hashRoot, uint256 fee);
constructor(ICanaryFlag canary_, ICreateFee fees_, uint256 recoveryDelay) {
FEES = fees_;
commits = new CommitRegistry(address(this));
implementation = address(new HybridWallet(address(this), canary_, fees_, recoveryDelay));
}
/// @dev The CREATE2 salt binds EVERY key parameter, so nobody can deploy different keys at the address a
/// user computed and funded in advance (H1).
function _salt(CreateParams calldata p) internal pure returns (bytes32) {
return keccak256(abi.encode(p.owner, p.hashRoot, p.pubSeed, p.recoveryCommit, p.mode, p.exitAddress, p.salt));
}
function predict(CreateParams calldata p) external view returns (address) {
return Clones.predictDeterministicAddress(implementation, _salt(p));
}
/// @notice Create a vault. The caller pays the creation fee (allowance to this factory), at most `maxFee`.
function createWallet(CreateParams calldata p, uint256 maxFee) public returns (address wallet) {
uint256 fee = FEES.createFee();
require(fee <= maxFee, "factory: fee above max");
if (fee > 0) {
FEES.feeToken().safeTransferFrom(msg.sender, address(FEES), fee);
FEES.settle(); // half burned, half to the canary bounty, in this transaction
}
wallet = Clones.cloneDeterministic(implementation, _salt(p));
HybridWallet(payable(wallet)).initialize(p.owner, p.hashRoot, p.pubSeed, p.recoveryCommit, p.mode, p.exitAddress);
isWallet[wallet] = true;
walletCount += 1;
commits.recordFor(wallet, keccak256(abi.encode(p.hashRoot, p.pubSeed)));
emit WalletCreated(wallet, p.owner, p.mode, p.hashRoot, fee);
}
/// @notice Same, with an EIP-2612 permit for the fee (no separate approval). A permit that was already used by a
/// front-runner is ignored when the allowance already suffices (audit r1 L2).
function createWalletWithPermit(
CreateParams calldata p,
uint256 maxFee,
uint256 permitDeadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (address wallet) {
IERC20 token = FEES.feeToken();
if (address(token) != address(0)) {
try IERC20Permit(address(token)).permit(msg.sender, address(this), maxFee, permitDeadline, v, r, s) {} catch {}
}
return createWallet(p, maxFee);
}
}
src/interfaces/IStockereum.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @dev Stockereum (stockereum.com) launch contracts on Ethereum mainnet, read from the verified sources
/// (LaunchHook 0x322dcEc4958C14e021A9F1cD49DF11b9457968cC, LaunchFactory 0xc6B080DEd03C3382476A76345e79f82BD480977B,
/// LaunchRouter 0xcdf832D2C11DA16055bb6C6145cF38EDD7233767; Verifier Alliance / Blockscout, 2026-10-08). Every launch
/// is one Uniswap v4 pool (fee 0, tick spacing 200, hooks = LaunchHook) holding the whole 1,000,000,000 supply in one
/// position owned by the hook; the hook charges the 1 to 3% trade fee on the quote side and a 99% anti-snipe fee
/// decaying over the first 20 seconds; exact-output swaps are refused; swaps are NOT limited to their router.
interface IStockereumHook {
struct Launch {
address token;
address feeRecipient;
address quote;
uint40 openedAt;
uint24 feePpm;
bool quoteIsCurrency0;
bool pendingDevBuy;
bool feesToHolders;
address devBuyer;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
}
function getLaunch(bytes32 poolId) external view returns (Launch memory);
function currentFee(bytes32 poolId) external view returns (uint256);
function ANTI_SNIPE_DURATION() external view returns (uint256);
function TICK_SPACING() external view returns (int24);
function factory() external view returns (address);
function poolManager() external view returns (address);
}
interface IStockereumFactory {
function quotes(address quote) external view returns (bool enabled, uint8 decimals, string memory symbol);
function hook() external view returns (address);
function weth() external view returns (address);
function launchCount() external view returns (uint256);
function allLaunches(uint256 i) external view returns (address);
}
src/interfaces/IUniswapV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @dev The subset of Uniswap v4 (core 1.0, Ethereum mainnet PoolManager 0x000000000004444c5dc75cB358380D2e3dE08A90,
/// StateView 0x7ffe42c4a5deea5b0fec41c94c136cf115597227) the fee policy and the zap use. Currency is an address
/// (address(0) = native ETH); BalanceDelta packs amount0 (high 128 bits) and amount1 (low 128 bits) into an int256.
struct PoolKey {
address currency0;
address currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
struct SwapParams {
bool zeroForOne;
int256 amountSpecified; // negative = exact input
uint160 sqrtPriceLimitX96;
}
interface IPoolManager {
function unlock(bytes calldata data) external returns (bytes memory);
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (int256 delta);
function sync(address currency) external;
function settle() external payable returns (uint256);
function take(address currency, address to, uint256 amount) external;
}
interface IUnlockCallback {
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
/// @dev Uniswap's StateView lens (reads PoolManager storage through extsload).
interface IStateView {
function poolManager() external view returns (address);
function getSlot0(bytes32 poolId) external view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);
function getLiquidity(bytes32 poolId) external view returns (uint128 liquidity);
}
library V4 {
function poolId(PoolKey memory k) internal pure returns (bytes32) {
return keccak256(abi.encode(k));
}
function amount0(int256 delta) internal pure returns (int128) {
return int128(delta >> 128);
}
function amount1(int256 delta) internal pure returns (int128) {
return int128(delta);
}
}
src/vendor/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
src/vendor/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
src/vendor/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.