Проверенный контрактЧастичноеUNLICENSED
CoinDeployerV4
Адрес0x8303775d8c59dc79cb2fc51dca98f6dfbe42a56f
- Баланс
0 ETH
- Транзакций
0
- Компилятор
solc 0.8.30
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.30+commit.73712a01
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- UNLICENSED
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 399 326
- Транзакция создания
- 0x090ff7a86a…1d25582ff3
39 файлов
- src/v4/bridge/CoinDeployerV4.solглавный5,48 КБ
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3,1 КБ
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2,48 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol636 Б
- lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol739 Б
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol881 Б
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6,54 КБ
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6,24 КБ
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 Б
- lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol6,33 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10,9 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Permit.sol2,77 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3,81 КБ
- lib/openzeppelin-contracts/contracts/utils/Address.sol6,03 КБ
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 Б
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 Б
- lib/openzeppelin-contracts/contracts/utils/Nonces.sol1,49 КБ
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1,97 КБ
- lib/openzeppelin-contracts/contracts/utils/ShortStrings.sol4,28 КБ
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4,18 КБ
- lib/openzeppelin-contracts/contracts/utils/Strings.sol3,93 КБ
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7,82 КБ
- lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol6,61 КБ
- lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol3,7 КБ
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol28,31 КБ
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34,94 КБ
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2,61 КБ
- src/v3/gap/GapPriceLib.sol4,26 КБ
- src/v4/bridge/CoinCodeRegistryV4.sol7,5 КБ
- src/v4/bridge/PangeaCoinV4.sol13,15 КБ
- src/v4/bridge/PangeaDeployerV4.sol2,04 КБ
- src/v4/factory/CodeStoreV4.sol1,43 КБ
- src/v4/gap/GapBlockV4.sol2,16 КБ
- src/v4/gap/GapMathV4.sol35,73 КБ
- src/v4/gap/GapRecorderV4.sol11,51 КБ
- src/v4/gap/IGapRegistryV4.sol20,77 КБ
- src/v4/gap/PangeaOFTV4Storage.sol3,31 КБ
src/v4/bridge/CoinDeployerV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {ITokenOpenV4} from "./PangeaCoinV4.sol";
import {IPendingConfigV4} from "./PangeaDeployerV4.sol";
import {CoinCodeRegistryV4} from "./CoinCodeRegistryV4.sol";
interface IOwnedV4 {
function owner() external view returns (address);
}
/// @title CoinDeployerV4 -- CREATE2s every PangeaCoinV4 of one chain (salt = coinId), for LaunchCoreV4 only
/// @notice UPGRADEABLE (owner 2026-11-12): this is the IMPLEMENTATION behind a UUPS ERC1967Proxy; the proxy is the coins'
/// CREATE2 deployer. The proxy and this implementation each have one address on every EVM chain (PangeaDeployerV4,
/// fixed salts; the implementation's chain values -- bridge, core PROXY, PoolManager, supply reporter, code
/// registry -- read from its deployer in the constructor, so they are immutables of THIS code and no proxy
/// storage is written at construction). Upgrades: `upgradeToAndCall`, by the bridge's owner (the v4 admin) only,
/// no delay (owner rule). The coin's code is NOT in this contract: it is the CoinCodeRegistryV4 version of the
/// coin's createdAt (immutable registry, append-only), so a coin has one address everywhere:
/// CREATE2(proxy, coinId, registry.creationCodeAt(createdAt) ++ abi.encode(name, symbol, coinId, creatorAtLaunch)),
/// and an open-later of an old coin deploys its original code there whatever this implementation becomes.
/// Storage: only the namespaced (ERC-7201) metadataURI scratch, empty between transactions.
contract CoinDeployerV4 is ITokenOpenV4, UUPSUpgradeable {
address public immutable bridge;
address public immutable core;
address public immutable poolManager;
/// @notice SUPPLY MIRROR: what every coin deployed here names as its `supplyReporter` (one address everywhere).
address public immutable supplyReporter;
CoinCodeRegistryV4 public immutable codeRegistry;
address internal transient _pendingMintTo;
/// @custom:storage-location erc7201:pangea.v4.coinDeployer
struct Layout {
/// @dev META-EVM: the coin's first metadataURI during deploy only (a string cannot be transient; deleted after).
string pendingMetadataURI;
}
// keccak256(abi.encode(uint256(keccak256("pangea.v4.coinDeployer")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant LAYOUT = 0x12a16d1785a5a386ab3e4673439cf147b752fc8ab9acc54207026b446e09ef00;
error NotCore();
error NotAdmin();
constructor() {
address reg;
(bridge, core, poolManager, supplyReporter, reg) =
abi.decode(IPendingConfigV4(msg.sender).pending(), (address, address, address, address, address));
codeRegistry = CoinCodeRegistryV4(reg);
}
function _l() private pure returns (Layout storage l) {
bytes32 s = LAYOUT;
assembly ("memory-safe") {
l.slot := s
}
}
function _authorizeUpgrade(address) internal view override {
if (msg.sender != IOwnedV4(bridge).owner()) revert NotAdmin();
}
function pendingMintTo() external view returns (address) {
return _pendingMintTo;
}
function pendingMetadataURI() external view returns (string memory) {
return _l().pendingMetadataURI;
}
/// @param metadataURI META-EVM (owner Q1 1150): the coin's first metadataURI (<= 128 bytes, the coin checks; may be
/// empty). Not in the init code: the token address does not depend on it.
/// @param createdAt the coin's preimage createdAt: picks its code version (CoinCodeRegistryV4.versionAt).
function deploy(
bytes32 coinId,
string calldata name,
string calldata symbol,
address creatorAtLaunch,
string calldata metadataURI,
uint64 createdAt
) external returns (address t) {
if (msg.sender != core) revert NotCore();
_pendingMintTo = msg.sender;
bool uri = bytes(metadataURI).length != 0;
if (uri) _l().pendingMetadataURI = metadataURI;
bytes memory init = abi.encodePacked(codeRegistry.creationCodeAt(createdAt), abi.encode(name, symbol, coinId, creatorAtLaunch));
assembly ("memory-safe") {
t := create2(0, add(init, 0x20), mload(init), coinId)
// the coin constructor's own error (e.g. MetadataURITooLong) bubbles up, as `new` did
if iszero(t) {
let p := mload(0x40)
returndatacopy(p, 0, returndatasize())
revert(p, returndatasize())
}
}
if (uri) delete _l().pendingMetadataURI;
_pendingMintTo = address(0);
}
/// @notice The coin's one address for a coin created NOW (the current code version); tokenAddressAt for any createdAt.
function tokenAddress(bytes32 coinId, string calldata name, string calldata symbol, address creatorAtLaunch)
external
view
returns (address)
{
return codeRegistry.tokenAddress(coinId, name, symbol, creatorAtLaunch, uint64(block.timestamp));
}
function tokenAddressAt(bytes32 coinId, string calldata name, string calldata symbol, address creatorAtLaunch, uint64 createdAt)
external
view
returns (address)
{
return codeRegistry.tokenAddress(coinId, name, symbol, creatorAtLaunch, createdAt);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
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/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.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/ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";
/**
* @dev Implementation 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.
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC-20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/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/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/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/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/Nonces.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract Nonces {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
mapping(address account => uint256) private _nonces;
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
return _nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return _nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}
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/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/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/v3/gap/GapPriceLib.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @title GapPriceLib -- pool prices as "whole quote per whole base, 1e18" (docs/v3-gap-fee-spec.md §2)
/// @notice Shared by PangeaOFTV3 (its official pool, rounded up at the source and down at the
/// destination) and the gap readers (always down). Never reverts for the inputs it accepts;
/// anything outside them returns 0, which every caller treats as "unknown".
library GapPriceLib {
uint256 internal constant Q64 = 1 << 64;
uint256 internal constant Q128 = 1 << 128;
uint256 internal constant Q192 = 1 << 192;
/// @dev Uniswap's TickMath bounds (v3 and v4 share them). Outside them the price is not one a
/// Uniswap pool can hold, and the arithmetic below is only overflow-free inside them.
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev |18 + baseDecimals - quoteDecimals| at most this; beyond it the price is 0 (unknown).
int256 internal constant MAX_EXP = 36;
/// @notice The decimal scaling of a raw (base-unit) price into "whole quote per whole base, 1e18":
/// multiply by `num`, divide by `den`. (0, 0) when the decimals are out of range.
function scale(uint8 baseDecimals, uint8 quoteDecimals) internal pure returns (uint256 num, uint256 den) {
int256 e = 18 + int256(uint256(baseDecimals)) - int256(uint256(quoteDecimals));
if (e > MAX_EXP || e < -MAX_EXP) return (0, 0);
if (e >= 0) return (10 ** uint256(e), 1);
return (1, 10 ** uint256(-e));
}
/// @notice The price of one whole `base` in whole `quote`, 1e18, from a Uniswap v3/v4
/// sqrtPriceX96 (sqrt of currency1 per currency0, raw units, Q96).
/// @param baseIs0 whether `base` is the pool's currency0
/// @param up round up (the source) or down (the destination, and every reader)
/// @return p the price, possibly above type(uint128).max (callers bound it); 0 when unknown
function fromSqrtX96(uint160 sqrtP, bool baseIs0, uint8 baseDecimals, uint8 quoteDecimals, bool up)
internal
pure
returns (uint256 p)
{
if (sqrtP < MIN_SQRT_PRICE || sqrtP > MAX_SQRT_PRICE) return 0;
(uint256 num, uint256 den) = scale(baseDecimals, quoteDecimals);
if (num == 0) return 0;
Math.Rounding r = up ? Math.Rounding.Ceil : Math.Rounding.Floor;
uint256 s = sqrtP;
// num <= 1e36 < 2^120, and sqrtP is inside TickMath's bounds, so no step below overflows:
// currency0 side s^2 < 2^256 (or s^2/2^64 < 2^256), times < 2^120, over >= 2^128;
// currency1 side 2^192 (or 2^128) times < 2^120, over s^2 >= 2^64 (or s^2/2^64 >= 2^192).
if (baseIs0) {
// raw price of base (currency0) in quote = s^2 / 2^192
if (s <= type(uint128).max) p = Math.mulDiv(s * s, num, Q192, r);
else p = Math.mulDiv(Math.mulDiv(s, s, Q64, r), num, Q128, r);
} else {
// raw price of base (currency1) in quote = 2^192 / s^2: round the divisor the other way
if (s <= type(uint128).max) p = Math.mulDiv(Q192, num, s * s, r);
else p = Math.mulDiv(Q128, num, Math.mulDiv(s, s, Q64, up ? Math.Rounding.Floor : Math.Rounding.Ceil), r);
}
if (den > 1) p = up ? Math.ceilDiv(p, den) : p / den;
}
/// @notice The price of one whole `base` in whole `quote`, 1e18, from constant-product reserves,
/// rounded down. 0 when either reserve is 0 or the decimals are out of range.
function fromReserves(uint256 reserveBase, uint256 reserveQuote, uint8 baseDecimals, uint8 quoteDecimals)
internal
pure
returns (uint256 p)
{
if (reserveBase == 0 || reserveQuote == 0) return 0;
if (reserveBase > type(uint128).max || reserveQuote > type(uint128).max) return 0;
(uint256 num, uint256 den) = scale(baseDecimals, quoteDecimals);
if (num == 0) return 0;
// reserveQuote * num < 2^248: no overflow.
p = Math.mulDiv(reserveQuote, num, reserveBase) / den;
}
}
src/v4/bridge/CoinCodeRegistryV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {CodeStoreV4} from "../factory/CodeStoreV4.sol";
import {IPendingConfigV4} from "./PangeaDeployerV4.sol";
interface ICoinFactsV4 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function coinId() external view returns (bytes32);
function creatorAtLaunch() external view returns (address);
function bridge() external view returns (address);
function poolManager() external view returns (address);
}
/// @title CoinCodeRegistryV4 -- the append-only list of PangeaCoinV4 creation codes, IMMUTABLE (no proxy, no upgrade)
/// @notice UPGRADEABLE COIN CREATION (owner 2026-11-12): LaunchCoreV4 and CoinDeployerV4 sit behind UUPS proxies, so NEW
/// coins get new coin code by a new version here (and new open logic by a core upgrade); an EXISTING coin never
/// changes:
/// - a coin's code version is a pure function of its preimage `createdAt` (the same on every chain, Solana-home
/// coins included): the newest version whose `activeFrom` <= createdAt (`versionAt`). Version 0: activeFrom 0.
/// - versions are only APPENDED, each with activeFrom STRICTLY after the block it is added in (and after the
/// previous one). The bridge refuses createdAt > block.timestamp, so the version of every coin that is or can
/// be open anywhere can never change. No function changes or removes a recorded code.
/// - a coin's address on every chain is CREATE2(the coin-deployer PROXY, coinId, code[versionAt(createdAt)] ++
/// abi.encode(name, symbol, coinId, creatorAtLaunch)): an open-later of an old coin deploys its ORIGINAL code
/// at its one address, whatever the deployer / core have been upgraded to since.
/// - `genuine` is what the IMMUTABLE bridge asks before registering any token (BridgeRoleV4.registerCoin): the
/// token sits at exactly that address (so its code is the recorded version, built through the coin-deployer
/// proxy) and names this bridge and this chain's PoolManager. A hostile core / coin-deployer upgrade can
/// therefore never register a token of its own (mintable, re-pointed) for any coinId.
/// One address on every EVM chain (PangeaDeployerV4, fixed salt, init code without arguments; owner, coin-deployer
/// proxy and PoolManager via pending()). The same versions must be added on every chain with the same activeFrom:
/// `versionsHash` is then equal everywhere (VerifyBridgeV4 compares it to the build's version 0).
contract CoinCodeRegistryV4 is Ownable2Step {
struct Version {
address a; // first half of the creation code (CodeStoreV4 data contract)
address b; // second half
uint64 activeFrom;
bytes32 codeHash; // keccak256(creation code)
}
/// @notice The coin-deployer PROXY (the CREATE2 deployer of every coin on this chain).
address public immutable coinDeployer;
address public immutable poolManager;
Version[] internal _versions;
/// @notice keccak256 chain over every (codeHash, activeFrom) added, in order: equal on every chain when they agree.
bytes32 public versionsHash;
event VersionAdded(uint256 indexed version, bytes32 codeHash, uint64 activeFrom);
error BadActiveFrom(uint64 activeFrom);
error EmptyCode();
error NoVersion(uint64 createdAt);
error ZeroAddress();
constructor() Ownable(_pendingOwner()) {
(, address cd, address pm) = abi.decode(IPendingConfigV4(msg.sender).pending(), (address, address, address));
if (cd == address(0) || pm == address(0)) revert ZeroAddress();
coinDeployer = cd;
poolManager = pm;
}
function _pendingOwner() private view returns (address o) {
(o,,) = abi.decode(IPendingConfigV4(msg.sender).pending(), (address, address, address));
}
/// @notice Appends a coin creation code. The first version must have activeFrom 0; every later one an activeFrom
/// strictly after this block and after the previous version's.
function addVersion(bytes calldata code, uint64 activeFrom) external onlyOwner returns (uint256 v) {
if (code.length == 0) revert EmptyCode();
v = _versions.length;
if (v == 0) {
if (activeFrom != 0) revert BadActiveFrom(activeFrom);
} else if (activeFrom <= block.timestamp || activeFrom <= _versions[v - 1].activeFrom) {
revert BadActiveFrom(activeFrom);
}
(address a, address b) = CodeStoreV4.storeHalves(code);
bytes32 h = keccak256(code);
_versions.push(Version(a, b, activeFrom, h));
versionsHash = keccak256(abi.encode(versionsHash, h, activeFrom));
emit VersionAdded(v, h, activeFrom);
}
function versionCount() external view returns (uint256) {
return _versions.length;
}
function version(uint256 v) external view returns (Version memory) {
return _versions[v];
}
/// @notice The version of a coin created at `createdAt`: the newest with activeFrom <= createdAt.
function versionAt(uint64 createdAt) public view returns (uint256) {
uint256 n = _versions.length;
while (n != 0) {
if (_versions[n - 1].activeFrom <= createdAt) return n - 1;
n--;
}
revert NoVersion(createdAt);
}
/// @notice The creation code of version `v`, exactly as added.
function creationCode(uint256 v) public view returns (bytes memory code) {
Version storage x = _versions[v];
(address a, address b) = (x.a, x.b);
uint256 la = a.code.length - 1;
uint256 lb = b.code.length - 1;
code = new bytes(la + lb);
assembly ("memory-safe") {
extcodecopy(a, add(code, 32), 1, la)
extcodecopy(b, add(add(code, 32), la), 1, lb)
}
}
/// @notice The creation code a coin created at `createdAt` is deployed with.
function creationCodeAt(uint64 createdAt) external view returns (bytes memory) {
return creationCode(versionAt(createdAt));
}
/// @notice The one address of coin `coinId` (created at `createdAt`) on every EVM chain.
function tokenAddress(bytes32 coinId, string memory name, string memory symbol, address creatorAtLaunch, uint64 createdAt)
public
view
returns (address)
{
bytes32 h = keccak256(abi.encodePacked(creationCode(versionAt(createdAt)), abi.encode(name, symbol, coinId, creatorAtLaunch)));
return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), coinDeployer, coinId, h)))));
}
/// @notice True only for the genuine coin `coinId` (created at `createdAt`) of `bridge_` on this chain: at its
/// recorded-version CREATE2 address under the coin-deployer proxy, naming `bridge_` and this PoolManager.
function genuine(address token, bytes32 coinId, address bridge_, uint64 createdAt) external view returns (bool) {
if (token.code.length == 0) return false;
ICoinFactsV4 t = ICoinFactsV4(token);
if (t.coinId() != coinId || t.bridge() != bridge_ || t.poolManager() != poolManager) return false;
return token == tokenAddress(coinId, t.name(), t.symbol(), t.creatorAtLaunch(), createdAt);
}
}
src/v4/bridge/PangeaCoinV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import {GapRecorderV4} from "../gap/GapRecorderV4.sol";
import {GapMathV4} from "../gap/GapMathV4.sol";
import {GapBlockV4} from "../gap/GapBlockV4.sol";
import {PangeaOFTV4Storage as S} from "../gap/PangeaOFTV4Storage.sol";
/// @notice What the coin reads from CoinDeployerV4 while it is constructed (bridge + the opening mint's recipient),
/// keeping both out of the init code: one CREATE2 address per coin on every EVM chain.
interface ITokenOpenV4 {
function bridge() external view returns (address);
function poolManager() external view returns (address);
function pendingMintTo() external view returns (address);
/// @notice META-EVM (owner Q1 1150): the coin's first metadataURI (the open's OpenArgs.metadataURI; may be empty),
/// read like pendingMintTo so it stays out of the init code (the token address does not depend on it).
function pendingMetadataURI() external view returns (string memory);
/// @notice SUPPLY MIRROR: the address that may report this coin's global minted supply (SupplyReporter).
function supplyReporter() external view returns (address);
}
interface ICreatorOfV4 {
function creatorOf(bytes32 coinId) external view returns (address);
function core() external view returns (address);
function coinInfo(bytes32 coinId)
external
view
returns (address token, uint32 homePcid, uint16 transportMask, uint8 nChains, uint32[] memory chains);
}
/// @title PangeaCoinV4 -- a v4 coin on one chain (V4-INTERFACES §11.2.8)
/// @notice Plain ERC-20 + EIP-2612 permit, 9 decimals, no owner. Exactly OPEN_SUPPLY (1B) is minted ONCE, in the
/// constructor, when this chain opens (CoinDeployerV4, CREATE2 salt = coinId). Afterwards only the immutable
/// bridge mints (verified arrivals, never more than burned at the source) and burns (only its own caller's
/// tokens, or tokens it just bought). No other issuance path exists.
/// Same-transaction sale lock (§11.2.8, B1-M1): after a buyAndSend the bridge calls lockSales(); for the rest of
/// that transaction a transfer of this coin TO the PoolManager reverts SameTxSellLocked (no buy-then-dump in
/// one transaction). B3-I2 (assessed, documented, not fixable here): a sale settled with
/// ERC-6909 claims of this coin already held in the PoolManager (deposited before the lock, even earlier in the
/// same transaction) moves no ERC-20 and is not seen by this lock; refusing it would need the pool's hook (the
/// live, unchanged V2 hook). The lock is defence in depth only: the buy's price is Ps = min(Pexec, Panchor x
/// (1 + k)) with Panchor read BEFORE the buy (B1-M1), so a same-transaction dump cannot raise what is credited.
/// Price recorder (§11.2.8, B1-M1): the audited old-scope GapRecorderV4 ring, unchanged, in this coin's
/// storage (PangeaOFTV4Storage's namespace): every non-zero move to / from the PoolManager records the official
/// pool's live price (the pool learned once from the bridge, GapRecorderV4.learn); `gapPrices()` gives the
/// fallback reads of §11.3.4 (Pref = min over L at the source, Pd_ref = pdTrusted at the destination), which
/// a same-block pump cannot raise / a same-block dump cannot lower.
contract PangeaCoinV4 is ERC20Permit {
uint256 public constant OPEN_SUPPLY = 1_000_000_000 * 1e9;
address public immutable bridge;
bytes32 public immutable coinId;
address public immutable creatorAtLaunch;
address public immutable poolManager;
bool internal transient _salesLocked;
/// @notice Arbitrum-stack chain (Robinhood): the ring counts L2 blocks (GapBlockV4), probed once at construction.
bool public immutable arbBlocks;
uint256 internal constant LOOKBACK = GapMathV4.LOOKBACK_DEFAULT_SEC;
/// @notice META-EVM (owner Q1 1150; live CH:89 BadTerms(9)): the most bytes a metadataURI may have.
uint256 public constant MAX_METADATA_URI_BYTES = 128;
address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
/// @notice META-EVM (owner Q1 1150, live PangeaOFTV3:207 / PangeaOFTV3LogModule:53-65): logo, description and links.
/// Set at the open (may be empty), then by the metadata authority only (setMetadataURI).
string public metadataURI;
/// @notice SUPPLY MIRROR (owner 2026-11-12, ported from PangeaOFTV3): `totalSupply()` reports the coin's GLOBAL
/// minted supply (web/lib/v4/supply-minted-v4.mjs: the open chains' local supplies + in flight), written by
/// `supplyReporter` (follows it up or down), floored at this chain's own supply. `localSupply()` is what is
/// really on this chain; balances and transfers are the plain local ERC-20's. 0 = never reported.
uint256 public reportedSupply;
/// @notice The only address that may call reportSupply (the v4 SupplyReporter: one address on every chain). Read
/// from the coin deployer at construction (not in the init code: the coin's address does not depend on it).
address public immutable supplyReporter;
/// @notice `totalSupply()` now reports `newSupply` (was `oldSupply`). No balance moved.
event SupplyReported(uint256 oldSupply, uint256 newSupply);
/// @notice Live PangeaOFTV3 / PangeaOFTV3LogModule event, same signature.
event MetadataURISet(string uri);
error NotBridge();
error NotSupplyReporter();
/// @notice A report above the coin's listed chains x 1B (it can never have minted more).
error SupplyAboveListed(uint256 supply, uint256 max);
error ZeroMintTo();
error ZeroBridge();
error SameTxSellLocked();
/// @notice Live PangeaOFTV3LogModule error: the caller is not the metadata authority.
error NotMetadataAuthority();
/// @notice META-EVM: a metadataURI above MAX_METADATA_URI_BYTES (live refused it at launch: CH:89 BadTerms(9)).
error MetadataURITooLong(uint256 length);
/// @notice v4-gap-A2 item 3 / TOKENOMICS-V4: the coin's creator NOW on this chain = its vault while the chain's
/// tokenomics switch is on (LaunchCoreV4.tokenomicsOf), else the bridge's creator role (0xdEaD after a
/// renounce). A TokenomicsVaultV24 binds only when this names it (ITokenomicsCoin.creator); the fee hook
/// never reads it.
function creator() external view returns (address) {
address core = ICreatorOfV4(bridge).core();
(bool ok, bytes memory r) = core.staticcall(abi.encodeWithSignature("tokenomicsOf(bytes32)", coinId));
if (ok && r.length == 32) {
address v = abi.decode(r, (address));
if (v != address(0)) return v;
}
return ICreatorOfV4(bridge).creatorOf(coinId);
}
constructor(string memory name_, string memory symbol_, bytes32 coinId_, address creatorAtLaunch_)
ERC20(name_, symbol_)
ERC20Permit(name_)
{
bridge = ITokenOpenV4(msg.sender).bridge();
if (bridge == address(0)) revert ZeroBridge();
coinId = coinId_;
creatorAtLaunch = creatorAtLaunch_;
poolManager = ITokenOpenV4(msg.sender).poolManager();
supplyReporter = ITokenOpenV4(msg.sender).supplyReporter();
arbBlocks = GapBlockV4.arbitrumStack();
address to = ITokenOpenV4(msg.sender).pendingMintTo();
if (to == address(0)) revert ZeroMintTo();
_mint(to, OPEN_SUPPLY);
string memory uri = ITokenOpenV4(msg.sender).pendingMetadataURI();
if (bytes(uri).length > MAX_METADATA_URI_BYTES) revert MetadataURITooLong(bytes(uri).length);
if (bytes(uri).length > 0) {
metadataURI = uri;
emit MetadataURISet(uri);
}
}
/// @notice META-EVM (owner Q1 1150): who may set metadataURI = the coin's creator role on this chain as the bridge
/// holds it (BridgeRoleV4.creatorOf: the current creator after a handover / admin step-in, as mirrored
/// here). address(0) = nobody (after a renounce, or no EVM creator). Live's separate
/// propose/acceptMetadataAuthority is replaced by the bridge's creator handover (one role, not two).
function metadataAuthority() public view returns (address a) {
a = ICreatorOfV4(bridge).creatorOf(coinId);
if (a == DEAD) a = address(0);
}
/// @notice Live PangeaOFTV3LogModule.setMetadataURI, plus the live launch bound (<= 128 bytes). Empty clears it.
function setMetadataURI(string calldata uri) external {
address a = metadataAuthority();
if (a == address(0) || msg.sender != a) revert NotMetadataAuthority();
if (bytes(uri).length > MAX_METADATA_URI_BYTES) revert MetadataURITooLong(bytes(uri).length);
metadataURI = uri;
emit MetadataURISet(uri);
}
function decimals() public pure override returns (uint8) {
return 9;
}
// ------------------------------------------------------------------ supply mirror (PangeaOFTV3 port)
/// @notice The global minted supply as last reported, never below this chain's own supply (before any report: the
/// local supply). Display only: nothing on chain reads it (every share, cap and bridge figure is local).
function totalSupply() public view override returns (uint256) {
uint256 l = super.totalSupply();
uint256 r = reportedSupply;
return r > l ? r : l;
}
/// @notice What is really on this chain (the ERC-20's own total).
function localSupply() external view returns (uint256) {
return super.totalSupply();
}
/// @notice The most a report may say: the coin's listed chains (the bridge's coin record) x OPEN_SUPPLY.
function maxReportableSupply() public view returns (uint256) {
(,,, uint8 n,) = ICreatorOfV4(bridge).coinInfo(coinId);
return uint256(n) * OPEN_SUPPLY;
}
/// @notice The supply reporter writes the global minted supply (up or down). Above maxReportableSupply reverts; a
/// figure below the local supply is kept but totalSupply() floors it (an arrival can land before a report).
function reportSupply(uint256 newSupply) external {
if (supplyReporter == address(0) || msg.sender != supplyReporter) revert NotSupplyReporter();
uint256 max = maxReportableSupply();
if (newSupply > max) revert SupplyAboveListed(newSupply, max);
uint256 old = reportedSupply;
if (newSupply == old) return;
reportedSupply = newSupply;
emit SupplyReported(old, newSupply);
emit Transfer(address(0), DEAD, 0);
}
function bridgeMint(address to, uint256 amount) external {
if (msg.sender != bridge) revert NotBridge();
_mint(to, amount);
}
/// @notice The bridge moves its own caller's bridge fee (B1-L4); called only with `from` = the bridge's caller.
function bridgeTransfer(address from, address to, uint256 amount) external {
if (msg.sender != bridge) revert NotBridge();
_transfer(from, to, amount);
}
/// @notice The bridge, right after a buyAndSend's swap: no sale of this coin into the PoolManager for the rest of
/// the transaction.
function lockSales() external {
if (msg.sender != bridge) revert NotBridge();
_salesLocked = true;
}
function _update(address from, address to, uint256 value) internal override {
address pm = poolManager;
if (_salesLocked && to == pm && value != 0) revert SameTxSellLocked();
super._update(from, to, value);
if (value != 0 && from != to && (from == pm || to == pm) && pm != address(0)) {
GapRecorderV4.recordLive(S.layout(), pm, bridge, GapBlockV4.number(arbBlocks));
}
}
/// @notice The recorded prices of the official pool, quote x 1e18 per whole coin (0 = none / pool not known):
/// Plast (newest earlier-block record), Pref (source: min(live, the ring within L)), Pd_ref (destination:
/// GapMathV4.pdTrusted, the max rule), live (rounded down).
function gapPrices() external view returns (uint256 plast, uint256 pref, uint256 pdRef, uint256 live) {
S.Layout storage l = S.layout();
if (!l.known) return (0, 0, 0, 0);
uint256 blk = GapBlockV4.number(arbBlocks);
GapMathV4.Ring memory r = GapRecorderV4.load(l);
live = GapRecorderV4.livePrice(l, poolManager, false);
plast = GapMathV4.plast(r, blk);
pref = GapMathV4.pref(r, live, block.timestamp, blk, LOOKBACK);
pdRef = GapMathV4.pdTrusted(
r, GapRecorderV4.livePrice(l, poolManager, true), block.timestamp, blk, LOOKBACK, GapRecorderV4.bucketWidth(l)
);
}
function bridgeBurn(address from, uint256 amount) external {
if (msg.sender != bridge) revert NotBridge();
_burn(from, amount);
}
}
src/v4/bridge/PangeaDeployerV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @notice What a v4 infra contract reads from its deployer in its constructor (the TokenDeployerV4 pattern, §11.2.1):
/// chain-specific values stay out of the init code, so the address is the same on every EVM chain.
interface IPendingConfigV4 {
function pending() external view returns (bytes memory);
}
/// @title PangeaDeployerV4 -- CREATE2 deployer of the shared-bridge infra (bridge, adapters, coin deployer, core)
/// @notice Itself deployed through the canonical CREATE2 deployer with a fixed salt and `initializer` (the same deploy
/// key / multisig in every config), so it has one address on every EVM chain, and so does everything it deploys
/// with the same salt and init code. Only `initializer` deploys; the per-chain config is handed over through
/// `pending()` for the duration of the constructor only.
contract PangeaDeployerV4 is IPendingConfigV4 {
address public immutable initializer;
bytes internal _pending;
event Deployed(bytes32 indexed salt, address indexed at);
error NotInitializer();
error DeployFailed();
constructor(address initializer_) {
initializer = initializer_;
}
function pending() external view returns (bytes memory) {
return _pending;
}
function predict(bytes32 salt, bytes calldata initcode) external view returns (address) {
return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(initcode))))));
}
function deploy(bytes32 salt, bytes calldata initcode, bytes calldata config) external returns (address a) {
if (msg.sender != initializer) revert NotInitializer();
_pending = config;
bytes memory code = initcode;
assembly ("memory-safe") {
a := create2(0, add(code, 0x20), mload(code), salt)
}
delete _pending;
if (a == address(0)) revert DeployFailed();
emit Deployed(salt, a);
}
}
src/v4/factory/CodeStoreV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title CodeStoreV4 -- deploys bytes as the runtime code of a data contract (a STOP byte, then the bytes),
/// TokenDeployerV3's `_store`, as a library for the tests: the two halves of the PangeaOFTV4 and
/// PangeaOFTV4GapModule creation codes PangeaTokenDeployerV4 reads (each half under EIP-170's 24,576).
library CodeStoreV4 {
error CodeStoreFailed();
function store(bytes memory data) internal returns (address at) {
// PUSH4 len, DUP1, PUSH1 14, PUSH1 0, CODECOPY, PUSH1 0, RETURN -- then the runtime.
bytes memory init = abi.encodePacked(hex"63", uint32(data.length + 1), hex"80600e6000396000f3", hex"00", data);
assembly ("memory-safe") {
at := create(0, add(init, 32), mload(init))
}
if (at == address(0)) revert CodeStoreFailed();
}
/// @notice Store `code` in two halves; returns their addresses.
function storeHalves(bytes memory code) internal returns (address a, address b) {
uint256 la = code.length / 2;
uint256 lb = code.length - la;
bytes memory first = new bytes(la);
bytes memory second = new bytes(lb);
assembly ("memory-safe") {
mcopy(add(first, 32), add(code, 32), la)
mcopy(add(second, 32), add(add(code, 32), la), lb)
}
a = store(first);
b = store(second);
}
}
src/v4/gap/GapBlockV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title GapBlockV4 -- the block number the v4 gap rules count in ("an earlier block", the ring's blocks)
/// @notice Audit r4 R4-1 (lead ruling): "earlier block" means the chain's OWN block. On Arbitrum-stack chains
/// (Robinhood, Arbitrum) `block.number` is the parent chain's (L1) number (~12 s, many L2 blocks with
/// different timestamps), so there the rules read ArbSys(0x64).arbBlockNumber(), the L2 block. Which one is
/// an IMMUTABLE of the token (PangeaOFTV4.gapArbBlockNumber), fixed at its construction from its deployer
/// (ITokenParamsV4.pendingArbBlockNumber); nothing can change it later.
library GapBlockV4 {
/// @dev Arbitrum's ArbSys precompile.
address internal constant ARB_SYS = address(0x64);
/// @dev The read's gas cap (ArbSys answers in a few hundred gas; an INVALID-coded account must not eat the rest).
uint256 internal constant READ_GAS = 20_000;
/// @dev ArbSys did not answer (never on an Arbitrum-stack chain): fail closed rather than mix block numbers.
error GapBlockUnreadable();
/// @notice The current block in the rules' numbering: arbBlockNumber() when `arb`, else block.number.
function number(bool arb) internal view returns (uint256 n) {
if (!arb) return block.number;
(bool ok, bytes memory r) = ARB_SYS.staticcall{gas: READ_GAS}(abi.encodeWithSignature("arbBlockNumber()"));
if (!ok || r.length != 32) revert GapBlockUnreadable();
n = abi.decode(r, (uint256));
}
/// @notice Whether this chain answers ArbSys.arbBlockNumber() (an Arbitrum-stack chain). On any other chain
/// the answer is not 32 bytes -> false: no code at 0x64 (the call succeeds with no return data), or another
/// precompile there (BSC's refuses this input, from memory of bsc-geth; the probe then burns READ_GAS once).
function arbitrumStack() internal view returns (bool) {
(bool ok, bytes memory r) = ARB_SYS.staticcall{gas: READ_GAS}(abi.encodeWithSignature("arbBlockNumber()"));
return ok && r.length == 32;
}
}
src/v4/gap/GapMathV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IGapRegistryV4} from "./IGapRegistryV4.sol";
/// @title GapMathV4 -- the Gap v4 arithmetic and the codec v4 (spec §2-§11, V4-INTERFACES §2, §3)
/// @notice CANONICAL. The Rust port (solana/oft-v4 math_v4.rs) and the JS port (web/lib/v4/gap-math-v4.mjs)
/// implement the same functions and must pass test/v4/vectors/gap-math-v4.json, which
/// test/v4/vectors/GapMathV4Vectors.t.sol checks against this library. A change here is a change to
/// all three.
/// @dev All pure. Units: ppm = 1e6 base; every price is "pricing unit x 1e18 per WHOLE token" (uint128, 0 =
/// unknown); amounts are raw local units. Every product goes through 512-bit mulDiv. Rounding is always
/// AGAINST THE CREDIT: Ps, Pexec, Pref, the cover and m round DOWN; Pd, fD, the depth round UP; the credit
/// rounds DOWN (so the withheld part A - credited rounds up).
library GapMathV4 {
// ================================================================ units
uint256 internal constant PPM = 1_000_000;
uint256 internal constant E18 = 1e18;
uint256 internal constant PRICE_MAX = type(uint128).max;
/// @dev USD 1e18 per micro-dollar (the codec's cover unit).
uint256 internal constant MICRO_USD_E18 = 1e12;
/// @dev OFT shared decimals.
uint8 internal constant SHARED_DECIMALS = 6;
// ================================================================ codec v4 (spec §7, frozen)
uint8 internal constant VER = 0x04;
uint8 internal constant MODE_PLAIN = 0;
uint8 internal constant MODE_BUY = 1;
uint8 internal constant MODE_REFUND = 0xFF;
uint8 internal constant REFUND_CLASS = 255;
uint256 internal constant OFF_SEND_TO = 0; // bytes32
uint256 internal constant OFF_AMOUNT_SD = 32; // uint64 BE
uint256 internal constant OFF_VER = 40; // uint8
uint256 internal constant OFF_MODE = 41; // uint8
uint256 internal constant OFF_CLASS = 42; // uint8
uint256 internal constant OFF_PS_CLASS = 43; // uint128 BE
uint256 internal constant OFF_PS_USD = 59; // uint128 BE
uint256 internal constant OFF_BRIDGE_FEE = 75; // uint32 BE
uint256 internal constant OFF_COVER_SRC = 79; // uint32 BE, micro-USD
uint256 internal constant OFF_MIN_CREDITED = 83; // uint64 BE
uint256 internal constant OFF_RESERVED = 91; // 5 bytes, 0
uint256 internal constant HEADER_LEN = 96;
/// @notice decode status: a valid v4 message (mode 0 or 1).
uint8 internal constant DEC_OK = 0;
/// @notice decode status: exactly the refund marker (mode 0xFF, class 255, both prices 0, not composed).
uint8 internal constant DEC_REFUND = 1;
/// @notice decode status: not a valid codec v4 message: refused (never credited at fee 0).
uint8 internal constant DEC_BAD = 2;
error GapMsgTooShort(uint256 length);
struct Header {
bytes32 sendTo;
uint64 amountSD;
uint8 mode;
uint8 priceClass;
uint128 psClassE18;
uint128 psUsdE18;
uint32 bridgeFeePpm;
uint32 coverSrcMicroUsd;
uint64 minCreditedSD;
bool composed;
}
/// @notice The v4 message: the 96-byte header, then composeFrom | composeMsg iff composeMsg is not empty.
/// The sender's own message only; the refund marker is built by `encodeRefund`.
function encode(Header memory h, bytes32 composeFrom, bytes memory composeMsg) internal pure returns (bytes memory m) {
m = abi.encodePacked(
h.sendTo,
h.amountSD,
VER,
h.mode,
h.priceClass,
h.psClassE18,
h.psUsdE18,
h.bridgeFeePpm,
h.coverSrcMicroUsd,
h.minCreditedSD,
bytes5(0)
);
if (composeMsg.length != 0) m = abi.encodePacked(m, composeFrom, composeMsg);
}
/// @notice The refund marker (v3 AMENDMENT 2 shape, v4 codec): only an expired-compose return builds it.
function encodeRefund(bytes32 sendTo, uint64 amountSD) internal pure returns (bytes memory) {
Header memory h;
(h.sendTo, h.amountSD, h.mode, h.priceClass) = (sendTo, amountSD, MODE_REFUND, REFUND_CLASS);
return encode(h, bytes32(0), "");
}
/// @notice Decodes and VALIDATES a message. Reverts only below 40 bytes (no sendTo / amountSD).
/// DEC_BAD when: shorter than 96 bytes; ver != 4; reserved bytes != 0; mode not 0, 1 or 0xFF;
/// mode 0xFF or class 255 that is not exactly the refund marker; class 0 with psClass != 0, or class
/// != 0 with psClass == 0; bridgeFeePpm >= 1e6 (arithmetic: G divides by 1e6 - b); mode 0 with coverSrc != 0 or with
/// no price at all; mode 1 with psUsd == 0.
function decode(bytes calldata m) internal pure returns (Header memory h, uint8 status) {
if (m.length < OFF_VER) revert GapMsgTooShort(m.length);
h.sendTo = bytes32(m[OFF_SEND_TO:OFF_AMOUNT_SD]);
h.amountSD = uint64(bytes8(m[OFF_AMOUNT_SD:OFF_VER]));
if (m.length < HEADER_LEN || uint8(m[OFF_VER]) != VER) return (h, DEC_BAD);
h.mode = uint8(m[OFF_MODE]);
h.priceClass = uint8(m[OFF_CLASS]);
h.psClassE18 = uint128(bytes16(m[OFF_PS_CLASS:OFF_PS_USD]));
h.psUsdE18 = uint128(bytes16(m[OFF_PS_USD:OFF_BRIDGE_FEE]));
h.bridgeFeePpm = uint32(bytes4(m[OFF_BRIDGE_FEE:OFF_COVER_SRC]));
h.coverSrcMicroUsd = uint32(bytes4(m[OFF_COVER_SRC:OFF_MIN_CREDITED]));
h.minCreditedSD = uint64(bytes8(m[OFF_MIN_CREDITED:OFF_RESERVED]));
h.composed = m.length > HEADER_LEN;
status = validate(h, bytes5(m[OFF_RESERVED:HEADER_LEN]));
}
/// @notice The rules of `decode` on decoded fields (shared with the vectors' memory decode).
function validate(Header memory h, bytes5 reserved) internal pure returns (uint8) {
if (reserved != bytes5(0)) return DEC_BAD;
if (h.mode == MODE_REFUND || h.priceClass == REFUND_CLASS) {
bool exact = h.mode == MODE_REFUND && h.priceClass == REFUND_CLASS && h.psClassE18 == 0 && h.psUsdE18 == 0
&& !h.composed;
return exact ? DEC_REFUND : DEC_BAD;
}
if (h.mode != MODE_PLAIN && h.mode != MODE_BUY) return DEC_BAD;
if ((h.priceClass == 0) != (h.psClassE18 == 0)) return DEC_BAD;
if (h.bridgeFeePpm >= PPM) return DEC_BAD;
if (h.mode == MODE_PLAIN) {
if (h.coverSrcMicroUsd != 0) return DEC_BAD;
if (h.psClassE18 == 0 && h.psUsdE18 == 0) return DEC_BAD;
} else if (h.psUsdE18 == 0) {
return DEC_BAD;
}
return DEC_OK;
}
/// @notice `composeFrom | composeMsg` of a composed message (LayerZero OFTComposeMsgCodec's last argument).
function composeTail(bytes calldata m) internal pure returns (bytes calldata) {
return m[HEADER_LEN:];
}
// ================================================================ defaults (LEAD UPDATE 2: NO compiled bounds)
//
// Every v4 parameter is an admin setting (per chain + per-coin override, GapRegistryV4.paramsOf). These are
// the documented defaults only; the code keeps arithmetic safety (no overflow, no division by zero) and
// resolves a nonsensical pair deterministically: min > max -> max wins.
uint64 internal constant MARGIN_K_DEFAULT = 1_000_000; // K = 1, x 1e6
uint32 internal constant MARGIN_MIN_DEFAULT_PPM = 1_000;
uint32 internal constant MARGIN_MAX_DEFAULT_PPM = 100_000;
uint64 internal constant EXEC_CAP_K_DEFAULT = 2_000_000; // Kk = 2, x 1e6
uint32 internal constant EXEC_CAP_MIN_DEFAULT_PPM = 15_000;
uint32 internal constant EXEC_CAP_MAX_DEFAULT_PPM = 200_000;
uint32 internal constant LOOKBACK_DEFAULT_SEC = 30;
uint32 internal constant FEE_CAP_DEFAULT_PPM = 10_000;
uint16 internal constant BRIDGE_FEE_DEFAULT_BPS = 20;
/// @dev The largest bridge fee a token charges: 9,999 bps (999,900 ppm < 1e6, which the codec accepts on EVM
/// and Solana). >= 10,000 bps would carry b >= 1e6, a message no destination can decode (invariant iii).
uint16 internal constant BRIDGE_FEE_MAX_BPS = 9_999;
// ================================================================ receive outcomes (events, previews)
uint8 internal constant R_CREDITED = 0; // the formula ran (withheld may be 0)
uint8 internal constant R_BAD_VERSION = 1; // DEC_BAD: refused
uint8 internal constant R_REFUND = 2; // the refund marker: full
uint8 internal constant R_ESCAPED = 3; // the per-coin escape: full
uint8 internal constant R_SEED_NO_POOL = 4; // no pool here, a listed seeder: full
uint8 internal constant R_NO_POOL = 5; // no pool here: hold
uint8 internal constant R_UNREADABLE = 6; // Pd, fD, m (depth) or the cover unreadable: hold
uint8 internal constant R_BELOW_MIN = 7; // credited < minCredited: hold (acceptBelowMin lands it)
uint8 internal constant R_UNTRUSTED = 8; // not a trusted executor: refused
uint8 internal constant R_BURN_OFF = 9; // burn off (LEAD UPDATE 3 §9.1): credited in full
// ================================================================ settings
/// @notice The bridge fee a token charges (LEAD UPDATE 3 §9.4): the resolved registry bps when readable and at
/// most 9,999; unreadable or >= 10,000 (which the registry refuses, and whose b >= 1e6 the codec refuses)
/// counts as unreadable: the default 20. Every send therefore carries b < 1e6.
function bridgeFeeBpsOrDefault(bool ok, uint256 bps) internal pure returns (uint16) {
if (!ok || bps > BRIDGE_FEE_MAX_BPS) return BRIDGE_FEE_DEFAULT_BPS;
return uint16(bps);
}
/// @notice A curve clamp(lo, hi, floor(K x 1e9 / sqrtUp(depthUsdE18))) (LEAD UPDATE 2: K stored x 1e6, so
/// the result is ppm): lo > hi -> hi wins (lo := hi); K 0 -> lo; depth 0 -> hi (an UNREADABLE depth is
/// the caller's hold, never this).
function curve(uint64 k, uint32 lo, uint32 hi, uint256 depthUsd) internal pure returns (uint32) {
if (lo > hi) lo = hi;
if (k == 0) return lo;
if (depthUsd == 0) return hi;
uint256 d = uint256(k) * 1e9 / sqrtUp(depthUsd);
if (d < lo) return lo;
if (d > hi) return hi;
return uint32(d);
}
// ================================================================ prices (spec §3, §5)
/// @notice ceil(a * b / 1e18); 0 if either factor is 0 or above PRICE_MAX, or the product above PRICE_MAX.
function mulUp(uint256 a, uint256 b) internal pure returns (uint256 p) {
if (a == 0 || b == 0 || a > PRICE_MAX || b > PRICE_MAX) return 0;
p = Math.mulDiv(a, b, E18, Math.Rounding.Ceil);
if (p > PRICE_MAX) return 0;
}
/// @notice floor(a * b / 1e18); 0 if either factor is 0 or above PRICE_MAX, the product 0 or above PRICE_MAX.
function mulDown(uint256 a, uint256 b) internal pure returns (uint256 p) {
if (a == 0 || b == 0 || a > PRICE_MAX || b > PRICE_MAX) return 0;
p = Math.mulDiv(a, b, E18);
if (p > PRICE_MAX) return 0;
}
/// @notice The part of the official pool's HOOK fee above feeCapPpm is removed from what the buyer paid
/// (spec §5): quotePaid - ceil(quotePaid * (hookFeePpm - feeCapPpm) / 1e6) when the hook fee is above
/// the cap, else quotePaid. (A fee taken in tokens is capped the same way: the removal is in value.)
function capQuotePaid(uint256 quotePaid, uint256 hookFeePpm, uint256 feeCapPpm) internal pure returns (uint256) {
if (hookFeePpm <= feeCapPpm) return quotePaid;
uint256 ex = hookFeePpm - feeCapPpm;
if (ex >= PPM) return 0;
return quotePaid - Math.mulDiv(quotePaid, ex, PPM, Math.Rounding.Ceil);
}
/// @notice Pexec = floor(quotePaid * 10^decTok * 1e18 / (tokensOut * 10^decQuote)): quote units x 1e18 per
/// whole token. 0 (unpriced: the buy reverts) when tokensOut is 0, the decimals are out of range
/// (|18 + decTok - decQuote| > 36) or the result is 0 or above PRICE_MAX.
function pexec(uint256 quotePaid, uint256 tokensOut, uint8 decTok, uint8 decQuote) internal pure returns (uint256 p) {
if (tokensOut == 0) return 0;
int256 e = 18 + int256(uint256(decTok)) - int256(uint256(decQuote));
if (e > 36 || e < -36) return 0;
if (e >= 0) {
// quotePaid / tokensOut above PRICE_MAX stays above it scaled up; below it the product fits.
if (quotePaid / tokensOut > PRICE_MAX) return 0;
p = Math.mulDiv(quotePaid, 10 ** uint256(e), tokensOut);
} else {
p = quotePaid / tokensOut / 10 ** uint256(-e);
}
if (p > PRICE_MAX) return 0;
}
/// @notice floor(Plast * (1e6 + k) / 1e6), at most PRICE_MAX.
function execCap(uint256 plastE18, uint256 k) internal pure returns (uint256 c) {
c = Math.mulDiv(plastE18, PPM + k, PPM);
if (c > PRICE_MAX) c = PRICE_MAX;
}
/// @notice The backstop k (LEAD UPDATE 2): max(mSrc, curve(Kk, kMin, kMax, srcDepthUsd)), mSrc the margin curve
/// at the same source depth (so k >= m always).
function kPpm(uint64 kk, uint32 kMin, uint32 kMax, uint256 srcDepthUsd, uint32 mSrcPpm) internal pure returns (uint32) {
uint32 k = curve(kk, kMin, kMax, srcDepthUsd);
return k > mSrcPpm ? k : mSrcPpm;
}
/// @notice The buy path's credit price (D2): Ps = min(Pexec, floor(Plast * (1 + k))) when the backstop is on,
/// Pexec when it is off. 0 when Pexec is 0, or (on) Plast is 0 (no record from an earlier block: the buy
/// reverts GapNeedRecord).
function psBuy(uint256 pexecE18, uint256 plastE18, bool on, uint256 k) internal pure returns (uint256) {
if (pexecE18 == 0) return 0;
if (!on) return pexecE18;
if (plastE18 == 0) return 0;
uint256 c = execCap(plastE18, k);
return pexecE18 < c ? pexecE18 : c;
}
/// @notice The destination's class pair or USD pair (v3 pickPair, unchanged): the class pair when the
/// message's class is non-zero, equal to the destination quote's class and both class prices are
/// known; else the USD pair when both are known; else nothing (hold).
function pickPair(uint8 msgClass, uint256 psClass, uint256 psUsd, uint8 dstClass, uint256 pdClass, uint256 pdUsd)
internal
pure
returns (bool ok, uint256 ps, uint256 pd, bool isClass)
{
if (msgClass != 0 && msgClass == dstClass && psClass != 0 && pdClass != 0) return (true, psClass, pdClass, true);
if (psUsd != 0 && pdUsd != 0) return (true, psUsd, pdUsd, false);
return (false, 0, 0, false);
}
// ================================================================ the recorder (spec §4a, §4d, §4e)
//
// Three buckets in a ring, each `width` seconds wide (width = L/2, the token's cached look-back; an L change
// reaches the buckets at the next send or receive and takes full effect within one L). A bucket keeps
// {start, lastTs, lastBlock, min, max, lastPrice}; a NEW bucket's min and max start at the price in force when
// it opens (the previous record's lastPrice: the "open price"), so the oldest bucket still in the ring always
// carries the price in force before its first record. The ring also keeps the last price of the newest block
// before the head bucket's lastBlock (prevBlock, prevPrice), so "the newest record from an earlier block" is
// known even after records of the current block.
struct Slot {
uint40 start; // bucket start, unix seconds (a multiple of the width at write time)
uint40 lastTs; // timestamp of its latest record
uint48 lastBlock; // block of its latest record; 0 = empty slot
uint128 min; // min of its records and its open price
uint128 max; // max of its records and its open price
uint128 lastPrice; // its latest record
}
struct Ring {
Slot[3] s;
uint8 head; // the newest slot
uint48 prevBlock; // the block before head.lastBlock that has a record (0 = none)
uint128 prevPrice; // its last record
uint40 prevTs; // its timestamp (audit r2: the destination's age bound)
}
/// @notice One record (the official pool's price `p`, quote x 1e18 per whole token, rounded DOWN) at
/// (`ts`, `blk`), into buckets of `width` seconds. A zero price or width writes nothing.
function ringWrite(Ring memory r, uint256 p, uint256 ts, uint256 blk, uint256 width) internal pure returns (Ring memory) {
if (p == 0 || width == 0) return r;
if (p > PRICE_MAX) p = PRICE_MAX;
uint128 price = uint128(p);
Slot memory h = r.s[r.head];
uint40 start = uint40(ts - ts % width);
if (h.lastBlock == 0) {
// the first record ever: its own open price
r.s[r.head] = Slot(start, uint40(ts), uint48(blk), price, price, price);
return r;
}
if (blk != h.lastBlock) (r.prevBlock, r.prevPrice, r.prevTs) = (h.lastBlock, h.lastPrice, h.lastTs);
if (start <= h.start) {
// the same bucket (or an older start after a width change: the head keeps it)
if (price < h.min) h.min = price;
if (price > h.max) h.max = price;
(h.lastTs, h.lastBlock, h.lastPrice) = (uint40(ts), uint48(blk), price);
r.s[r.head] = h;
return r;
}
uint128 open = h.lastPrice;
uint8 n = uint8((uint256(r.head) + 1) % 3);
r.s[n] = Slot(start, uint40(ts), uint48(blk), open < price ? open : price, open > price ? open : price, price);
r.head = n;
return r;
}
/// @notice Plast: the lastPrice of the newest record from a block BEFORE `blk` (0 = none).
function plast(Ring memory r, uint256 blk) internal pure returns (uint256 p) {
(p,) = plastRec(r, blk);
}
/// @notice The newest record from a block BEFORE `blk`: its price and timestamp ((0, 0) = none).
function plastRec(Ring memory r, uint256 blk) internal pure returns (uint256 p, uint256 t) {
Slot memory h = r.s[r.head];
if (h.lastBlock == 0) return (0, 0);
if (h.lastBlock < blk) return (h.lastPrice, h.lastTs);
if (r.prevBlock != 0 && r.prevBlock < blk) return (r.prevPrice, r.prevTs);
return (0, 0);
}
/// @notice Pref_src (spec §4e) = min(live, every bucket with a record at or after now - L (its min, which
/// includes its open price), the lastPrice of the newest bucket whose last record is before now - L
/// (the price in force at the window start)). Records of the current block can only LOWER it (a
/// minimum), never raise it. 0 (the send reverts GapNeedRecord) when there is no record from an
/// earlier block or `live` is 0.
function pref(Ring memory r, uint256 live, uint256 ts, uint256 blk, uint256 lookback) internal pure returns (uint256 v) {
if (live == 0 || plast(r, blk) == 0) return 0;
v = live;
uint256 from = ts > lookback ? ts - lookback : 0;
uint256 preTs;
uint256 prePrice;
for (uint256 i; i < 3; i++) {
Slot memory s = r.s[i];
if (s.lastBlock == 0) continue;
if (s.lastTs >= from) {
if (s.min < v) v = s.min;
} else if (s.lastTs >= preTs) {
(preTs, prePrice) = (s.lastTs, s.lastPrice);
}
}
if (prePrice != 0 && prePrice < v) v = prePrice;
}
/// @notice Pd for a TRUSTED delivery (audit r3 F1 / F2 rulings, r4 R4-1 + lead ruling R4-1-2; r2 G2-02). With
/// R = the newest earlier-block record and B = the max of EVERY ring bucket whose last record is at or after
/// R (R's own bucket carries the price in force when it opened, so a netted fake LOW close cannot hide the
/// honest price before it; later buckets hold only current-block records, which can only raise Pd), and
/// H = horizonMax (every bucket max within L + 3 widths and the previous block's close, as pdSelf):
/// - R within the look-back (ts >= now - L): Pd = max(live, R + 1, B + 1, H);
/// - R stale but the pool already has a record from the CURRENT block (it was traded before the delivery
/// in this block, e.g. a same-block dump): the same -- the price in force at the start of the block,
/// so a same-block dump never lowers it;
/// - otherwise (a quiet pool, no current-block trade): Pd = live (a stale planted close cannot pin Pd).
/// H (lead ruling after r4, r5 G5-M1): the honest price stays counted until its bucket ages out of H or
/// leaves the ring. NOT a closure of the netted-fake attack: A-SETTERS.md "Pd" has the measured residual
/// (a trusted delivery has no L gate, so two fakes still work once a same-block dump waits out L + 3w).
/// Accepted cost: honest trusted arrivals within L + 3w of a real spike, or on the first record after a
/// quiet stretch that ended one, are priced at it (a lower credit, a larger burn).
/// R4-1: when R counts but its bucket is no longer in the ring (three newer buckets opened in the current
/// block), 0: the caller HOLDS (retriable next block), never the bare R.
/// Accepted residual (grief only): a stale HIGH (planted, or an honest old spike in R's bucket: R4-4) plus
/// any trade in the delivery's block before it counts again (a lower credit). 0 when live is 0.
function pdTrusted(Ring memory r, uint256 liveUp, uint256 ts, uint256 blk, uint256 lookback, uint256 width)
internal
pure
returns (uint256)
{
if (liveUp == 0) return 0;
(uint256 p, uint256 t, uint256 bmax, bool inRing) = plastRecBucket(r, blk);
if (p == 0) return liveUp;
bool within = t + lookback >= ts;
bool currentBlockTraded = r.s[r.head].lastBlock == blk;
if (!within && !currentBlockTraded) return liveUp;
if (!inRing) return 0;
uint256 rec = (bmax > p ? bmax : p) + 1;
(uint256 hz,) = horizonMax(r, ts, blk, lookback, width);
if (hz > rec) rec = hz;
return liveUp > rec ? liveUp : rec;
}
/// @notice The max + 1 of every non-empty bucket still in force within L + 3 bucket widths (r4 R4-2: 2.5 L at width
/// L/2) and of the previous block's close when as recent (0 = none). A bucket's close stays in force until
/// the next newer bucket opens, however late, so a bucket counts while its last record OR the next newer
/// bucket's start is within that horizon (r5 G5-M1, option 1). `ok`: a record from an earlier block
/// within L exists (a bucket counts only when its last record is from an earlier block, F6).
function horizonMax(Ring memory r, uint256 ts, uint256 blk, uint256 lookback, uint256 width)
internal
pure
returns (uint256 m, bool ok)
{
uint256 from = ts > lookback ? ts - lookback : 0;
uint256 horizon = lookback + 3 * width;
uint256 fromMax = ts > horizon ? ts - horizon : 0;
for (uint256 i; i < 3; i++) {
Slot memory s = r.s[i];
if (s.lastBlock == 0) continue;
// the slot after a non-head slot is the next newer bucket (ringWrite's order)
if (s.lastTs < fromMax && (i == r.head || r.s[(i + 1) % 3].start < fromMax)) continue;
if (uint256(s.max) + 1 > m) m = uint256(s.max) + 1;
if (s.lastTs >= from && s.lastBlock < blk) ok = true;
}
if (r.prevBlock != 0 && r.prevBlock < blk && r.prevTs >= fromMax) {
if (uint256(r.prevPrice) + 1 > m) m = uint256(r.prevPrice) + 1;
if (r.prevTs >= from) ok = true;
}
}
/// @notice The newest earlier-block record R (price, ts), the max over R and every non-empty bucket whose last
/// record is at or after R's ts, and whether R's own bucket (a bucket with start <= R.ts <= lastTs) is
/// still in the ring. (0, 0, 0, false) = no earlier-block record.
function plastRecBucket(Ring memory r, uint256 blk)
internal
pure
returns (uint256 p, uint256 t, uint256 bmax, bool inRing)
{
(p, t) = plastRec(r, blk);
if (p == 0) return (0, 0, 0, false);
bmax = p;
for (uint256 i; i < 3; i++) {
Slot memory s = r.s[i];
if (s.lastBlock == 0 || s.lastTs < t) continue;
if (s.max > bmax) bmax = s.max;
if (s.start <= t) inRing = true;
}
}
/// @notice Pd for a SELF-delivered arrival (the executor is the recipient, not a trusted executor or a delivery
/// key; audit r2 G2-01, r3 F4 / F6, r4 R4-2, r5 G5-M1): max(live, horizonMax), so two netted fake low closes
/// at any spacing do not hide the honest open price from the recipient's own delivery (the L gate below
/// keeps the second bucket's start inside the horizon). Three fakes still do: A-SETTERS.md "Pd" has the
/// measured residual. An old spike burns only the first record after a quiet stretch, for L + 3w (F4,
/// narrowed by G5-M1). Needs at least one record from an earlier block within L (ts >= now - L; a
/// non-head bucket only when its last record is from an earlier block, F6): otherwise ok = false (the
/// arrival holds, retriable). Never below pdTrusted at the same moment.
function pdSelf(Ring memory r, uint256 liveUp, uint256 ts, uint256 blk, uint256 lookback, uint256 width)
internal
pure
returns (bool ok, uint256 pd)
{
if (liveUp == 0) return (false, 0);
uint256 m;
(m, ok) = horizonMax(r, ts, blk, lookback, width);
if (!ok) return (false, 0);
pd = liveUp > m ? liveUp : m;
}
// ================================================================ the dynamic margin (LEAD, V4-INTERFACES §3)
/// @notice ceil(sqrt(x)).
function sqrtUp(uint256 x) internal pure returns (uint256 s) {
s = Math.sqrt(x);
if (s * s != x) s += 1;
}
/// @notice The destination pool's QUOTE-side virtual reserve, raw quote units, rounded UP, at the pool price
/// `priceE18` (quote x 1e18 per whole token): liquidity x sqrt(raw price), the same on both currency
/// orders (token currency0: L x sqrtP of currency1; token currency1: L / sqrtP' of currency0, sqrtP' =
/// sqrt(1 / raw price)). 0 (unreadable) when 18 + decQuote - decTok < 0 or decQuote > 36.
/// G-EVMB-2 L-1: e = 18 + decQuote - decTok above 38 (quotes of 30..36 decimals at the coin's 9) is split:
/// j = ceil((e - 38) / 2), sqrt(priceE18 x 10^e) is taken as sqrtUp(priceE18 x 10^(e - 2j)) x 10^j (still
/// rounded up; e <= 54, so j <= 8 and every product stays far below 2^256).
function depthQuoteRaw(uint256 liquidity, uint256 priceE18, uint8 decTok, uint8 decQuote) internal pure returns (uint256) {
if (liquidity == 0 || priceE18 == 0 || priceE18 > PRICE_MAX || decQuote > 36) return 0;
int256 e = 18 + int256(uint256(decQuote)) - int256(uint256(decTok));
if (e < 0) return 0;
uint256 j = e > 38 ? (uint256(e) - 37) / 2 : 0;
// x = raw price x 1e36 / 10^(2j) = priceE18 x 10^(e - 2j), e - 2j <= 38; x < 2^128 x 10^38 < 2^255
uint256 x = priceE18 * 10 ** (uint256(e) - 2 * j);
return Math.mulDiv(liquidity, sqrtUp(x) * 10 ** j, E18, Math.Rounding.Ceil);
}
/// @notice USD x 1e18 of `rawQuote` quote units at `usdPerQuoteUpE18` (rounded up): ceil(raw x usd / 10^dec).
function depthUsdE18(uint256 rawQuote, uint256 usdPerQuoteUpE18, uint8 decQuote) internal pure returns (uint256) {
if (rawQuote == 0 || usdPerQuoteUpE18 == 0 || decQuote > 36) return 0;
return Math.mulDiv(rawQuote, usdPerQuoteUpE18, 10 ** uint256(decQuote), Math.Rounding.Ceil);
}
/// @notice m (ppm) at a locked-LP quote depth (LEAD UPDATE 2): curve(marginK, marginMinPpm, marginMaxPpm, depth).
/// A fixed per-coin m is marginK 0 with min = max = m.
function margin(uint64 marginK, uint32 mMin, uint32 mMax, uint256 depthUsd) internal pure returns (uint32) {
return curve(marginK, mMin, mMax, depthUsd);
}
// ================================================================ the cost cover (spec §9)
/// @notice The counted basefee: clamp(basefee, floor, cap); cap 0 -> 0 (no gas cover); floor > cap -> the cap.
function effBaseFee(uint256 basefee, IGapRegistryV4.CoverV4 memory c) internal pure returns (uint256) {
uint256 cap = c.baseFeeCapWei;
if (cap == 0) return 0;
uint256 fl = c.baseFeeFloorWei > cap ? cap : c.baseFeeFloorWei;
if (basefee < fl) return fl;
return basefee > cap ? cap : basefee;
}
/// @notice The native price the cover counts: the read clamped to the band [min, max]; 0 (no cover) when the
/// read is 0 or max is 0; min > max -> max.
function nativeUsd(uint256 read, IGapRegistryV4.CoverV4 memory c) internal pure returns (uint256) {
uint256 hi = c.nativeUsdMaxE18;
if (read == 0 || hi == 0) return 0;
uint256 lo = c.nativeUsdMinE18 > hi ? hi : c.nativeUsdMinE18;
if (read < lo) return lo;
return read > hi ? hi : read;
}
/// @notice The source cover carried in the message, micro-USD, rounded down (spec §9 SOURCE):
/// min(cap, floor((lzFeeWei + buyAndSendUnits x (effBaseFee + tip)) x nativeUsd / 1e18)) / 1e12, with
/// the gas term 0 when the basefee cap is 0; at most type(uint32).max micro-USD (the codec field).
/// 0 when the native price is unreadable or the band max is 0.
function coverSrcMicroUsd(uint256 lzFeeWei, IGapRegistryV4.CoverV4 memory c, uint256 basefee, uint256 nativeRead)
internal
pure
returns (uint32)
{
uint256 n = nativeUsd(nativeRead, c);
if (n == 0 || c.coverCapUsdE18 == 0) return 0;
uint256 b = effBaseFee(basefee, c);
uint256 gasWei = b == 0 ? 0 : uint256(c.buyAndSendUnits) * (b + c.tipAllowanceWei);
uint256 cap = c.coverCapUsdE18;
if (lzFeeWei > PRICE_MAX) lzFeeWei = PRICE_MAX; // gasWei < 2^97: the sum fits
uint256 usd = Math.mulDiv(lzFeeWei + gasWei, n, E18);
if (usd > cap) usd = cap;
uint256 micro = usd / MICRO_USD_E18;
return micro > type(uint32).max ? type(uint32).max : uint32(micro);
}
/// @notice The destination cover, USD x 1e18, rounded down (spec §9 DESTINATION):
/// min(cap, floor(swapUnits x (effBaseFee + tip) x nativeUsd / 1e18)); 0 when unreadable.
function coverDstUsdE18(IGapRegistryV4.CoverV4 memory c, uint256 basefee, uint256 nativeRead) internal pure returns (uint256) {
uint256 n = nativeUsd(nativeRead, c);
uint256 b = effBaseFee(basefee, c);
if (n == 0 || b == 0 || c.coverCapUsdE18 == 0) return 0;
uint256 usd = Math.mulDiv(uint256(c.swapUnits) * (b + c.tipAllowanceWei), n, E18);
return usd > c.coverCapUsdE18 ? c.coverCapUsdE18 : usd;
}
/// @notice Audit r4 R4-3: the destination sale allowance bounded by the arrival's value: min(coverDst,
/// floor(A x psUsd / 10^dec x maxPpm / 1e6)), USD x 1e18, with A the amount (local decimals `dec`) and
/// psUsd the source USD price the message carries (what was paid; not manipulable here). Splitting one
/// round into N arrivals then gains at most maxPpm of its value in destination cover. maxPpm 0 = no
/// destination cover.
function coverDstBounded(uint256 coverDstUsd, uint256 amountLD, uint256 psUsdE18, uint256 maxPpm, uint8 dec)
internal
pure
returns (uint256)
{
if (coverDstUsd == 0 || maxPpm == 0 || dec > 36) return 0;
uint256 bound = Math.mulDiv(Math.mulDiv(amountLD, psUsdE18, 10 ** uint256(dec)), maxPpm, PPM);
return coverDstUsd < bound ? coverDstUsd : bound;
}
/// @notice C_usd = min(destination cap, coverSrc + coverDst), USD x 1e18. (The source already capped its part
/// at its own cap, so the sum is at most min(both caps) + the destination's part, then capped again.)
function coverUsdE18(uint32 coverSrcMicro, uint256 coverDstUsd, uint256 capDstUsd) internal pure returns (uint256 c) {
c = uint256(coverSrcMicro) * MICRO_USD_E18 + coverDstUsd;
if (c > capDstUsd) c = capDstUsd;
}
/// @notice C in the pricing unit: the USD amount itself for the USD pair; for a class pair
/// floor(C_usd x 1e18 / classUsdE18), 0 when the class's USD price is unreadable.
function coverInUnit(uint256 coverUsd, bool isClass, uint256 classUsdE18) internal pure returns (uint256) {
if (!isClass) return coverUsd;
if (classUsdE18 == 0 || classUsdE18 > PRICE_MAX) return 0;
return Math.mulDiv(coverUsd, E18, classUsdE18);
}
// ================================================================ the credit (spec §6, §9)
/// @notice G = floor(A x 1e6 / (1e6 - b)), b < 1e6 (the codec refuses more).
function gross(uint256 amountLD, uint256 bPpm) internal pure returns (uint256) {
return Math.mulDiv(amountLD, PPM, PPM - bPpm);
}
/// @notice Plain (spec §6): credited = min(A, floor(A x Ps / Pd)). Pd 0 is the caller's hold (returns 0).
function creditPlain(uint256 amountLD, uint256 ps, uint256 pd) internal pure returns (uint256) {
if (pd == 0) return 0;
if (ps >= pd) return amountLD;
return Math.mulDiv(amountLD, ps, pd); // < A
}
/// @notice Buy-and-bridge (spec §9): with G = gross(A, b),
/// V = floor(G x Ps x (1e6 + m) / (1e6 x 10^decDst)) value of G in [unit x 1e18]
/// credited = min(A, floor((V + C) x 10^decDst x 1e6 / (Pd x (1e6 - fD))))
/// G is counted in the destination's raw units (it is derived from the shared-decimal amount, so it is
/// the same token amount as the source's G; the spec's /10^decSrc x 10^decDst is that conversion).
/// Pd 0 or fD >= 1e6 is the caller's hold (returns 0). Never overflows (the A check comes first).
function creditBuy(
uint256 amountLD,
uint256 bPpm,
uint256 ps,
uint256 mPpm,
uint256 coverUnitE18,
uint256 pd,
uint256 fDPpm,
uint8 decDst
) internal pure returns (uint256) {
if (pd == 0 || pd > PRICE_MAX || fDPpm >= PPM || decDst > 36) return 0;
uint256 g = gross(amountLD, bPpm);
uint256 scale = 10 ** uint256(decDst);
uint256 v = Math.mulDiv(g, ps * (PPM + mPpm), PPM * scale) + coverUnitE18;
uint256 den = pd * (PPM - fDPpm); // < 2^148
uint256 num = scale * PPM; // <= 1e42 < 2^140
// credited >= A <=> v x num >= A x den <=> v >= ceil(A x den / num)
if (v >= Math.mulDiv(amountLD, den, num, Math.Rounding.Ceil)) return amountLD;
return Math.mulDiv(v, num, den); // < A
}
function _min32(uint32 a, uint32 b) private pure returns (uint32) {
return a < b ? a : b;
}
}
src/v4/gap/GapRecorderV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {GapMathV4} from "./GapMathV4.sol";
import {GapPriceLib} from "../../v3/gap/GapPriceLib.sol";
import {IGapRegistryV4} from "./IGapRegistryV4.sol";
import {PangeaOFTV4Storage as S} from "./PangeaOFTV4Storage.sol";
/// @title GapRecorderV4 -- the token's own price recorder (spec §4a, owner D1: no new hook)
/// @notice Shared by PangeaOFTV4 (its `_update` writes a record whenever a non-zero amount of the token moves to
/// or from the PoolManager, and every send / receive writes one) and PangeaOFTV4GapModule (reads Plast,
/// Pref, Pd_ref). The ring's arithmetic is GapMathV4.ringWrite / plast / pref; this library packs it into
/// the token's storage and writes only the words a record changes (one bucket and the meta word).
/// `record` here and GapMathV4.ringWrite are the same function (fuzzed against each other).
///
/// v4 settle ordering: a v4 swap moves the price in `swap`, BEFORE the ERC-20 moves in settle / take, so a
/// record always holds the price AFTER the swap that caused it, and a record of the current block can
/// already be pumped. GapMathV4.plast / pref therefore never let a current-block record raise anything.
/// @dev The official pool's state is read from the PoolManager by extsload (StateLibrary's layout): pools slot 6,
/// slot0 at the pool's base slot, liquidity at + 3.
library GapRecorderV4 {
uint256 internal constant POOLS_SLOT = 6;
uint256 internal constant LIQUIDITY_OFFSET = 3;
uint256 internal constant POSITIONS_OFFSET = 6;
bytes4 internal constant EXTSLOAD = 0x1e2eaeaf;
/// @dev The bucket width before any send or receive has set it: L's default / 2.
uint256 internal constant WIDTH_DEFAULT = GapMathV4.LOOKBACK_DEFAULT_SEC / 2;
/// @dev Gas caps of the one-time pool read (registry) and of the quote's decimals().
uint256 internal constant LEARN_GAS = 60_000;
uint256 internal constant DECIMALS_GAS = 30_000;
uint8 internal constant TOKEN_DECIMALS = 9;
/// @dev v4's dynamic-fee flag (LPFeeLibrary.DYNAMIC_FEE_FLAG).
uint24 internal constant DYNAMIC_FEE_FLAG = 0x800000;
uint256 private constant M32 = (1 << 32) - 1;
uint256 private constant M40 = (1 << 40) - 1;
uint256 private constant M48 = (1 << 48) - 1;
uint256 private constant M128 = (1 << 128) - 1;
// ------------------------------------------------------------------ the official pool
/// @notice Caches the official pool from the registry once (never again: set-once in the registry, no
/// re-point in v4). Refuses (returns false, caches nothing) a pool whose key does not hash to its
/// id, a dynamic or out-of-range LP fee, a currency order that cannot be, or an unreadable quote
/// decimals. Gas-capped (LEARN_GAS), any failure is "not known".
/// G-EVMB-2 L-3 (negative cache): a pool that is SET but can never be used is marked `unusable` and never
/// looked up again (no repeated registry read + decimals() on every swap). Only a definite answer is
/// cached: a failed or malformed registry read, an unset pool, or a decimals() call that did not get its
/// full DECIMALS_GAS (the caller's gas, 63/64 rule) caches nothing.
function learn(S.Layout storage l, address reg) internal returns (bool) {
if (l.known) return true;
if (l.unusable) return false;
(bool ok, bytes memory ret) = reg.staticcall{gas: LEARN_GAS}(abi.encodeCall(IGapRegistryV4.officialPool, (address(this))));
if (!ok || ret.length != 256) return false;
(bool set, IGapRegistryV4.OfficialPool memory o) = abi.decode(ret, (bool, IGapRegistryV4.OfficialPool));
if (!set) return false;
if (o.poolId == bytes32(0) || o.poolId != poolIdOf(o) || o.lpFee >= DYNAMIC_FEE_FLAG || o.lpFee > GapMathV4.PPM) {
l.unusable = true;
return false;
}
bool fullGas = gasleft() > DECIMALS_GAS + DECIMALS_GAS / 63 + 1_000;
(bool okDec, uint8 dec) = quoteDecimalsOf(o.quote);
if (!okDec) {
if (fullGas) l.unusable = true;
return false;
}
(l.known, l.tokenIs0, l.quoteDecimals, l.lpFee, l.tickSpacing) = (true, o.tokenIsCurrency0, dec, o.lpFee, o.tickSpacing);
(l.poolQuote, l.poolHook, l.poolId, l.lockedPositionKey) = (o.quote, o.hook, o.poolId, o.lockedPositionKey);
return true;
}
/// @notice keccak256(abi.encode(PoolKey)) of the key the pool names (this token and `quote` in currency
/// order, fee lpFee, its tick spacing and hook); 0 when the order is impossible.
function poolIdOf(IGapRegistryV4.OfficialPool memory o) internal view returns (bytes32) {
address t = address(this);
if (o.tokenIsCurrency0 ? !(t < o.quote) : !(o.quote < t)) return bytes32(0);
(address c0, address c1) = o.tokenIsCurrency0 ? (t, o.quote) : (o.quote, t);
return keccak256(abi.encode(c0, c1, uint24(o.lpFee), int24(o.tickSpacing), o.hook));
}
function quoteDecimalsOf(address quote) internal view returns (bool ok, uint8 d) {
if (quote == address(0)) return (true, 18);
uint256 w;
uint256 size;
assembly ("memory-safe") {
mstore(0, 0x313ce56700000000000000000000000000000000000000000000000000000000) // decimals()
ok := staticcall(DECIMALS_GAS, quote, 0, 4, 0, 32)
size := returndatasize()
if and(ok, eq(size, 32)) { w := mload(0) }
}
if (!ok || size != 32 || w > 36) return (false, 0);
return (true, uint8(w));
}
// ------------------------------------------------------------------ PoolManager reads
function _extsload(address pm, bytes32 slot) private view returns (bool ok, uint256 w) {
bytes4 sel = EXTSLOAD;
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, sel)
mstore(add(m, 4), slot)
ok := staticcall(gas(), pm, m, 36, 0, 32)
ok := and(ok, eq(returndatasize(), 32))
if ok { w := mload(0) }
}
}
/// @notice slot0's sqrtPriceX96 of pool `id` (0 on failure).
function liveSqrt(address pm, bytes32 id) internal view returns (uint160) {
(, uint256 w) = _extsload(pm, keccak256(abi.encodePacked(id, POOLS_SLOT)));
return uint160(w);
}
/// @notice The pool's in-range liquidity (0 on failure).
function liquidity(address pm, bytes32 id) internal view returns (uint128) {
(, uint256 w) = _extsload(pm, bytes32(uint256(keccak256(abi.encodePacked(id, POOLS_SLOT))) + LIQUIDITY_OFFSET));
return uint128(w);
}
/// @notice The liquidity of position `key` in pool `id` (StateLibrary.getPositionLiquidity; 0 on failure).
function positionLiquidity(address pm, bytes32 id, bytes32 key) internal view returns (uint128) {
if (key == bytes32(0)) return 0;
bytes32 base = bytes32(uint256(keccak256(abi.encodePacked(id, POOLS_SLOT))) + POSITIONS_OFFSET);
(, uint256 w) = _extsload(pm, keccak256(abi.encodePacked(key, base)));
return uint128(w);
}
/// @notice The official pool's live price, quote x 1e18 per whole token, rounded `up` or down; 0 unknown.
function livePrice(S.Layout storage l, address pm, bool up) internal view returns (uint256) {
if (!l.known) return 0;
return GapPriceLib.fromSqrtX96(liveSqrt(pm, l.poolId), l.tokenIs0, TOKEN_DECIMALS, l.quoteDecimals, up);
}
// ------------------------------------------------------------------ the ring
/// @notice A record of the official pool's live price (rounded down), now. Nothing when the pool is not
/// known (and cannot be learned) or the price is unknown.
/// `blk` is the block in the rules' numbering (GapBlockV4: the L2 block on Arbitrum-stack chains).
function recordLive(S.Layout storage l, address pm, address reg, uint256 blk) internal {
if (!l.known && !learn(l, reg)) return;
uint256 p = livePrice(l, pm, false);
if (p != 0) record(l, p, block.timestamp, blk);
}
/// @notice GapMathV4.ringWrite on the packed storage (same rules; fuzzed against it).
function record(S.Layout storage l, uint256 p, uint256 ts, uint256 blk) internal {
if (p == 0) return;
if (p > GapMathV4.PRICE_MAX) p = GapMathV4.PRICE_MAX;
uint256 meta = l.ringMeta;
uint256 head = meta & 0xff;
uint256 width = (meta >> 8) & M32;
if (width == 0) width = WIDTH_DEFAULT;
uint256 b = l.ring[2 * head + 1];
uint256 lastBlock = (b >> 80) & M48;
uint256 start = ts - ts % width;
if (lastBlock == 0) {
l.ring[2 * head] = p | (p << 128);
l.ring[2 * head + 1] = _b(start, ts, blk, p);
return;
}
uint256 lastPrice = b >> 128;
uint256 newMeta = meta;
// prev = the head's latest (block, price, ts) when this record opens a new block
if (blk != lastBlock) {
newMeta = (newMeta & ((1 << 40) - 1)) | (lastBlock << 40) | (lastPrice << 88) | (((b >> 40) & M40) << 216);
}
uint256 hStart = b & M40;
if (start <= hStart) {
uint256 a = l.ring[2 * head];
uint256 mn = a & M128;
uint256 mx = a >> 128;
if (p < mn) mn = p;
if (p > mx) mx = p;
uint256 na = mn | (mx << 128);
if (na != a) l.ring[2 * head] = na;
l.ring[2 * head + 1] = _b(hStart, ts, blk, p);
} else {
uint256 n = (head + 1) % 3;
(uint256 mn, uint256 mx) = lastPrice < p ? (lastPrice, p) : (p, lastPrice);
l.ring[2 * n] = mn | (mx << 128);
l.ring[2 * n + 1] = _b(start, ts, blk, p);
newMeta = (newMeta & ~uint256(0xff)) | n;
}
if (newMeta != meta) l.ringMeta = newMeta;
}
/// @notice Sets the bucket width to max(1, L / 2) (a send or receive, which read L). An L change takes full
/// effect within one L (GapMathV4 ring notes).
function setWidth(S.Layout storage l, uint256 lookback) internal {
uint256 w = lookback / 2;
if (w == 0) w = 1;
uint256 meta = l.ringMeta;
if ((meta >> 8) & M32 != w) l.ringMeta = (meta & ~(M32 << 8)) | (w << 8);
}
function _b(uint256 start, uint256 ts, uint256 blk, uint256 p) private pure returns (uint256) {
return (start & M40) | ((ts & M40) << 40) | ((blk & M48) << 80) | (p << 128);
}
/// @notice The ring, unpacked (for GapMathV4.plast / pref and the views).
function load(S.Layout storage l) internal view returns (GapMathV4.Ring memory r) {
uint256 meta = l.ringMeta;
r.head = uint8(meta);
r.prevBlock = uint48(meta >> 40);
r.prevPrice = uint128(meta >> 88);
r.prevTs = uint40(meta >> 216);
for (uint256 i; i < 3; i++) {
uint256 a = l.ring[2 * i];
uint256 b = l.ring[2 * i + 1];
r.s[i] = GapMathV4.Slot(uint40(b), uint40(b >> 40), uint48(b >> 80), uint128(a), uint128(a >> 128), uint128(b >> 128));
}
}
/// @notice The current bucket width (seconds).
function bucketWidth(S.Layout storage l) internal view returns (uint256 w) {
w = (l.ringMeta >> 8) & M32;
if (w == 0) w = WIDTH_DEFAULT;
}
}
src/v4/gap/IGapRegistryV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title IGapRegistryV4 -- per-chain gap settings for PangeaOFTV4 tokens (Gap v4 spec §15, V4-INTERFACES §4, §8)
/// @notice Stream A owns this file; stream B implements it (src/v4/registry/GapRegistryV4.sol).
/// It is IPangeaGapRegistry (v3) MINUS the price log, its capacity and windows, the writer reward,
/// the co-sign, the oversized land and the cover window; PLUS the v4 settings. Readers, hop gas caps,
/// trusted executors and the two delivery keys are unchanged from v3.
///
/// ANYPAIRS (owner 2026-11-06, lead ruling in RESUME-2026-11-06.md): ANY pool on ANY chain. There is NO
/// listing of a pair token: no stables list, no admin quote classes, no registrar, no admin routes. The admin
/// keeps PARAMETERS only: the USD anchors (the tokens a path may end in, taken as exactly $1), the chain's
/// native class, and the venues (per reader: the DEX code whose pools it may read, by CREATE2). A coin's
/// quote USD path is passed IN ITS LAUNCH (setOfficialPool) and stored PER COIN; the registry checks only that
/// it READS (pools at a venue's CREATE2 address, listed readers, ends in an anchor, both roundings non-zero).
/// Anchor quotes and native-class quotes (native, wrapped native) need no path (the chain's native path, set
/// by anyone while none reads, prices the native coin). A stored path that stops reading may be replaced by
/// ANYONE with one that reads; one that still reads cannot be touched by anyone. Class is derived: an anchor
/// 1, native / wrapped native the chain's `nativeClass`, any other quote 0 (priced through USD).
/// The token's ABI here is UNCHANGED: `quoteClass`, `usdPerQuoteE18`, `usdPerQuoteBothNativeE18` answer for
/// the CALLER's own path (msg.sender is the token, also through its module and views), so the module needs
/// no new code.
///
/// LEAD UPDATE 2 (owner 2026-11-05): NO COMPILED BOUNDS. Every v4 parameter is admin-set per chain PLUS a
/// per-coin override (B's storage and setters; every setter emits an event, no timelock; listed in
/// B-SETTERS.md). The TOKEN reads ONE resolved struct, `paramsOf(token)` (the chain values with the coin's
/// overrides applied), and keeps only arithmetic safety: a nonsensical pair resolves deterministically
/// (min > max: max wins), nothing overflows or divides by zero. HARD INVARIANTS stay in the token's code
/// whatever the registry says: credited <= A on every arrival (the rest is never minted); no admin path mints,
/// moves or seizes users' tokens or pool liquidity; a pause stops only NEW sends (arrivals always land or
/// hold retriably, the refund marker always lands); supply and balances are untouchable.
///
/// A token reads its official pool ONCE (the first send, receive or pool transfer after it is set) and
/// caches it for life: setOfficialPool is set-once per token and there is no re-point in v4.
/// FACTORY ORDER (stream B): setOfficialPool(token, pool) BEFORE the launch liquidity is added, so the
/// launch LP add (a token transfer into the PoolManager) writes the token's first price record; a
/// buy-and-bridge or plain send needs a record from an earlier block (GapNeedRecord otherwise).
interface IGapRegistryV4 {
// ------------------------------------------------------------------ types
/// @notice One conversion step (v3 unchanged): the price of one whole `tokenIn` in `tokenOut`, read by
/// `reader.priceE18(poolRef, tokenIn, tokenOut)` under `staticcall{gas: gasCap}`.
struct Hop {
address reader;
bytes32 poolRef;
address tokenIn;
address tokenOut;
uint32 gasCap;
}
/// @notice ANYPAIRS: what a listed reader may read, an admin PARAMETER (venue code, never a token choice).
/// `kind` 1: a Uniswap-v3-style pool, address = CREATE2(deployer, keccak256(abi.encode(token0, token1,
/// fee)), initCodeHash) with fee = pool.fee(); 2: a Uniswap-v2-style pair, salt keccak256(abi.encodePacked
/// (token0, token1)); 0: none (the reader prices no path). `deployer` is the address that CREATE2s the pools
/// (the factory for Uniswap; PancakeSwap v3's PoolDeployer). `gasCap`: the hop gas cap every stored hop of
/// this reader gets (the caller's is ignored), in [1, 100,000].
struct Venue {
address deployer;
bytes32 initCodeHash;
uint8 kind;
uint32 gasCap;
}
/// @notice A token's official launch pool (Uniswap v4). Set once, by a listed factory. v4 adds `tickSpacing`
/// (the token rebuilds the exact PoolKey -- currency order from the token and `quote`, fee = `lpFee`,
/// hooks = `hook` -- and checks keccak256(PoolKey) == `poolId` before it ever swaps on it) and
/// `lockedPositionKey`: the v4 position key (Position.calculatePositionKey(owner, tickLower, tickUpper,
/// salt)) of the PERMANENTLY LOCKED launch liquidity, whose liquidity the margin and the k curve read
/// (LEAD UPDATE 2: depth = locked-LP quote depth). It may hold no liquidity yet when set (the factory
/// names the pool before seeding it); a depth of 0 holds a receive and refuses a buy.
struct OfficialPool {
bytes32 poolId; // the v4 PoolId
address hook; // its fee hook; the fee is read as `hookKind(hook)` says
address quote; // the pool's other currency; address(0) is native
uint24 lpFee; // the v4 static LP fee, ppm (the dynamic-fee flag 0x800000 is refused by the token)
bool tokenIsCurrency0;
int24 tickSpacing;
bytes32 lockedPositionKey;
}
/// @notice How the official pool's hook fee is read (v3 unchanged). NONE: unreadable (the token
/// refuses the pool's price: send reverts, receive holds).
enum HookKind {
NONE,
V1, // PangeaFeeHook: configs(id).feeBps
V2 // PangeaFeeHookV2: feeOf(id), live
}
/// @notice The cost cover figures (spec §9). No compiled bounds; the token's arithmetic rules:
/// baseFeeCapWei 0 = no gas cover; baseFeeFloorWei > baseFeeCapWei -> the cap wins;
/// nativeUsdMaxE18 0 = no cover at all; nativeUsdMinE18 > nativeUsdMaxE18 -> the max wins;
/// coverCapUsdE18 0 = no cover. Units are the MEASURED MINIMUM receipt gasUsed. The source uses
/// buyAndSendUnits, the destination swapUnits; one message's cover is at most the destination's cap
/// (the source already capped its own part at its cap).
struct CoverV4 {
uint32 buyAndSendUnits;
uint32 swapUnits;
uint64 baseFeeFloorWei;
uint64 baseFeeCapWei;
uint64 tipAllowanceWei;
uint128 nativeUsdMinE18;
uint128 nativeUsdMaxE18;
uint128 coverCapUsdE18;
/// @dev Audit r4 R4-3: the destination sale allowance is at most this share (ppm) of the arrival's value at the
/// source USD price (A x psUsd). Per chain (setCover), per coin with O_COVER. 0 = no destination cover.
uint32 coverDstMaxValuePpm;
}
/// @notice What a token reads on its send / receive path, in ONE call: the chain values with `token`'s
/// overrides already applied (LEAD UPDATE 2). Defaults in brackets.
/// margin (destination): m = clamp(marginMinPpm, marginMaxPpm, floor(marginK x 1e9 / isqrtUp(depthUsdE18)))
/// with depth the destination's locked-LP quote depth at Pd_ref; marginK = K x 1e6 [K 1 -> 1e6];
/// marginK 0 -> marginMinPpm; [1,000 / 100,000]. A fixed per-coin m is marginK 0 and min = max = m.
/// k (source backstop): when execCapOn [true], k = max(m_src, clamp(execCapMinPpm, execCapMaxPpm,
/// floor(execCapK x 1e9 / isqrtUp(srcDepthUsdE18)))), srcDepth the source's locked-LP quote depth at
/// Plast, m_src this chain's margin curve at srcDepth; Ps = min(Pexec, Plast x (1 + k)). Off: Ps = Pexec.
/// [Kk 2 -> 2e6; 15,000 / 200,000]. A fixed per-coin k is execCapK 0 and min = max = k.
/// lookbackSec L [30]; feeCapPpm [10,000] caps the counted hook fee (Pexec) and fD; minLiquidity [0]
/// the least in-range liquidity of a pool whose price is read; bridgeFeeBps [20] (> 10,000 refused by
/// the token's arithmetic); lockOn [true] the same-transaction sell lock after a buyAndSend;
/// burnOn [true]: the gap rule withholds (and so burns) the part above the formula; false (LEAD UPDATE 3
/// §9.1) credits every arrival IN FULL (credited = A), like an escape. There is no withheld sink.
struct ParamsV4 {
uint64 marginK;
uint32 marginMinPpm;
uint32 marginMaxPpm;
bool execCapOn;
uint64 execCapK;
uint32 execCapMinPpm;
uint32 execCapMaxPpm;
uint32 lookbackSec;
uint32 feeCapPpm;
uint128 minLiquidity;
uint16 bridgeFeeBps;
bool lockOn;
bool burnOn;
CoverV4 cover;
}
// ------------------------------------------------------------------ events
event ReaderSet(address indexed reader, bool allowed);
event GapEscapeSet(address indexed token, bool on);
event V2RecordMaxAgeSet(uint32 seconds_);
event HookKindSet(address indexed hook, HookKind kind);
event FactorySet(address indexed factory, bool listed);
// ---- ANYPAIRS
event UsdAnchorSet(address indexed token, bool anchor);
event NativeClassSet(uint8 class_);
event VenueSet(address indexed reader, Venue venue);
/// @notice The chain's native path was set (`by`: whoever sent it; first, or replacing one that no longer read).
/// The hops as stored: `nativePath()` (not in the event: the registry's EIP-170 room).
event NativePathSet(address indexed by);
/// @notice `token`'s quote path was stored: at its launch (`by` = its factory) or as a replacement of a path that
/// no longer read (`by` = anyone). The hops as stored: `coinPath(token)`.
event CoinPathSet(address indexed token, address indexed by);
event OfficialPoolSet(address indexed token, address indexed factory, OfficialPool pool);
event GapExecutorSet(address indexed executor, bool trusted);
event DeliveryKeySet(uint8 indexed slot, address indexed key);
event BridgeFeeSet(uint16 bps);
// ---- v4: B defines the setter events (one per setter, B-SETTERS.md)
event SendPausedSet(address indexed token, uint32 indexed dstEid, bool paused);
// ------------------------------------------------------------------ errors (setters)
error NotOwner();
error NotListedFactory();
error PoolAlreadySet(address token);
error HookNotListed(address hook);
/// @notice The quote path does not read (a launch leg is refused; a replacement is refused).
error QuoteNotPricable(address quote);
/// @notice Native, the 0xEeee placeholder and the wrapped native are never USD anchors.
error NotAnAnchor(address token);
/// @notice nativeClass 1 (USD) and 255 (the refund marker) are refused.
error BadNativeClass(uint8 class_);
/// @notice A venue with kind > 2, a zero deployer / hash for kind != 0, or a gas cap outside [1, 100,000].
error BadVenue(address reader);
/// @notice A path refused: 1 shape (0 or more than 2 hops, not starting at the quote, hops not chained),
/// 2 does not end in a USD anchor, 3 a hop's reader is unlisted or has no venue, 4 a hop's pool is not
/// its venue's CREATE2 pool of exactly the hop's two tokens, 5 a path given for a quote that needs none.
error BadPath(uint8 why);
/// @notice A replacement of a path that still reads (nobody may touch a path that reads).
error PathStillReads();
/// @notice The quote's decimals are unreadable or above 36 (the math bound).
error BadQuoteDecimals(address quote);
error BadV2RecordMaxAge(uint32 seconds_);
error BridgeFeeTooHigh(uint16 bps);
error LzExecutorHelperRefused(address helper);
/// @notice A reader's gas cap cannot be met (v3 rule): gasleft() >= gasCap * 64 / 63 + 5,000 before
/// each hop. The token passes it on (retriable), never prices on a starved read.
error GapGasTooLow(uint256 needed, uint256 left);
// ------------------------------------------------------------------ owner setters
function owner() external view returns (address);
/// @notice A listed reader is the owner's statement that it is FLASH-PROOF (v3: UniV3Reader at the previous
/// block's close, V2PairReader only for a pair untouched this block). No v4-pool hop readers (D1).
function setReader(address reader, bool allowed) external;
/// @notice ANYPAIRS parameters (owner): the USD anchors, the native class, each reader's venue.
function setUsdAnchor(address token, bool anchor) external;
function setNativeClass(uint8 class_) external;
function setVenue(address reader, Venue calldata venue) external;
function setGapEscape(address token, bool on) external;
function setV2RecordMaxAge(uint32 seconds_) external;
function setHookKind(address hook, HookKind kind) external;
function setFactory(address factory, bool listed) external;
function setGapExecutor(address executor, bool trusted) external;
function setDeliveryKey(uint8 slot, address key) external;
/// @notice The v4 settings' setters are B's (chain values and per-coin overrides of every ParamsV4 field,
/// the chain-wide and per-coin send pause, events, no timelock): see B-SETTERS.md. Only the views the
/// token reads are part of this interface.
// ------------------------------------------------------------------ paths (ANYPAIRS: anyone)
/// @notice The chain's native USD path (1 or 2 hops from address(0) to an anchor). Anyone, while no native
/// path is stored or the stored one does not read; it must read.
function setNativePath(Hop[] calldata hops) external;
/// @notice Replace `token`'s stored quote path with `hops`. Anyone, only while the stored one does NOT read;
/// the new one must read (the checks of setOfficialPool).
function replaceCoinPath(address token, Hop[] calldata hops) external;
// ------------------------------------------------------------------ listed factory
/// @notice Once per token, from a listed factory, BEFORE the launch liquidity is added (see above).
/// Refused unless the hook is listed (hookKind != NONE), the quote's decimals read and are <= 36,
/// lpFee is static (< 0x800000), lockedPositionKey != 0 and poolId == keccak256(abi.encode(PoolKey))
/// for the key built from (token, quote, lpFee, tickSpacing, hook). ANYPAIRS: `path` is the quote's USD
/// path, stored for this token: empty for an anchor or native-class quote (BadPath(5) otherwise),
/// else it must READ (QuoteNotPricable: that leg is refused).
function setOfficialPool(address token, OfficialPool calldata pool, Hop[] calldata path) external;
// ------------------------------------------------------------------ views read by the token
function poolManager() external view returns (address);
function wrappedNative() external view returns (address);
function isReader(address reader) external view returns (bool);
function isUsdAnchor(address token) external view returns (bool);
function nativeClass() external view returns (uint8);
function isFactory(address factory) external view returns (bool);
/// @notice Derived (ANYPAIRS): an anchor 1; native or the wrapped native `nativeClass`; else 0.
function quoteClass(address quote) external view returns (uint8);
function gapEscape(address token) external view returns (bool);
function v2RecordMaxAge() external view returns (uint32);
function hookKind(address hook) external view returns (HookKind);
function venueOf(address reader) external view returns (Venue memory);
function nativePath() external view returns (Hop[] memory);
function coinPath(address token) external view returns (Hop[] memory);
/// @notice Whether `quote` needs a path (it is not an anchor and not native-class).
function needsPath(address quote) external view returns (bool);
/// @notice `set == false`: no official pool on this chain yet.
function officialPool(address token) external view returns (bool set, OfficialPool memory pool);
function hasOfficialPool(address token) external view returns (bool);
/// @notice The official pool's live fee, ppm: hook fee (V1 configs(id).feeBps x 100, V2 feeOf(id)) + the
/// static lpFee. ok false on no pool, HookKind NONE or a failed hook read. The token caps it at
/// feeCapPpm.
function poolFeePpm(address token) external view returns (bool ok, uint32 ppm);
/// @notice USD per whole `quote`, 1e18 (an anchor is 1e18), through the CALLER's stored path (the native path for
/// address(0) and the wrapped native); the path chained rounding UP when `roundUp`, DOWN otherwise; 0 on any
/// failure (a caller with no path for `quote` reads 0). Reverts only with GapGasTooLow.
function usdPerQuoteE18(address quote, bool roundUp) external view returns (uint256);
/// @notice Both roundings from one read of each hop (the caller's path, as above; v3's usdPerQuoteBothE18 is gone:
/// no v4 token reads it, and off chain `coinUsdE18` answers per coin) and, when the same reads give it, the native path rounded down
/// (else 0: the token reads usdPerQuoteE18(address(0), false) itself).
function usdPerQuoteBothNativeE18(address quote) external view returns (uint256 down, uint256 up, uint256 nativeDown);
/// @notice For anyone (web, arb): `token`'s quote in USD through its stored path, both roundings (0, 0 = unreadable).
function coinUsdE18(address token) external view returns (uint256 down, uint256 up);
/// @notice For anyone (the launch form): 0 when `hops` would be stored for `quote` and reads now; else the
/// BadPath reason (1..5), 6 when it validates but does not read.
function checkPath(address quote, Hop[] calldata hops) external view returns (uint8 why);
/// @notice Whether `executor` (the caller of EndpointV2.lzReceive) may land a v4 receive: a listed LayerZero
/// executor (setGapExecutor) or one of the two delivery keys. address(0) never. v4: EVERY receive
/// but the refund marker requires it (spec §8 rule 3).
function isTrustedExecutor(address executor) external view returns (bool);
function gapExecutor(address executor) external view returns (bool);
function deliveryKeys(uint256 slot) external view returns (address);
function isDeliveryKey(address key) external view returns (bool);
function deliveryKeysSet() external view returns (bool);
function isLzExecutorHelper(address a) external pure returns (bool);
/// @notice The chain's bridge fee bps (default 20). LEAD UPDATE 3 §9.4: the token charges the RESOLVED
/// paramsOf(token).bridgeFeeBps (coin override applied); the registry refuses >= 10,000.
function bridgeFeeBps() external view returns (uint16);
/// @notice Sends of `token` toward `dstEid` refused (GapSendPaused) while the chain-wide or the coin's pause is
/// on (B resolves both); arrivals always land.
function sendPaused(address token, uint32 dstEid) external view returns (bool);
/// @notice The resolved settings of `token` (see ParamsV4). This is what the token calls.
function paramsOf(address token) external view returns (ParamsV4 memory);
// ------------------------------------------------------------------ keys-only delivery and the Solana prepay (v3 unchanged)
/// @notice v3 IGapDelivery: our delivery cost toward a keys-only destination, this chain's native wei (0 = LayerZero delivers).
function deliveryCost(uint32 dstEid) external view returns (uint256);
/// @notice v3 IGapDelivery: (cost, recipient); a non-zero cost needs a recipient.
function deliveryCharge(uint32 dstEid) external view returns (uint256 costWei, address to);
/// @notice v3 IGapPrepay: the L4 prepay of a composed send into Solana.
function prepayCharge(uint32 dstEid, uint256 composeLen) external view returns (uint256 lamports, uint256 costWei, address to);
}
src/v4/gap/PangeaOFTV4Storage.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title PangeaOFTV4Storage -- the state PangeaOFTV4 shares with its gap module
/// @notice One ERC-7201 namespace, read and written by the token (its price recorder in `_update`, the metadata
/// it sets in its constructor) and by PangeaOFTV4GapModule, which runs in the token's context by
/// DELEGATECALL (buyAndSend's swap, the send's message, the receive, the views and the metadata calls).
/// Nothing else of the token's storage is touched by the module: the OFT, ERC20 and Ownable state stays
/// where their own bases put it.
/// v4: the v3 price records, price log, writer rewards, cover windows, co-sign nonces and epochs are
/// gone; the official pool is cached once for life (no re-point); the recorder is a 3-bucket ring
/// (GapMathV4.Ring, packed by GapRecorderV4).
library PangeaOFTV4Storage {
/// @custom:storage-location erc7201:pangea.oft.v4
struct Layout {
// ---- the official pool, cached from the registry on first use (GapRecorderV4.learn), never changed
bool known; // the pool below is cached
bool tokenIs0; // this token is the pool's currency0
uint8 quoteDecimals; // the quote's decimals (native: 18)
uint24 lpFee; // the static LP fee (ppm)
int24 tickSpacing;
address poolQuote; // address(0) = native
/// @dev G-EVMB-2 L-3: the pool the bridge / registry names can never be used (its key does not hash to its id,
/// a dynamic or out-of-range fee, or a quote whose decimals() is unreadable with its full gas cap), so it is
/// never looked up again. Packed into the first word after poolQuote (bits 232..239): no field moves.
bool unusable;
address poolHook;
bytes32 poolId;
bytes32 lockedPositionKey; // the permanently locked launch position (the margin's and k's depth)
// ---- the recorder ring (GapRecorderV4): slot i is words 2i (min | max << 128) and 2i + 1
// (start | lastTs << 40 | lastBlock << 80 | lastPrice << 128); `ringMeta` is
// head | width << 8 (32 bits) | prevBlock << 40 | prevPrice << 88 | prevTs << 216.
uint256[6] ring;
uint256 ringMeta;
// ---- the receive
uint256 gapBurnedLD;
mapping(bytes32 guid => uint256 withheldLD) gapWithheld;
/// @dev acceptBelowMin: the recipient's consent to land `guid` below its minCredited.
mapping(bytes32 guid => mapping(address to => bool)) acceptedBelowMin;
// ---- the metadata (v3 unchanged)
string metadataURI;
address metadataAuthority;
address pendingMetadataAuthority;
// ---- audit r3 F5: the block in which `sendTo`'s destination sale allowance (coverDst) was last counted
mapping(address sendTo => uint256 blockNumber) coverDstBlock;
}
/// @dev keccak256(abi.encode(uint256(keccak256("pangea.oft.v4")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant SLOT = 0x80e06bfa3d992f4a0a3d295e6f9a5c02e26e679360a34ac5a5c8b08a4affb900;
function layout() internal pure returns (Layout storage l) {
bytes32 s = SLOT;
assembly ("memory-safe") {
l.slot := s
}
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"@layerzerolabs/oft-evm/=lib/layerzero/oft-evm/",
"@layerzerolabs/oapp-evm/=lib/layerzero/oapp-evm/",
"@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero/protocol-v2/",
"@uniswap/v4-core/=lib/uniswap-v4-core/",
"solmate/=lib/solmate/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"layerzero/=lib/layerzero/",
"uniswap-v4-core/=lib/uniswap-v4-core/src/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.