Verified contractExactUNLICENSED
BridgeGapV4
Address0x161925a08b5da27e0ef56f8f5aeac7ce207d62c7
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,401,403
- Creation transaction
- 0xfc431e2784…e1b5eb5317
11 files
- src/v4/bridge/gap/BridgeGapV4.solmain12.63 KB
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.82 KB
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol28.31 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/v4/bridge/BridgeCodecV4.sol5.82 KB
- src/v4/bridge/PangeaDeployerV4.sol2.04 KB
- src/v4/bridge/gap/GapPriceSigV4.sol2.65 KB
- src/v4/bridge/gap/IGapOracleV4.sol3.86 KB
- src/v4/gap/GapMathV4.sol35.73 KB
- src/v4/gap/IGapRegistryV4.sol20.77 KB
src/v4/bridge/gap/BridgeGapV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IPendingConfigV4} from "../PangeaDeployerV4.sol";
import {BridgeCodecV4 as Codec} from "../BridgeCodecV4.sol";
import {IGapOracleV4} from "./IGapOracleV4.sol";
import {GapPriceSigV4 as Sig} from "./GapPriceSigV4.sol";
import {GapMathV4} from "../../gap/GapMathV4.sol";
/// @title BridgeGapV4 -- the shared bridge's gap pricing, a STATELESS view helper (size: §11.2.10's module split)
/// @notice Called (STATICCALL) by PangeaBridgeV4 only for prices and credits; holds no state and no power: every
/// number it returns is capped by the bridge's own rules (credited <= A, hard invariant (i)). Same address on
/// every EVM chain (PangeaDeployerV4; the oracle from `pending()`).
/// - verify(): §11.3.2 on a signed PAIR price, EIP-712 domain ("PangeaGapPrice", "1", chain id, the BRIDGE).
/// - source price: signed (verified, reverts on a bad signature) > fallback reader > none (§11.3.4-5).
/// - credit(): the §8 arrival rules with GapMathV4 (signed Pd from the message, else the destination reader).
/// - buy(): Ps = min(Pexec in USD, Panchor x (1 + k)), the source cover.
contract BridgeGapV4 {
bytes32 internal constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 internal constant NAME_HASH = keccak256("PangeaGapPrice");
bytes32 internal constant VERSION_HASH = keccak256("1");
IGapOracleV4 public immutable oracle;
/// @dev BridgeStateV4.chainKind(uint32) (KIND_EVM = 1), read from the calling bridge.
bytes4 internal constant CHAIN_KIND = bytes4(keccak256("chainKind(uint32)"));
error GapPriceInvalid(uint8 why);
error GapPriceExpired(uint64 validUntil);
constructor() {
oracle = IGapOracleV4(abi.decode(IPendingConfigV4(msg.sender).pending(), (address)));
}
function domainSeparator(address bridge) public view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, block.chainid, bridge));
}
function digest(Sig.GapPrice calldata p, address bridge) public view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator(bridge), Sig.hash(p)));
}
/// @dev why: 1 coin, 2 src pcid, 3 dst pcid, 4 src token, 5 decimals, 6 key, 7 validity window, 8 clock skew,
/// 9 zero price, 10 signature; 11 the signed quote price's chain / quote (A2-ASK-1; any quote, ANY PAIRS).
function verify(Sig.SignedGapPrice calldata gp, bytes32 coinId, uint32 local, uint32 dst, address token, address bridge)
public
view
{
Sig.GapPrice calldata p = gp.p;
if (p.coinId != coinId) revert GapPriceInvalid(1);
if (p.src.pcid != local) revert GapPriceInvalid(2);
if (p.dst.pcid != dst) revert GapPriceInvalid(3);
if (p.src.token != bytes32(uint256(uint160(token)))) revert GapPriceInvalid(4);
if (p.src.decimals != 9) revert GapPriceInvalid(5);
address key = _signer(p.keyId, p.observedAt, p.validUntil);
if (p.src.priceUsdE18 == 0 || p.dst.priceUsdE18 == 0) revert GapPriceInvalid(9);
_checkSig(digest(p, bridge), gp.sig, key);
}
/// @dev §11.3.2 steps shared by both signed messages: the signer slot live, not expired, the validity window,
/// the clock skew. Returns the slot's key.
function _signer(uint8 keyId, uint64 observedAt, uint64 validUntil) internal view returns (address) {
if (keyId > 3) revert GapPriceInvalid(6);
IGapOracleV4.PriceSigner memory s = oracle.priceSigner(keyId);
if (s.key == address(0) || block.timestamp < s.validFrom || block.timestamp > s.validUntil) revert GapPriceInvalid(6);
if (block.timestamp > validUntil) revert GapPriceExpired(validUntil);
if (validUntil < observedAt || validUntil - observedAt > oracle.maxValiditySec()) revert GapPriceInvalid(7);
if (observedAt > block.timestamp + 5) revert GapPriceInvalid(8);
return s.key;
}
function _checkSig(bytes32 dg, bytes memory sig, address key) internal pure {
(address got, ECDSA.RecoverError e,) = ECDSA.tryRecover(dg, sig);
if (e != ECDSA.RecoverError.NoError || got != key) revert GapPriceInvalid(10);
}
/// @notice A2-ASK-1: the EIP-712 digest of a signed quote USD price (the gap price's domain: this chain, the bridge).
function quoteDigest(Sig.QuoteUsdPrice memory q, address bridge) public view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator(bridge), Sig.hashQuote(q)));
}
/// @notice A2-ASK-1 (signed price first): the quote's USD for Pexec_usd. `signedQuote` = abi.encode(QuoteUsdPrice,
/// bytes sig) (empty = none): when given it is VERIFIED (else the call reverts) and used for this chain
/// (pcid = oracle.localChain()) and THIS quote (the coin's). ANY PAIRS (owner 2026-11-08 23:15, F1): any
/// quote -- native, or ANY ERC-20, listed or not (no asset venue needed); the signer prices it. None ->
/// the oracle's asset reader (0 = unpriced: that buy then crosses plain and unpriced, credited in full;
/// OD-A-11, D1 RULE-CHECK 1300, was BuyNeedsPrice).
function quoteUsd(address quote, bytes calldata signedQuote, address bridge) public view returns (uint256) {
if (signedQuote.length == 0) return oracle.assetUsd(quote, false);
(Sig.QuoteUsdPrice memory q, bytes memory sig) = abi.decode(signedQuote, (Sig.QuoteUsdPrice, bytes));
if (q.pcid != oracle.localChain() || q.quote != quote) revert GapPriceInvalid(11);
address key = _signer(q.keyId, q.observedAt, q.validUntil);
if (q.priceUsdE18 == 0) revert GapPriceInvalid(9);
_checkSig(quoteDigest(q, bridge), sig, key);
return q.priceUsdE18;
}
/// @notice The send's price: (priceSource, psUsdE18, p2E18, source depth). AB1-R2 (§11.3.2 "k unchanged"): under a
/// signed price the source depth is still read ON CHAIN from the coin's source reader (before the buy), so
/// k follows the dynamic curve exactly as on the fallback path; depth 0 (unreadable) -> kMin as there.
function sourcePrice(Sig.SignedGapPrice calldata gp, bytes32 coinId, uint32 local, uint32 dst, address token)
external
view
returns (uint8 source, uint128 ps, uint128 p2, uint256 depth)
{
if (gp.sig.length != 0) {
verify(gp, coinId, local, dst, token, msg.sender);
(, depth) = oracle.coinPriceSrc(token);
return (Codec.PS_SIGNED, gp.p.src.priceUsdE18, gp.p.dst.priceUsdE18, depth);
}
uint256 p;
(p, depth) = oracle.coinPriceSrc(token);
if (p != 0 && p <= type(uint128).max) return (Codec.PS_FALLBACK, uint128(p), 0, depth);
// GAPFIX ANYPAIRS: the quote has no USD source -> its pool price in the QUOTE, p2 = the quote's family (EVM
// destinations only; priceClass stays 0, so a Solana-style class message never reads as one). The destination
// prices the gap as the ratio when its quote is of the same family, else credits in full (fee 0 by design).
(bool ok, bytes memory k) = msg.sender.staticcall(abi.encodeWithSelector(CHAIN_KIND, dst));
if (ok && k.length == 32 && abi.decode(k, (uint256)) == 1) {
uint8 fam;
(p, fam) = oracle.coinPriceClass(token, false);
if (fam != 0) return (Codec.PS_FALLBACK, uint128(p), fam, 0);
}
return (Codec.PS_NONE, 0, 0, 0);
}
/// @notice The arrival credit (LD) of `h` on this chain for `token`, amount `a` (LD).
function credit(Codec.Header calldata h, address token, uint256 a) external view returns (uint256) {
IGapOracleV4.Params memory p = oracle.params(h.coinId);
if (!p.gapOn || h.priceSource == Codec.PS_NONE || h.psUsdE18 == 0) return a;
if (h.priceSource == Codec.PS_FALLBACK && h.priceClass == 0 && h.p2E18 != 0) {
// GAPFIX ANYPAIRS class pair (sourcePrice): Ps and Pd in the same quote family, the pools' price ratio
(uint256 pc, uint8 fam) = oracle.coinPriceClass(token, true);
if (h.mode != Codec.MODE_PLAIN || fam == 0 || fam != h.p2E18) return a; // no common family: fee 0 by design
return GapMathV4.creditPlain(a, h.psUsdE18, pc);
}
(uint256 pdR, uint256 depth, uint32 fD) = oracle.coinPriceDst(token);
uint256 pd = h.priceSource == Codec.PS_SIGNED ? h.p2E18 : pdR;
if (pd == 0 || pd > GapMathV4.PRICE_MAX) return a;
if (h.mode == Codec.MODE_PLAIN) return GapMathV4.creditPlain(a, h.psUsdE18, pd);
uint256 cover = GapMathV4.coverUsdE18(h.coverSrcMicroUsd, 0, p.coverCapUsdE18);
uint256 c = GapMathV4.creditBuy(
a, h.bridgeFeePpm, h.psUsdE18, _marginAt(p, depth), cover, pd, h.priceSource == Codec.PS_SIGNED ? 0 : fD, 9
);
return c > a ? a : c;
}
/// @notice buyAndSend's credit price and cover: Ps = min(Pexec_usd, Panchor x (1 + k)); 0 Ps = unpriced.
/// A2-ASK-1: `signedQuote` (see quoteUsd) prices the quote first; the cover's native USD is the signed
/// quote price when the quote is native, else the oracle's.
function buy(
bytes32 coinId,
address quote,
uint256 quotePaid,
uint256 out,
uint256 panchor,
uint256 depth,
uint256 transportFee,
bytes calldata signedQuote
) external view returns (uint256 ps, uint256 pexecUsd, uint32 coverMicro) {
IGapOracleV4.Params memory p = oracle.params(coinId);
uint256 qUsd = quoteUsd(quote, signedQuote, msg.sender);
pexecUsd = _pexecUsd(quote, quotePaid, out, qUsd);
if (pexecUsd == 0 || panchor == 0) return (0, pexecUsd, 0);
ps = GapMathV4.psBuy(pexecUsd, panchor, p.kOn, _k(p, depth));
if (ps > type(uint128).max) ps = 0;
coverMicro = _cover(p, transportFee, quote == address(0) && signedQuote.length != 0 ? qUsd : oracle.assetUsd(address(0), false));
}
/// @notice Plain-send credit known at the source (priceSource 1): min(A, A x Ps / Pd).
function creditPlain(uint256 a, uint256 ps, uint256 pd) external pure returns (uint256) {
return GapMathV4.creditPlain(a, ps, pd);
}
/// @notice AB1-R2: the buy path's k (ppm) for `coinId` at `token`'s source depth as the bridge reads it now (the
/// planner's mirror; signed and fallback alike): (depth USD E18, k ppm).
function sourceK(bytes32 coinId, address token) external view returns (uint256 depth, uint256 kPpm) {
(, depth) = oracle.coinPriceSrc(token);
kPpm = _k(oracle.params(coinId), depth);
}
function _k(IGapOracleV4.Params memory p, uint256 depth) internal pure returns (uint256) {
return depth == 0 ? _lo(p.kMinPpm, p.kMaxPpm) : GapMathV4.kPpm(p.kK, p.kMinPpm, p.kMaxPpm, depth, _marginAt(p, depth));
}
function _marginAt(IGapOracleV4.Params memory p, uint256 depth) internal pure returns (uint32) {
if (depth == 0) return _lo(p.marginMinPpm, p.marginMaxPpm);
return GapMathV4.margin(p.marginK, p.marginMinPpm, p.marginMaxPpm, depth);
}
function _lo(uint32 lo, uint32 hi) internal pure returns (uint32) {
return lo > hi ? hi : lo;
}
function _pexecUsd(address quote, uint256 quotePaid, uint256 out, uint256 qUsd) internal view returns (uint256) {
if (quotePaid == 0) return 0;
uint8 dq = 18;
if (quote != address(0)) {
(bool s, bytes memory r) = quote.staticcall{gas: 30_000}(abi.encodeWithSignature("decimals()"));
if (!s || r.length != 32 || abi.decode(r, (uint256)) > 36) return 0;
dq = uint8(abi.decode(r, (uint256)));
}
uint256 pq = GapMathV4.pexec(quotePaid, out, 9, dq);
return pq == 0 ? 0 : GapMathV4.mulDown(pq, qUsd);
}
function _cover(IGapOracleV4.Params memory p, uint256 transportFee, uint256 n) internal pure returns (uint32) {
if (p.coverCapUsdE18 == 0 || transportFee == 0) return 0;
uint256 usd = Math.mulDiv(transportFee, n, 1e18);
if (usd > p.coverCapUsdE18) usd = p.coverCapUsdE18;
uint256 micro = usd / GapMathV4.MICRO_USD_E18;
return micro > type(uint32).max ? type(uint32).max : uint32(micro);
}
}
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/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/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))
}
}
}
src/v4/bridge/BridgeCodecV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title BridgeCodecV4 -- codec 0x05 (V4-INTERFACES §11.2.5), transport-neutral, big-endian
/// 0 ver 0x05 | 1 mode (0 plain, 1 buy, 2 creator mirror, 3 open authorisation, 0xFF refund) | 2 transportId |
/// 3 priceSource (0 none, 1 signed, 2 on-chain fallback) | 4 srcPcid u32 | 8 dstPcid u32 | 12 coinId | 44 recipient |
/// 76 sender | 108 amountSD u64 (shared decimals 6) | 116 psUsdE18 u128 | 132 p2E18 u128 | 148 bridgeFeePpm u32 |
/// 152 coverSrcMicroUsd u32 | 156 minCreditedSD u64 | 164 priceClass u8 | 165 reserved 3 = 0 | 168 tail
/// tail: mode 0/1 composeMsg (composed iff length > 168); mode 2 creatorEvm 32 | creatorSvm 32 | u64 roleNonce |
/// u8 renounced (241 B); mode 3 opener 32 | u64 deadline | the mode-2 role fields | u64 issuedAt (unix s at the
/// home's authorizeOpen; B4-I1: appended, 289 B); mode 0xFF none.
/// META-OPENLATER (audit G-ROLL 18 M-2): a mode 3's header recipient (44..76, zero before) = uriHash = keccak256 of the
/// home coin's metadataURI at authorizeOpen; the far chain opens the authorised leg only with that URI. The length is
/// unchanged (289 B = the LayerZero maxMessageSize pin toward Solana).
library BridgeCodecV4 {
uint8 internal constant VERSION = 0x05;
uint8 internal constant MODE_PLAIN = 0;
uint8 internal constant MODE_BUY = 1;
uint8 internal constant MODE_ROLE = 2;
uint8 internal constant MODE_OPEN_AUTH = 3;
uint8 internal constant MODE_REFUND = 0xFF;
uint8 internal constant PS_NONE = 0;
uint8 internal constant PS_SIGNED = 1;
uint8 internal constant PS_FALLBACK = 2;
uint256 internal constant HEADER = 168;
uint256 internal constant ROLE_LEN = 73;
uint256 internal constant OPEN_AUTH_LEN = 121;
uint8 internal constant SHARED_DECIMALS = 6;
struct Header {
uint8 mode;
uint8 transportId;
uint8 priceSource;
uint32 srcPcid;
uint32 dstPcid;
bytes32 coinId;
bytes32 recipient;
bytes32 sender;
uint64 amountSD;
uint128 psUsdE18;
uint128 p2E18;
uint32 bridgeFeePpm;
uint32 coverSrcMicroUsd;
uint64 minCreditedSD;
uint8 priceClass;
}
struct Role {
bytes32 creatorEvm;
bytes32 creatorSvm;
uint64 roleNonce;
bool renounced;
}
error BadVersion();
error BadReserved();
error BadMessage(uint8 why);
function encode(Header memory h, bytes memory tail) internal pure returns (bytes memory) {
return abi.encodePacked(
abi.encodePacked(VERSION, h.mode, h.transportId, h.priceSource, h.srcPcid, h.dstPcid, h.coinId, h.recipient, h.sender),
abi.encodePacked(h.amountSD, h.psUsdE18, h.p2E18, h.bridgeFeePpm, h.coverSrcMicroUsd, h.minCreditedSD, h.priceClass),
bytes3(0),
tail
);
}
function encodeRole(Role memory r) internal pure returns (bytes memory) {
return abi.encodePacked(r.creatorEvm, r.creatorSvm, r.roleNonce, r.renounced ? uint8(1) : uint8(0));
}
/// @notice Strict: version, reserved, mode-specific length and fields. why: 1 short, 2 unknown mode, 3 tail length,
/// 4 cover in mode 0, 5 priceSource / class, 6 bridge fee >= 1e6, 7 refund / control fields not zero.
function decode(bytes calldata b) internal pure returns (Header memory h, bytes calldata tail) {
if (b.length < HEADER) revert BadMessage(1);
if (uint8(b[0]) != VERSION) revert BadVersion();
if (bytes3(b[165:168]) != bytes3(0)) revert BadReserved();
h.mode = uint8(b[1]);
h.transportId = uint8(b[2]);
h.priceSource = uint8(b[3]);
h.srcPcid = uint32(bytes4(b[4:8]));
h.dstPcid = uint32(bytes4(b[8:12]));
h.coinId = bytes32(b[12:44]);
h.recipient = bytes32(b[44:76]);
h.sender = bytes32(b[76:108]);
h.amountSD = uint64(bytes8(b[108:116]));
h.psUsdE18 = uint128(bytes16(b[116:132]));
h.p2E18 = uint128(bytes16(b[132:148]));
h.bridgeFeePpm = uint32(bytes4(b[148:152]));
h.coverSrcMicroUsd = uint32(bytes4(b[152:156]));
h.minCreditedSD = uint64(bytes8(b[156:164]));
h.priceClass = uint8(b[164]);
tail = b[168:];
uint8 m = h.mode;
if (m > MODE_OPEN_AUTH && m != MODE_REFUND) revert BadMessage(2);
if (m == MODE_ROLE && tail.length != ROLE_LEN) revert BadMessage(3);
if (m == MODE_OPEN_AUTH && tail.length != OPEN_AUTH_LEN) revert BadMessage(3);
if ((m == MODE_REFUND) && tail.length != 0) revert BadMessage(3);
if (m == MODE_PLAIN && h.coverSrcMicroUsd != 0) revert BadMessage(4);
if (h.priceSource > PS_FALLBACK || (h.priceSource != PS_FALLBACK && h.priceClass != 0)) revert BadMessage(5);
if (h.priceSource == PS_NONE && (h.psUsdE18 != 0 || h.p2E18 != 0)) revert BadMessage(5);
if (h.bridgeFeePpm >= 1_000_000) revert BadMessage(6);
if (m >= MODE_ROLE && (h.priceSource != PS_NONE || h.coverSrcMicroUsd != 0 || h.minCreditedSD != 0)) revert BadMessage(7);
if (m == MODE_ROLE || m == MODE_OPEN_AUTH) {
if (h.amountSD != 0) revert BadMessage(7);
}
}
function decodeRole(bytes calldata t) internal pure returns (Role memory r) {
r.creatorEvm = bytes32(t[0:32]);
r.creatorSvm = bytes32(t[32:64]);
r.roleNonce = uint64(bytes8(t[64:72]));
r.renounced = uint8(t[72]) != 0;
}
/// @notice msgId = keccak256(u8 transportId | bytes32 transportMsgId) (LZ guid / Hyperlane message id).
function msgId(uint8 transportId, bytes32 transportMsgId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(transportId, transportMsgId));
}
}
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/bridge/gap/GapPriceSigV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title GapPriceSigV4 -- the signed gap price PAIR (V4-INTERFACES §11.3.1), EIP-712 struct hashing
library GapPriceSigV4 {
struct GapPriceLeg {
uint32 pcid;
bytes32 token;
bytes32 pool;
uint128 priceUsdE18;
uint8 decimals;
uint64 blockOrSlot;
}
struct GapPrice {
bytes32 coinId;
GapPriceLeg src;
GapPriceLeg dst;
uint64 observedAt;
uint64 validUntil;
uint8 keyId;
}
/// @notice sig.length == 0 -> "no signed price" (fallback).
struct SignedGapPrice {
GapPrice p;
bytes sig;
}
/// @notice RULING A2-ASK-1 (signed price first): the signed USD price of the coin's QUOTE on the chain of the buy
/// (native = address(0), or ANY ERC-20: ANY PAIRS, listed or not), for buyAndSend's Pexec_usd (and the cover when the quote is native) where no asset
/// reader prices it (Robinhood). Same EIP-712 domain and signer slots as GapPrice ("PangeaGapPrice", "1",
/// chain id, the BRIDGE). priceUsdE18 = USD x 1e18 per WHOLE quote unit (1 ETH, 1 USDC).
struct QuoteUsdPrice {
uint32 pcid;
address quote;
uint128 priceUsdE18;
uint64 observedAt;
uint64 validUntil;
uint8 keyId;
}
bytes32 internal constant QUOTE_USD_TYPEHASH =
keccak256("QuoteUsdPrice(uint32 pcid,address quote,uint128 priceUsdE18,uint64 observedAt,uint64 validUntil,uint8 keyId)");
function hashQuote(QuoteUsdPrice memory q) internal pure returns (bytes32) {
return keccak256(abi.encode(QUOTE_USD_TYPEHASH, q.pcid, q.quote, q.priceUsdE18, q.observedAt, q.validUntil, q.keyId));
}
bytes32 internal constant LEG_TYPEHASH =
keccak256("GapPriceLeg(uint32 pcid,bytes32 token,bytes32 pool,uint128 priceUsdE18,uint8 decimals,uint64 blockOrSlot)");
bytes32 internal constant PRICE_TYPEHASH = keccak256(
"GapPrice(bytes32 coinId,GapPriceLeg src,GapPriceLeg dst,uint64 observedAt,uint64 validUntil,uint8 keyId)GapPriceLeg(uint32 pcid,bytes32 token,bytes32 pool,uint128 priceUsdE18,uint8 decimals,uint64 blockOrSlot)"
);
function hashLeg(GapPriceLeg calldata l) internal pure returns (bytes32) {
return keccak256(abi.encode(LEG_TYPEHASH, l.pcid, l.token, l.pool, l.priceUsdE18, l.decimals, l.blockOrSlot));
}
function hash(GapPrice calldata p) internal pure returns (bytes32) {
return keccak256(abi.encode(PRICE_TYPEHASH, p.coinId, hashLeg(p.src), hashLeg(p.dst), p.observedAt, p.validUntil, p.keyId));
}
}
src/v4/bridge/gap/IGapOracleV4.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title IGapOracleV4 -- the shared bridge's gap prices: our signed gap price (PRIMARY) and the upgradable fallback
/// reader registry. Owner 2026-11-06 20:45: signed price first; else the on-chain reader of the coin's pool;
/// else NO gap fee; never a user-supplied price.
interface IGapOracleV4 {
/// @notice §11.3.3 signer slot (keyId 0..3): validFrom <= now <= validUntil; validUntil = now revokes at once.
struct PriceSigner {
address key;
uint64 validFrom;
uint64 validUntil;
}
/// @notice Per-chain gap parameters (coin override possible). Every value admin-set (LEAD UPDATE 2/3).
struct Params {
uint16 bridgeFeeBps; // < 10,000; default 20
bool gapOn; // false = the coin's arrivals are credited in full (escape)
bool kOn; // the buy backstop Ps = min(Pexec, Psrc x (1 + k))
uint64 marginK; // x 1e6 (GapMathV4.curve)
uint32 marginMinPpm;
uint32 marginMaxPpm;
uint64 kK; // x 1e6
uint32 kMinPpm;
uint32 kMaxPpm;
uint128 coverCapUsdE18; // 0 = no cover
}
function localChain() external view returns (uint32);
function params(bytes32 coinId) external view returns (Params memory);
function priceSigner(uint8 keyId) external view returns (PriceSigner memory);
function maxValiditySec() external view returns (uint32);
/// @notice B1-M3: our delivery keys (buy-mode arrivals at once) and the window after which anyone may deliver.
function isDeliveryKey(address key) external view returns (bool);
function exclusiveWindowSec() external view returns (uint32);
/// @notice A-D8: what a send toward (dstPcid, tid) owes our keys-only delivery and to whom ((0, 0) = none).
function deliveryCharge(uint32 dstPcid, uint8 tid) external view returns (uint256 costWei, address to);
/// @notice FALLBACK source price: the coin's pool reader on this chain, rounded down (0s = unreadable).
function coinPriceSrc(address token) external view returns (uint256 priceUsdE18, uint256 depthUsdE18);
/// @notice FALLBACK destination price: the reader of `token`'s pool on this chain, rounded UP; 0s when unreadable.
function coinPriceDst(address token) external view returns (uint256 priceUsdE18, uint256 depthUsdE18, uint32 feePpm);
/// @notice USD x 1e18 per whole `asset` (quote / native = address(0)) on this chain, by its reader (0 = unreadable).
function assetUsd(address asset, bool roundUp) external view returns (uint256);
/// @notice GAPFIX ANYPAIRS: `token`'s rule price in its pool's quote and that quote's family ((0, 0) = none).
function coinPriceClass(address token, bool roundUp) external view returns (uint256 pQuoteE18, uint8 family);
/// @notice A2-ASK-1: the venue id `asset` is LISTED under (0 = not listed).
function assetVenueId(address asset) external view returns (uint16);
}
/// @title IGapReaderV4 -- a venue reader in the fallback registry (Uniswap v2/v3/v4, Aerodrome, Pancake, ...).
interface IGapReaderV4 {
/// @notice USD x 1e18 per whole `token` at the pool `poolRef` (venue-specific encoding), rounded as asked; its
/// quote-side depth in USD x 1e18 and the pool's total fee (ppm). 0s = unreadable.
function read(address token, bytes calldata poolRef, bool roundUp)
external
view
returns (uint256 priceUsdE18, uint256 depthUsdE18, uint32 feePpm);
}
/// @title IGapQuoteReaderV4 -- GAPFIX ANYPAIRS (optional for a reader; one without it = no class price): the price in
/// the pool's quote (x 1e18 per whole token) and the quote.
interface IGapQuoteReaderV4 {
function readQuote(address token, bytes calldata poolRef, bool roundUp) external view returns (uint256 pQuoteE18, address quote);
}
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/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);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
":@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero/protocol-v2/",
":@layerzerolabs/oapp-evm/=lib/layerzero/oapp-evm/",
":@layerzerolabs/oft-evm/=lib/layerzero/oft-evm/",
":@openzeppelin/=lib/openzeppelin-contracts/",
":@uniswap/v4-core/=lib/uniswap-v4-core/",
":ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
":layerzero/=lib/layerzero/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":solmate/=lib/solmate/",
":uniswap-v4-core/=lib/uniswap-v4-core/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.