Skip to content
Verified contractExactUNLICENSED

PangeaBridgeV4

Address0x52a4b40fa6d72f44fbaadb0e38cbc087b3af0880
Balance

0 ETH

 

Transactions

14

 

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,405
Creation transaction
0xf24a39c53c…4623b8c0bd

65 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/v4/bridge/PangeaBridgeV4.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {BridgeCodecV4 as Codec} from "./BridgeCodecV4.sol";
import {CoinPreimageV4 as Pre} from "./CoinPreimageV4.sol";
import {PangeaCoinV4} from "./PangeaCoinV4.sol";
import {BridgeBuyerV4} from "./BridgeBuyerV4.sol";
import {BridgeRowsV4} from "./BridgeRowsV4.sol";
import {IPendingConfigV4} from "./PangeaDeployerV4.sol";
import {ITransportAdapterV4, IBridgeForAdaptersV4} from "./ITransportV4.sol";
import {IGapOracleV4} from "./gap/IGapOracleV4.sol";
import {GapPriceSigV4 as Sig} from "./gap/GapPriceSigV4.sol";
import {BridgeGapV4} from "./gap/BridgeGapV4.sol";
import {BridgeStateV4} from "./BridgeStateV4.sol";

/// @dev gate-cheap-erc20 H-1: what setComposer checks on the composer it lists.
interface IComposerBridgeV4 {
    function bridge() external view returns (address);
}

interface IComposeExecV4 {
    function composeExec(bytes32 msgId, bytes32 coinId, uint32 srcPcid, bytes32 composeFrom, address to, uint256 creditedLD, bytes calldata composeMsg)
        external;
}

interface IPangeaComposerV4 {
    function pangeaCompose(bytes32 msgId, bytes32 coinId, uint32 srcPcid, bytes32 composeFrom, uint256 creditedLD, bytes calldata composeMsg)
        external;
}

/// @title PangeaBridgeV4 -- ONE shared bridge per chain for every v4 coin (V4-INTERFACES §11.2; owner 2026-11-07)
/// @notice IMMUTABLE, one address on every EVM chain (PangeaDeployerV4; chain values from `pending()`).
/// - ROWS: chain kinds and (pcid, transport) routes {remoteDomain, peer}, each set ONCE, never removed; an EVM peer is
///   forced to the canonical adapter address. Adapters set once per transport id.
/// - COINS: coinId = keccak256(CoinPreimageV4) binds the chain list, transport mask and rowsHash (every listed
///   (pcid, tid) row of the tids common to its chains, plus its per-chain tid sets when they are not the mask on every
///   chain); registered here only by LaunchCoreV4 at the chain's open, only if the LOCAL rows hash to it. A route of
///   the coin uses only tids in BOTH ends' creation sets (T17-FIX): nobody can add a chain or transport to a coin.
/// - SEND burns first (dust below 6 shared decimals stays with the sender), then one message on one transport.
/// - RECEIVE only from the adapter of the transport the message names, from that row's peer, once per msgId; credit
///   <= amount (gap fee withheld, never minted). A listed but unopened chain HOLDS (release / refund later).
/// - GAP: signed pair price (EIP-712, verified here) PRIMARY; else the fallback readers (GapOracleV4); else none.
/// - CREATOR ROLE (= fee payee) lives here on every chain; changed on the home chain, mirrored by mode-2 messages.
/// - ADMIN: rows, adapters (once), pauses of NEW sends, the creator step-in, fee recipient. No mint, no burn, no list
///   change, no upgrade, no receive pause (hard invariants i-iv).
contract PangeaBridgeV4 is BridgeStateV4, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;

    uint32 public immutable localPcid;
    IGapOracleV4 public immutable oracle;
    address public immutable core;
    BridgeGapV4 public immutable gap;
    BridgeBuyerV4 public immutable buyer;
    /// @notice T17-SIZE: the rowsHash view of this bridge (created after `buyer`, so `buyer` keeps its address).
    BridgeRowsV4 public immutable rows;
    /// @notice The creator-role module (BridgeRoleV4), run by DELEGATECALL from `fallback` (§11.6 functions).
    address public immutable roleModule;
    /// @notice UPGRADEABLE COIN CREATION: the immutable append-only coin code list; registerCoin takes only a token it
    ///         calls genuine (the recorded code at its one CREATE2 address), whatever the (upgradeable) core hands over.
    address public immutable codeRegistry;

    constructor() Ownable(_pendingOwner()) {
        (uint32 pcid,, address oracle_, address core_, address feeTo_, address gap_, address role_, address pm_, address reg_) =
            abi.decode(IPendingConfigV4(msg.sender).pending(), (uint32, address, address, address, address, address, address, address, address));
        roleModule = role_;
        // the registry is placed after the bridge (its config names the coin-deployer proxy): its address only, never 0
        if (reg_ == address(0)) revert ZeroAddress();
        codeRegistry = reg_;
        // G-EVMB-1 L-3: the role module (delegatecall target: an empty one would make every admin call a silent
        // no-op) and the PoolManager must be contracts
        if (oracle_ == address(0) || core_ == address(0) || feeTo_ == address(0) || gap_ == address(0)) revert ZeroAddress();
        if (role_.code.length == 0 || pm_.code.length == 0) revert ZeroAddress();
        gap = BridgeGapV4(gap_);
        localPcid = pcid;
        oracle = IGapOracleV4(oracle_);
        core = core_;
        bridgeFeeTo = feeTo_;
        buyer = new BridgeBuyerV4(pm_);
        rows = new BridgeRowsV4();
    }

    function _local() internal view override returns (uint32) {
        return localPcid;
    }

    /// @notice transferCreator / renounceCreator / adminProposeCreator / acceptCreator / pushCreator / authorizeOpen
    ///         (IBridgeRoleV4) run in BridgeRoleV4 by DELEGATECALL, as this bridge.
    fallback() external payable {
        address m = roleModule;
        assembly ("memory-safe") {
            calldatacopy(0, 0, calldatasize())
            let ok := delegatecall(gas(), m, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch ok
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    /// @notice G-EVMB-1 I-7: disabled (an ownerless bridge could never add a row, adapter or pause again).
    function renounceOwnership() public view override onlyOwner {
        revert RenounceDisabled();
    }

    function _pendingOwner() private view returns (address o) {
        (, o,,,,,,,) = abi.decode(IPendingConfigV4(msg.sender).pending(), (uint32, address, address, address, address, address, address, address, address));
    }

    // admin (rows, adapters, pauses), creatorOf, gapPriceDigest: in BridgeRoleV4 (size split)

    // SIZE-17 TRACK B: setTransport + setComposer moved back here from BridgeRoleV4 (EIP-170 room after the buy dedup).

    function setTransport(uint8 tid, address adapter) external onlyOwner {
        if (adapterOf[tid] != address(0)) revert AdapterExists(tid);
        if (tid == 0 || tid > 15 || adapter.code.length == 0) revert AdapterMismatch();
        if (ITransportAdapterV4(adapter).transportId() != tid || ITransportAdapterV4(adapter).bridge() != address(this)) {
            revert AdapterMismatch();
        }
        adapterOf[tid] = adapter;
        emit TransportSet(tid, adapter);
    }

    /// @notice gate-cheap-erc20 H-1: this release's CheapestComposerV4 on this chain (go-live, right after the composer's
    ///         deploy; owner, instant: no timelock by the owner rule; 0 = none). It must be bound to this bridge
    ///         (its bridge() = this). A send it makes carries a.refundTo (the user) as the message's sender (buyAndSend). SIZE-17 TRACK B: here again (was BridgeRoleV4, EIP-170).
    function setComposer(address c) external onlyOwner {
        if (c != address(0) && (c.code.length == 0 || IComposerBridgeV4(c).bridge() != address(this))) revert ComposerSend();
        _composer = c;
        emit ComposerSet(c);
    }

    function composer() external view returns (address) {
        return _composer;
    }

    // ================================================================== views

    function routeOf(uint32 pcid, uint8 tid) external view returns (Route memory) {
        return _routes[pcid][tid];
    }

    function pcidOf(uint8 tid, uint32 remoteDomain) external view returns (uint32) {
        return _pcidOfDomain[tid][remoteDomain];
    }

    /// @notice B4-I3: the number of pause-only keys switched on (VerifyBridgeV4: 1 = the supply watcher).
    function pauserCount() external view returns (uint256) {
        return _pauserCount;
    }

    /// @notice AB1-R1: refundHeld opens beyond the recipient this long after heldAt.
    function heldRefundWindow() external pure returns (uint64) {
        return HELD_REFUND_WINDOW;
    }

    // isSendPaused, quoteSend: in BridgeRoleV4 (size split; same selectors at this address)

    // registerCoin (open, LaunchCoreV4 only): in BridgeRoleV4 (size split; same selector at this address, under this
    // bridge's reentrancy lock); it reads `rowsHash` below by a static self-call (T17-SIZE: moved here for EIP-170).

    /// @notice rowsHash of THIS bridge's rows (§11.2.2) for `chains`, `mask`, per-chain tids `chainTids`: computed by
    ///         `rows` (BridgeRowsV4, created in the constructor; T17-SIZE, EIP-170), which reads this bridge's rows by `routeOf`.
    ///         Same selector, same reverts (bubbled).
    function rowsHash(uint32[] calldata chains, uint16 mask, uint128 chainTids) external view returns (bytes32) {
        return rows.rowsHash(chains, mask, chainTids);
    }

    // ================================================================== send

    function send(SendArgs calldata a, Sig.SignedGapPrice calldata gp) external payable nonReentrant returns (bytes32 msgId) {
        (Coin storage c, ITransportAdapterV4 adapter) = _route(a);
        IGapOracleV4.Params memory p = oracle.params(a.coinId);
        (uint256 burnLD, uint256 fee, uint64 sd) = _amounts(a.amountLD, p.bridgeFeeBps);
        Codec.Header memory h = _header(a, sd, p.bridgeFeeBps, Codec.MODE_PLAIN);
        if (p.gapOn) _price(h, c.token, gp);
        // B1-L4: the fee moves by transfer; only what crosses is burned. B1-L2: minCredited after the fee.
        if (fee != 0) PangeaCoinV4(c.token).bridgeTransfer(msg.sender, bridgeFeeTo, fee);
        PangeaCoinV4(c.token).bridgeBurn(msg.sender, burnLD - fee);
        if (a.minCreditedLD > uint256(sd) * LD_PER_SD) revert CreditBelowMin(uint256(sd) * LD_PER_SD, a.minCreditedLD);
        if (h.priceSource == Codec.PS_SIGNED) {
            uint256 credited = gap.creditPlain(uint256(sd) * LD_PER_SD, h.psUsdE18, h.p2E18);
            if (credited < a.minCreditedLD) revert CreditBelowMin(credited, a.minCreditedLD);
        }
        msgId = _dispatch(adapter, h, a, msg.value);
        _sent(msgId, h, a, burnLD, fee, gp, msg.value);
    }

    /// @notice Buy-and-bridge (§11.2.6, B1-H3/B1-M1): Panchor is read FIRST (the signed src leg, else the fallback
    ///         reader); then `b.quoteIn` of the official pool's quote buys the coin on THAT pool only (BridgeBuyerV4,
    ///         Pexec from the pool's own deltas); the same-transaction sale lock is set in the coin; Ps = min(Pexec,
    ///         Panchor x (1 + k)); the coins bought are burned (fee by transfer, dust to the caller); mode 1 with the
    ///         cover. ERC-20 quote: approve the bridge for quoteIn; native: msg.value = quoteIn + transport fee.
    ///         G-EVMB-1 M-1 (ruling E, §11.3.5 "never a block"): under the coin's gap escape (gapOn false) nothing is
    ///         priced and nothing refuses: the coins bought cross as a PLAIN unpriced message (credited in full; a
    ///         mode-1 message must carry a price on every chain, Solana's decoder included). OD-A-11 (owner "no
    ///         refusals", D1 RULE-CHECK 1300; replaces lead C2-2's BuyNeedsPrice): with no price at all (no signed
    ///         price, no fallback, or no Ps because the quote has no USD price) the buy crosses the same way.
    function buyAndSend(BuyArgs calldata b, SendArgs calldata a, Sig.SignedGapPrice calldata gp)
        external
        payable
        nonReentrant
        returns (bytes32 msgId, uint256 tokensOut)
    {
        // SIZE-17 TRACK B: `preview` is read at run time (msg.sig), not a literal: the optimizer then keeps ONE copy of
        // _buyAndSend for buyAndSend + gapPreviewBuy (a literal made a specialized ~2.5 KB copy per entry; EIP-170).
        // Same value as before: false in buyAndSend, true in gapPreviewBuy.
        return _buyAndSend(b, a, gp, msg.data[0:0], msg.sig == this.gapPreviewBuy.selector);
    }

    /// @notice A2-ASK-1 (signed price first): buyAndSend with the SIGNED USD price of the coin's quote on this chain
    ///         (`signedQuote` = abi.encode(GapPriceSigV4.QuoteUsdPrice, bytes sig), BridgeGapV4.quoteUsd): Pexec_usd is
    ///         priced from it (where no asset reader prices the quote, e.g. Robinhood). A bad one reverts.
    ///         `preview` true = gapPreviewBuy for this path (reverts GapPreviewBuy(figures), never succeeds). One entry
    ///         for both (EIP-170: each caller of _buyAndSend is a full inlined copy).
    function buyAndSendQuoted(BuyArgs calldata b, SendArgs calldata a, Sig.SignedGapPrice calldata gp, bytes calldata signedQuote, bool preview)
        external
        payable
        nonReentrant
        returns (bytes32 msgId, uint256 tokensOut)
    {
        return _buyAndSend(b, a, gp, signedQuote, preview);
    }

    /// @notice F2-REQ: buyAndSend run to the point of the send, then reverts GapPreviewBuy(figures) (eth_call with the
    ///         same value / approval as the real call). Never succeeds.
    function gapPreviewBuy(BuyArgs calldata b, SendArgs calldata a, Sig.SignedGapPrice calldata gp) external payable nonReentrant {
        // SIZE-17 TRACK B: `preview` is read at run time (msg.sig), not a literal: the optimizer then keeps ONE copy of
        // _buyAndSend for buyAndSend + gapPreviewBuy (a literal made a specialized ~2.5 KB copy per entry; EIP-170).
        // Same value as before: false in buyAndSend, true in gapPreviewBuy.
        _buyAndSend(b, a, gp, msg.data[0:0], msg.sig == this.gapPreviewBuy.selector);
    }

    function _buyAndSend(BuyArgs calldata b, SendArgs calldata a, Sig.SignedGapPrice calldata gp, bytes calldata sq, bool preview)
        internal
        returns (bytes32 msgId, uint256 tokensOut)
    {
        (Coin storage c, ITransportAdapterV4 adapter) = _route(a);
        IGapOracleV4.Params memory p = oracle.params(a.coinId);
        Codec.Header memory h = _header(a, 0, p.bridgeFeeBps, p.gapOn ? Codec.MODE_BUY : Codec.MODE_PLAIN);
        // gate-cheap-erc20 H-1: through this release's composer the sender is the user it names (a.refundTo, where the
        // composer pays every leftover too), so a held arrival's refund (refundHeld: to o.sender) reaches the user, never
        // the composer. Only that composer can name a sender, and such a message never carries a compose (no compose
        // target ever sees a caller-named composeFrom).
        if (msg.sender == _composer) {
            if (a.refundTo == address(0) || a.composeMsg.length != 0) revert ComposerSend();
            h.sender = bytes32(uint256(uint160(a.refundTo)));
        }
        uint256 depth = p.gapOn ? _price(h, c.token, gp) : 0;
        // OD-A-11 (owner "no price => no gap fee, never blocks" / "no refusals"; D1 RULE-CHECK 1300, replaces lead
        // C2-2): with no price at all the buy crosses as the M-1 escape shape (MODE_PLAIN, unpriced, credited in full).
        bool priced = p.gapOn && h.priceSource != Codec.PS_NONE;
        if (!priced) _unpriced(h);
        uint256 quotePaid;
        uint256 transportFee;
        (quotePaid, tokensOut, transportFee) = _buy(c.token, a.coinId, b);
        PangeaCoinV4(c.token).lockSales();
        (uint256 burnLD, uint256 fee, uint64 sd) = _amounts(tokensOut, p.bridgeFeeBps);
        h.amountSD = sd;
        if (a.minCreditedLD > uint256(sd) * LD_PER_SD) revert CreditBelowMin(uint256(sd) * LD_PER_SD, a.minCreditedLD);
        uint256 panchor = h.psUsdE18;
        // B3-M2 (§11.2.6 step 6): the cover is the transport's own quote for THIS message with the ENFORCED options
        // only (+ our keys-only delivery charge), never msg.value; the caller must pay at least it.
        uint256 q = adapter.quote(a.dstPcid, Codec.encode(h, a.composeMsg), "") + _charge(a);
        if (transportFee < q) revert DeliveryFeeUnpaid(transportFee, q);
        uint256 ps;
        uint256 pexecUsd;
        if (priced) {
            uint32 cover;
            (ps, pexecUsd, cover) = gap.buy(a.coinId, _officialPool[a.coinId].quote, quotePaid, tokensOut, panchor, depth, q, sq);
            // OD-A-11: no Ps (the quote has no USD price, or no anchor) -> the same unpriced plain crossing, never a
            // refusal. The header keeps its size, so `q` (quoted on the mode-1 header) is this message's quote too.
            if (ps == 0) {
                _unpriced(h);
            } else {
                h.psUsdE18 = uint128(ps);
                h.coverSrcMicroUsd = cover;
            }
        }
        if (preview) {
            revert GapPreviewBuy(tokensOut, quotePaid, pexecUsd, ps, h.priceSource, panchor, h.p2E18, h.coverSrcMicroUsd, sd, h.bridgeFeePpm);
        }
        if (fee != 0) IERC20(c.token).safeTransfer(bridgeFeeTo, fee);
        PangeaCoinV4(c.token).bridgeBurn(address(this), burnLD - fee);
        if (tokensOut > burnLD) IERC20(c.token).safeTransfer(msg.sender, tokensOut - burnLD); // dust below 6 decimals
        msgId = _dispatch(adapter, h, a, transportFee);
        emit GapBuy(msgId, msg.sender, a.dstPcid, quotePaid, tokensOut, pexecUsd, ps, panchor);
        // G-EVMB-1 I-5: Sent.nativeFee = what paid the transport (+ our delivery charge), never the native quote
        _sent(msgId, h, a, tokensOut, fee, gp, transportFee);
    }

    // ================================================================== receive

    /// @dev `executor`: the LZ executor (lzReceive's caller) / the Hyperlane relayer (tx.origin of process). B1-M3
    ///      (HL-3, HL1-M1, §11.2.14 keys-only): a BUY-mode arrival (its credit depends on this chain's pool at the
    ///      moment of delivery) lands at once only when a delivery key delivers it (oracle.isDeliveryKey: our keys,
    ///      incl. our Hyperlane relayer key); from anyone else it is stored (held, reason 3) and released by a delivery
    ///      key at once or by anyone once oracle.exclusiveWindowSec() has passed. Plain arrivals: anyone, at once.
    function receiveFromTransport(uint32 srcPcid, bytes32 srcPeer, bytes calldata message, bytes32 transportMsgId, address executor)
        external
        nonReentrant
    {
        if (message.length < 3) revert Codec.BadMessage(1);
        uint8 tid = uint8(message[2]);
        if (msg.sender != adapterOf[tid] || msg.sender == address(0)) revert NotAdapter();
        Route storage r = _routes[srcPcid][tid];
        if (r.peer == bytes32(0) || r.peer != srcPeer) revert WrongPeer();
        (Codec.Header memory h, bytes calldata tail) = Codec.decode(message);
        if (h.srcPcid != srcPcid || h.dstPcid != localPcid || srcPcid == localPcid) revert WrongChain();
        bytes32 id = Codec.msgId(tid, transportMsgId);
        if (consumed[id]) revert AlreadyConsumed(id);
        consumed[id] = true;

        Coin storage c = _coins[h.coinId];
        if (c.token == address(0) && (h.mode == Codec.MODE_OPEN_AUTH || h.mode == Codec.MODE_ROLE)) {
            _storeOpenAuth(keccak256(abi.encode(h.coinId, srcPcid, tid)), h.coinId, tail, h.mode == Codec.MODE_OPEN_AUTH, h.recipient);
            return;
        }
        if (h.mode == Codec.MODE_OPEN_AUTH) return; // open here: an authorisation has nothing left to do
        if (c.token == address(0)) {
            _hold(id, h.coinId, srcPcid, 1, message);
            return;
        }
        _checkListed(c, srcPcid, tid);
        if (h.mode == Codec.MODE_ROLE) {
            _applyRole(c, h.coinId, Codec.decodeRole(tail), 2);
            return;
        }
        if (h.mode == Codec.MODE_BUY && !oracle.isDeliveryKey(executor)) {
            _hold(id, h.coinId, srcPcid, 3, message);
            return;
        }
        _arriveMem(id, h, tail, c, srcPcid, message, uint64(block.timestamp));
    }

    /// @notice The recipient's consent to land `msgId` below its minCredited (then releaseHeld).
    function acceptBelowMin(bytes32 msgId) external {
        acceptedBelowMin[msgId][msg.sender] = true;
        emit AcceptedBelowMin(msgId, msg.sender);
    }

    /// @notice Anyone: re-runs a HELD arrival (the coin is open here now / the recipient consented). G-EVMB-1 L-1: an
    ///         arrival held again (still below minCredited) keeps its FIRST heldAt, so no third party can push back
    ///         the original sender's refund window.
    function releaseHeld(bytes32 msgId) external nonReentrant {
        HeldArrival memory hd = _held[msgId];
        if (hd.message.length == 0) revert NotHeld();
        (Codec.Header memory h, bytes memory tail) = this.decodeView(hd.message);
        Coin storage c = _coins[h.coinId];
        if (c.token == address(0)) revert HeldNotReleasable();
        _checkListed(c, hd.srcPcid, h.transportId);
        if (h.mode == Codec.MODE_BUY && !oracle.isDeliveryKey(msg.sender)) {
            uint64 openAt = hd.heldAt + oracle.exclusiveWindowSec();
            if (block.timestamp < openAt) revert DeliveryWindow(openAt);
        }
        delete _held[msgId];
        emit HeldReleased(msgId);
        _arriveMem(msgId, h, tail, c, hd.srcPcid, hd.message, hd.heldAt);
    }

    /// @dev Calldata view of a stored message (decode works on calldata only).
    function decodeView(bytes calldata m) external pure returns (Codec.Header memory h, bytes memory tail) {
        return Codec.decode(m);
    }


    // ================================================================== internals

    function _checkListed(Coin storage c, uint32 srcPcid, uint8 tid) internal view {
        _checkPair(c, srcPcid, tid); // T17-FIX: the route's creation-bound tids, not the mask
    }




    /// @dev For a coin not open here: a mode-3 sets (opener, deadline); both modes raise the stored role when their
    ///      roleNonce is higher (B2-L1: a handover after the authorisation reaches the open).
    /// META-OPENLATER: `uriHash` = a mode 3's header recipient (keccak256 of the home coin's metadataURI).
    function _storeOpenAuth(bytes32 key, bytes32 coinId, bytes calldata t, bool auth, bytes32 uriHash) internal {
        Codec.Role memory r = Codec.decodeRole(auth ? t[40:113] : t);
        OpenAuth storage a = _openAuth[key];
        uint64 issued = auth ? uint64(bytes8(t[113:121])) : 0;
        // B3-L1: never from an authorisation older than the stored role; B4-I1: under the same role only a NEWER
        // issuedAt replaces the stored one (unordered transports: a late older authorisation never wins)
        if (auth && r.roleNonce >= a.roleNonce && (r.roleNonce > a.roleNonce || issued > a.issuedAt)) {
            uint64 dl = uint64(bytes8(t[32:40]));
            uint64 cap = uint64(block.timestamp) + MAX_OPEN_AUTH; // deadline at most 7 days from arrival
            (a.opener, a.deadline, a.issuedAt) = (bytes32(t[0:32]), dl > cap ? cap : dl, issued);
            a.uriHash = uriHash; // META-OPENLATER: the home URI's hash at authorizeOpen
            emit OpenAuthReceived(coinId, a.opener, a.deadline);
        }
        if (r.roleNonce > a.roleNonce) {
            (a.creatorEvm, a.creatorSvm, a.roleNonce, a.renounced) = (r.creatorEvm, r.creatorSvm, r.roleNonce, r.renounced);
            // B3-L1: a newer role voids the opener authorised under an older one (B4-I1: and its issuedAt, so the new
            // role's first authorisation is stored whatever its timestamp)
            if (!auth) (a.opener, a.issuedAt, a.uriHash) = (bytes32(0), 0, bytes32(0));
        } else if (!auth) {
            emit RoleMirrorStale(coinId, r.roleNonce);
        }
    }


    function _hold(bytes32 id, bytes32 coinId, uint32 srcPcid, uint8 reason, bytes memory message) internal {
        _holdAt(id, coinId, srcPcid, reason, message, uint64(block.timestamp));
    }

    function _holdAt(bytes32 id, bytes32 coinId, uint32 srcPcid, uint8 reason, bytes memory message, uint64 heldAt) internal {
        _held[id] = HeldArrival(srcPcid, reason, heldAt, message);
        emit Held(id, coinId, reason);
    }

    /// @dev §11.3.2 (BridgeGapV4): a provided signature is verified or the call reverts; none -> the fallback
    ///      reader; else none. Returns the source depth (for k).
    /// @dev OD-A-11: a buy with no price crosses as a plain, unpriced message (the M-1 escape shape; codec rule 5:
    ///      PS_NONE carries no psUsd / p2, and a plain message no cover).
    function _unpriced(Codec.Header memory h) internal pure {
        h.mode = Codec.MODE_PLAIN;
        h.priceSource = Codec.PS_NONE;
        h.psUsdE18 = 0;
        h.p2E18 = 0;
        h.coverSrcMicroUsd = 0;
    }

    function _price(Codec.Header memory h, address token, Sig.SignedGapPrice calldata gp) internal view returns (uint256 depth) {
        (h.priceSource, h.psUsdE18, h.p2E18, depth) = gap.sourcePrice(gp, h.coinId, localPcid, h.dstPcid, token);
    }

    /// @dev A-D8: toward a keys-only (dstPcid, tid) the send's native `value` first carries our delivery charge
    ///      (oracle.deliveryCharge, paid to its recipient after the transport send); the adapter gets the rest. The
    ///      buy cover counts the whole `value` (transport + this charge: the figure charged is the figure covered).
    function _charge(SendArgs calldata a) internal view returns (uint256 d) {
        (d,) = _deliveryCharge(oracle, a.dstPcid, a.transportId);
    }

    function _dispatch(ITransportAdapterV4 adapter, Codec.Header memory h, SendArgs calldata a, uint256 value) internal returns (bytes32 id) {
        (uint256 d, address to) = _deliveryCharge(oracle, a.dstPcid, a.transportId);
        if (value < d) revert DeliveryFeeUnpaid(value, d);
        bytes32 t = adapter.send{value: value - d}(a.dstPcid, Codec.encode(h, a.composeMsg), a.extraOptions, a.refundTo == address(0) ? msg.sender : a.refundTo);
        id = Codec.msgId(a.transportId, t);
        if (d != 0) {
            (bool ok,) = to.call{value: d}("");
            if (!ok) revert DeliveryPayFailed(to);
            emit DeliveryPaid(id, a.dstPcid, a.transportId, to, d);
        }
    }

    function _sent(bytes32 msgId, Codec.Header memory h, SendArgs calldata a, uint256 amountLD, uint256 fee, Sig.SignedGapPrice calldata gp, uint256 nativeFee)
        internal
    {
        emit Sent(msgId, a.coinId, msg.sender, a.dstPcid, a.transportId, h.mode, amountLD, h.amountSD, a.recipient, h.priceSource, h.psUsdE18, h.p2E18, fee, nativeFee);
        if (h.priceSource == Codec.PS_SIGNED) {
            emit GapPriceUsed(msgId, gp.p.keyId, gp.p.observedAt, gp.p.src.pool, gp.p.dst.pool, gp.p.src.blockOrSlot, gp.p.dst.blockOrSlot);
        }
    }

    /// @dev `heldAt`: now for a fresh arrival; the stored heldAt for a released one (G-EVMB-1 L-1).
    function _arriveMem(bytes32 id, Codec.Header memory h, bytes memory tail, Coin storage c, uint32 srcPcid, bytes memory message, uint64 heldAt)
        internal
    {
        address to = uint256(h.recipient) >> 160 == 0 && h.recipient != bytes32(0) ? address(uint160(uint256(h.recipient))) : DEAD;
        uint256 a = uint256(h.amountSD) * LD_PER_SD;
        uint256 credited = h.mode == Codec.MODE_REFUND ? a : gap.credit(h, c.token, a);
        if (credited > a) credited = a;
        uint256 minLD = uint256(h.minCreditedSD) * LD_PER_SD;
        if (credited < minLD && !acceptedBelowMin[id][to]) {
            _holdAt(id, h.coinId, srcPcid, 2, message, heldAt);
            return;
        }
        // B1-M4: a composed arrival is minted FIRST (to the bridge), its compose STORED, then tried once inline; a
        // failure (incl. a deliverer's gas starvation) leaves it retryable by anyone (retryCompose); after
        // COMPOSE_WINDOW anyone may hand the tokens to the recipient without the call (releaseCompose).
        bool composed = tail.length != 0 && h.mode <= Codec.MODE_BUY && to.code.length != 0;
        if (credited != 0) PangeaCoinV4(c.token).bridgeMint(composed ? address(this) : to, credited);
        emit Received(id, h.coinId, to, srcPcid, h.transportId, h.mode, h.amountSD, credited, a - credited, h.priceSource);
        if (composed) {
            pendingCompose[id] = PendingCompose(
                keccak256(abi.encode(id, h.coinId, srcPcid, h.sender, to, credited, tail)), uint64(block.timestamp) + COMPOSE_WINDOW
            );
            emit ComposeStored(id, h.coinId, to, srcPcid, h.sender, credited, tail);
            uint256 g = gasleft();
            g = g > COMPOSE_RESERVE_GAS ? g - COMPOSE_RESERVE_GAS : 0;
            try IComposeExecV4(address(this)).composeExec{gas: g}(id, h.coinId, srcPcid, h.sender, to, credited, tail) {}
            catch {
                emit ComposeFailed(id, to, ""); // B3-I1: the composer's revert data is never copied (returndata bomb)
            }
        }
    }

    function _buy(address token, bytes32 coinId, BuyArgs calldata b) internal returns (uint256 quotePaid, uint256 out, uint256 transportFee) {
        OfficialPool memory op = _officialPool[coinId];
        if (b.quoteIn == 0 || op.hook == address(0)) revert BadAmount();
        if (op.quote == address(0)) {
            if (msg.value < b.quoteIn) revert BuyValue();
            transportFee = msg.value - b.quoteIn;
        } else {
            transportFee = msg.value;
            IERC20(op.quote).safeTransferFrom(msg.sender, address(buyer), b.quoteIn);
        }
        uint256 bal = IERC20(token).balanceOf(address(this));
        (quotePaid,) = buyer.buy{value: op.quote == address(0) ? b.quoteIn : 0}(
            buyer.keyOf(token, op.quote, op.lpFee, op.tickSpacing, op.hook), token, b.quoteIn, msg.sender
        );
        out = IERC20(token).balanceOf(address(this)) - bal;
        if (out == 0 || out < b.minTokensOut) revert BuySlippage(out, b.minTokensOut);
    }
}
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.