Verified contractExactUNLICENSED
PangeaFastBridgeV3
Address0x9c385c829e751d2ab9bca17233f0357da7607aa4
- Balance
0 ETH
- Transactions
11
- 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,328,617
- Creation transaction
- 0xb61e7dc0f3…66349bcd0a
27 files
- src/v3/PangeaFastBridgeV3.solmain70.68 KB
- lib/layerzero/oapp-evm/contracts/oapp/OAppCore.sol3.36 KB
- lib/layerzero/oapp-evm/contracts/oapp/OAppSender.sol5.63 KB
- lib/layerzero/oapp-evm/contracts/oapp/interfaces/IOAppComposer.sol427 B
- lib/layerzero/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol1.86 KB
- lib/layerzero/oft-evm/contracts/interfaces/IOFT.sol6.28 KB
- lib/layerzero/oft-evm/contracts/libs/OFTComposeMsgCodec.sol2.99 KB
- lib/layerzero/protocol-v2/contracts/interfaces/ILayerZeroComposer.sol1.05 KB
- lib/layerzero/protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol2.59 KB
- lib/layerzero/protocol-v2/contracts/interfaces/IMessageLibManager.sol2.76 KB
- lib/layerzero/protocol-v2/contracts/interfaces/IMessagingChannel.sol1.54 KB
- lib/layerzero/protocol-v2/contracts/interfaces/IMessagingComposer.sol1.03 KB
- lib/layerzero/protocol-v2/contracts/interfaces/IMessagingContext.sol239 B
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.06 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.07 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- src/v3/SolanaPda.sol3.73 KB
- src/v3/gap/IPangeaOFTV3Gap.sol5.77 KB
src/v3/PangeaFastBridgeV3.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 {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IOAppComposer} from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppComposer.sol";
import {OFTComposeMsgCodec} from "@layerzerolabs/oft-evm/contracts/libs/OFTComposeMsgCodec.sol";
import {SendParam, MessagingFee, MessagingReceipt, IOFT, OFTReceipt} from
"@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol";
import {IPangeaOFTV3Gap} from "./gap/IPangeaOFTV3Gap.sol";
import {SolanaPda} from "./SolanaPda.sol";
/// @dev The v3c gap surface this bridge reads (_v3/gapcost/BRIEF-common.md interface contract,
/// SPEC-gap-v3c.md §1, §4): exactly what a v3 token's send now carries, and its receive's code
/// path as a view. Declared here, to the contract's signatures, until IPangeaOFTV3Gap carries
/// them (the token answers both through its gap module; the selectors are the same either way).
interface IPangeaOFTV3GapQuote {
/// @notice What a send of `amountSD` (net of the bridge fee) to `dstEid` now carries in its
/// codec v3 header; feeSrcPpm holds costPpm. Reverts like the send (GapSourceUnreadable,
/// GapNoOfficialPool, GapGasTooLow).
function gapSendQuote(uint32 dstEid, uint64 amountSD)
external
view
returns (
uint128 psE18,
uint32 feeSrcPpm,
uint32 bridgeFeePpm,
uint8 priceClass,
uint128 psClassE18,
uint32 srcGasMicroUsd,
uint16 srcCoverCapCents
);
/// @notice The receive's code path as a view (AMENDMENT 6: the source's gas cover srcGasMicroUsd /
/// srcCoverCapCents, the destination's own swap gas and fixed margin). `holds` = the receive would revert retriably
/// (GapNoPool / GapUnreadable, `reason` says which); withheld and credited are then 0.
function gapPreview(
uint128 psE18,
uint32 feeSrcPpm,
uint32 bridgeFeePpm,
uint8 priceClass,
uint128 psClassE18,
uint32 srcGasMicroUsd,
uint16 srcCoverCapCents,
uint256 amountLD
)
external
view
returns (
uint256 withheldLD,
uint256 creditedLD,
uint256 pdE18,
uint32 gapPpm,
uint64 allowPpm,
uint8 reason,
bool holds
);
}
/// @dev The OFT's LD per shared unit (OFTCore's public immutable).
/// @dev E6 (audit round 1 I-2): the token's enforced options (OAppOptionsType3).
interface IEnforcedOptionsV3 {
function enforcedOptions(uint32 eid, uint16 msgType) external view returns (bytes memory);
}
interface IOFTRateV3 {
function decimalConversionRate() external view returns (uint256);
}
/// @dev Arbitrum's system precompile, at 0x64 on every Arbitrum chain.
interface IArbSysV3 {
function arbBlockNumber() external view returns (uint256);
}
/// @dev What this contract asks of the endpoint besides delivering to it.
interface IEndpointStateV3 {
function eid() external view returns (uint32);
function inboundPayloadHash(address receiver, uint32 srcEid, bytes32 sender, uint64 nonce)
external
view
returns (bytes32);
function lazyInboundNonce(address receiver, uint32 srcEid, bytes32 sender) external view returns (uint64);
}
/// @dev eth-fallback-fix (r1 M-1): the source registry's keys-only delivery view (src/v3/gap/IGapDelivery.sol
/// `deliveryCharge`, the one the token's own combineOptions / quoteSend / send read). A non-zero cost
/// toward `dstEid` = the destination is KEYS-ONLY (only our delivery keys deliver; LayerZero's executor
/// cannot). Declared here by selector so this file needs nothing of the registry's source.
interface IGapDeliveryChargeV3 {
function deliveryCharge(uint32 dstEid) external view returns (uint256 costWei, address to);
}
interface IBridgeFeeRecipientV3 {
function bridgeFeeTo() external view returns (address);
}
interface IOAppPeersV3 {
function peers(uint32 eid) external view returns (bytes32);
}
/// @dev A launch factory's record of what it launched (v2's getter, kept by v3).
interface ILaunchRegistryV3 {
function launches(bytes32 launchId)
external
view
returns (address token, address splitter, address launchOwner, address locker, uint128 liquidity);
}
/// @title PangeaFastBridgeV3
/// @notice The fast bridge for v3 (gap-fee) tokens: `PangeaFastBridge`'s order book, ids and
/// settlement, with the one change a gap fee forces (docs/v3-gap-fee-spec.md §4, §8, Q4).
/// v1/v2 tokens stay on `PangeaFastBridge`, which is unchanged; this contract serves ONLY
/// v3 tokens (a listed factory's token that answers `gapRegistry() != 0`).
///
/// ## Why a V3 bridge
///
/// A v3 destination withholds the price gap from what it mints (`credited = gross - withheld`), and
/// the compose it queues carries `amountLD = credited`. `PangeaFastBridge` hashes the compose's
/// amount into the order id, so the id of a charged arrival would differ from the one the sender
/// posted and the relayer filled: the relayer would never be repaid. Here the id is computed from
/// the GROSS amount, `credited + gapWithheld(guid)` read from the token that minted -- exactly what
/// the source's `quoteOFT` promised and the order hashed -- and the payout is what actually arrived.
///
/// ## Who bears the gap (owner decision (b), 2026-10-28)
///
/// Whoever fronted the user's gross order ON TIME bears it: a relayer whose fill EARNED is repaid
/// `credited`. Otherwise the recipient bears it, as on the slow bridge: an unfilled order, or a
/// fill that did not earn (made in the settling block, or naming another message), leaves the
/// recipient with `credited` in total, and the relayer is made whole out of what arrived. A fill
/// pays the recipient `amount - relayerFee` (the gross order less the fee) at once, so an earned
/// relayer nets `relayerFee - withheld` and must price the gap before it fronts an order:
/// `previewFill` runs the destination token's own `gapPreview` (the receive's code path, as a view)
/// with the header the source sent (`OrderGapQuote` on an EVM source; the packet's message bytes
/// 41..96 from Solana, codec v3). The price may still move before the message lands; that is the relayer's risk,
/// as the fill itself is -- and it can be MADE to move (audit H-1, 2026-10-28): Pd is the HIGHER of
/// the official pool's last two recorded closes (each the last swap of an earlier block with a
/// swap; never the live price), so a lift inside one transaction does not move it, but anyone may
/// lift the pool, hold it to the end of one block so that block's close records it, then run the
/// message's `lzReceive` themselves in a later block and sell back. Pd then sees the lift, the receive withholds up to all
/// of it above the allowance, and an earned fill is repaid only that `credited`: the relayer can
/// lose most of an order for the pool's fee on the round trip. `previewFill` cannot see this
/// coming. Relayers must cap each fronted order by what such a pump would cost on that pool (its
/// depth and fee) and bound what they have in flight (script/fastbridge/v3-front-cap.mjs does
/// both for ours).
///
/// With G = gross, F = relayerFee, W = withheld, C = G - W (credited), P = G - F (what a fill paid):
///
/// case relayer repaid recipient at settlement recipient in total
/// unfilled - C C
/// filled, earned C 0 P
/// filled, not earned, W <= F P (made whole) F - W C
/// filled, not earned, W > F C (< P) 0 P (C < P < G)
/// same order arriving again - C of that message + its own mint
/// unpayable `to` - C held for `refund` -
/// C < minCredited (M) nothing yet: the receive REVERTS (retriable) and the message
/// waits in the endpoint; a later try at a better price lands it
/// (then one of the rows above), never with less than M
/// fill after arrival refused (TooLateToFill) -- "arrival" is the message VERIFIED,
/// so an order whose receive is reverting can no longer be filled;
/// after settlement (AlreadySettled); twice (AlreadyFilled).
/// Partial fills do not exist: a fill pays P.
///
/// The last "not earned" row is the one place a relayer that did not earn is out of pocket: the
/// recipient already holds P > C from its fill and nothing can take it back, so only C is there to
/// repay it. Every settlement pays out exactly C, this message's own mint: nothing is double-paid
/// and nothing stays here.
///
/// OWNER-APPROVED (2026-10-28), both edge cases as built: a fill that did not earn with W > F
/// costs its relayer W - F (it gets C, having paid out P); an earned fill with F > W leaves the
/// recipient with P, less than C (the fee the sender chose to pay for speed).
///
/// ## The least credited amount (owner, 2026-10-28)
///
/// Every order names `minCredited` (M): the least the destination may credit. It is in the order
/// id (so no fill or settlement can name another), in the payload (so the destination can rebuild
/// that id) and in the gap message's header (`SendParam.oftCmd = abi.encode(M)`, codec v3), where the
/// destination token enforces it: `credited < M` reverts the receive (`GapCreditBelowMin`), and the
/// message stays in the endpoint to be retried -- the H-1 pump above can then only DELAY an
/// order, not take it, and an earned fill is repaid at least M (it nets at least M - P). Nothing is
/// paid twice: the receive either lands once (one compose, one settlement) or not at all; a fill
/// made before the message was verified waits with it. M = 0 is no minimum. Our senders set M at
/// the request's slippage (else 1%, at most 20%) under what they expect credited
/// (web/lib/trade/min-credited.mjs). A refund carries no minimum: it always lands.
///
/// ## Toward Solana
///
/// A v3 Solana store makes no LayerZero compose: `lz_receive` writes a `GapReceipt`
/// (PDA ["GapReceipt", guid], spec §10.5) that the Solana fast bridge consumes and closes. Its rent
/// (`259 + len` bytes; `SOLANA_RECEIPT_RENT` for this bridge's 120-byte packed payload) is paid ONCE,
/// in the token's L4 prepay P (owner Q60): the token's quoteSend / send charge P for every composed
/// send into Solana, our delivery key funds it in the receive. So no lzReceive VALUE rides an order
/// toward Solana: this bridge adds compute units only and `setGasLimits` refuses a value there
/// (`SolanaValueRefused`). From Solana a v3
/// order carries 76 bytes (`SOLANA_ORDER_PAYLOAD_LEN`: no sender, the composeFrom is it). The payload toward
/// Solana is the PACKED form (`launchId 32 | sender 32 | senderNonce 8 | to 32 | relayerFee 8 |
/// minCredited 8`), which the Solana program decodes (a 248-byte gap message -- the codec v3 header 96 + composeFrom 32 + 120 -- under the v3 tokens'
/// 256-byte executor cap toward Solana; six ABI words would make 297); the order id is the ABI hash
/// either way.
///
/// The order also prepays what settling it costs on Solana (audit r1 I-1): `SOLANA_ORDER_RENT_DROP`
/// lamports -- its Fill tombstone's rent and the recipient's token account's -- on the order's own
/// Fill PDA, `PDA(["fill", order id])` under the Solana fast bridge (`solanaFillAddress`, Solana's
/// find_program_address done here). The program makes the tombstone out of it and pays the
/// account's part back to whoever made the account (else to the recipient), so whoever settles pays
/// no rent net. eth-fallback Q37 (owner, main 2026-10-31): a priced v3 order into Solana is delivered
/// by OUR delivery key, so the drop is no longer an LZ lzNativeDrop (LayerZero must not charge it):
/// the user pays it ONCE, here, as `fillDropCostWei` (this chain's native wei, admin-set, bounded,
/// `FillDropCostSet`) to `deliveryFeeTo` (event `OrderFillDropPaid`, which tells our delivery bot
/// the order is funded: it then puts SOLANA_ORDER_RENT_DROP lamports on the Fill PDA itself). It is
/// in `quoteOrder`; an order into Solana with no figure set is refused (FillDropCostUnset).
///
/// ## Routing
///
/// This bridge moves a token between two chains for a user; it is never a leg of the Cheapest
/// chain route. The Cheapest chain route's Solana-far leg is OFF for v3 tokens (owner Q5) and no
/// quote built on this bridge may offer it (script/fastbridge/v3-gap-quote.mjs refuses it).
///
/// Everything else -- ids, accepted remotes, fills, `notYetArrived`, fees, refunds, admin --
/// is `PangeaFastBridge`'s, documented there.
contract PangeaFastBridgeV3 is IOAppComposer, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
address public immutable endpoint;
uint32 public immutable localEid;
bool public immutable arbitrum;
uint256 internal constant ARBSYS_PROBE_GAS = 30_000;
/// @dev The most gas `gapRegistry()` may use when a token is checked for v3: a getter.
uint256 internal constant V3_PROBE_GAS = 30_000;
/// @dev The most gas the registry's `deliveryCharge` read may use (the token's own DELIVERY_READ_GAS).
uint256 internal constant DELIVERY_READ_GAS = 30_000;
uint256 public constant MAX_FACTORIES = 32;
/// @notice The packed payload toward Solana (and from a v3 Solana store's post_order_v3), in bytes.
uint256 public constant PACKED_PAYLOAD_LEN = 120;
/// @notice The ABI payload toward the EVM chains, in bytes: six words.
uint256 public constant PAYLOAD_LEN = 192;
/// @notice A v3 Solana store's order (post_order_v3), in bytes: launchId 32 | senderNonce 8 |
/// to 20 (the EVM address) | relayerFee 8 | minCredited 8, big-endian. The sender is the
/// compose's composeFrom (the send's signer); compact so the fast order, minimum and all,
/// fits one Solana transaction.
uint256 public constant SOLANA_ORDER_PAYLOAD_LEN = 76;
/// @dev Where the order's payload starts in a compose: nonce 8 | srcEid 4 | amountLD 32 |
/// composeFrom 32 (OFTComposeMsgCodec.composeMsg is message[76:]).
uint256 internal constant COMPOSE_MSG_OFFSET = 76;
/// @notice A Solana `GapReceipt` holding a composeMsg of `n` bytes is `RECEIPT_BASE_LEN + n`
/// bytes (spec §10.5: 8 discriminator + 207 fixed fields, composeFrom among them, + 4
/// length): 731 at the 512-byte cap.
uint256 public constant RECEIPT_BASE_LEN = 219;
/// @notice e6-r2fix (lead #5 addendum 2; v3c-oft-l4): the L4 GapReceipt's tail after the composeMsg --
/// prepaid u64 and refund_to Pubkey, 40 bytes: a receipt is 259 + n bytes (solana/client
/// gap-v3.mjs gapReceiptSize).
uint256 public constant RECEIPT_L4_LEN = 40;
/// @notice The longest compose message a v3 token carries to Solana (spec §4).
uint256 public constant MAX_SOLANA_COMPOSE_MSG_LEN = 512;
/// @notice Solana's rent-exempt minimum is (128 + data length) x 6,960 lamports.
uint256 public constant LAMPORTS_PER_BYTE_EXEMPT = 6_960;
uint256 internal constant ACCOUNT_STORAGE_OVERHEAD = 128;
/// @notice The rent of the receipt of this bridge's packed payload (379 bytes with L4's 40-byte tail):
/// 3,528,720 lamports (e6-r2fix, addendum 2: was 3,250,320 for the pre-L4 339 bytes, 278,400
/// short). At the 512-byte cap 6,257,040 (`gapReceiptRent(512)`).
uint256 public constant SOLANA_RECEIPT_RENT =
(ACCOUNT_STORAGE_OVERHEAD + RECEIPT_BASE_LEN + RECEIPT_L4_LEN + PACKED_PAYLOAD_LEN) * LAMPORTS_PER_BYTE_EXEMPT;
/// @notice The Solana fast bridge's Fill (98 bytes) at rent exemption: 1,572,960 lamports.
uint256 public constant SOLANA_FILL_RENT = (ACCOUNT_STORAGE_OVERHEAD + 98) * LAMPORTS_PER_BYTE_EXEMPT;
/// @notice A recipient's Token-2022 account of a launched mint (170 bytes): 2,074,080 lamports.
uint256 public constant SOLANA_ATA_RENT = (ACCOUNT_STORAGE_OVERHEAD + 170) * LAMPORTS_PER_BYTE_EXEMPT;
/// @notice What an order to Solana drops on its Fill PDA (audit r1 I-1): 3,647,040 lamports.
uint256 public constant SOLANA_ORDER_RENT_DROP = SOLANA_FILL_RENT + SOLANA_ATA_RENT;
/// @notice Q37: the most `setFillDropCost` accepts (this chain's native wei): 0.001 ETH (about 8.8x the
/// drop's 3,647,040 lamports at the go-live $93 SOL / $3,000 ETH); on BNB Chain 0.005 BNB.
uint256 public constant FILL_DROP_COST_MAX_WEI = 0.001 ether;
uint256 public constant FILL_DROP_COST_MAX_BNB_WEI = 0.005 ether;
/// @notice The Solana fast bridge program, 7YNA5pg5sxmKxma7XiKDJnpWgyF5VPc7SaqyuzNhqZtw.
bytes32 public constant SOLANA_FASTBRIDGE_PROGRAM = 0x612f0c69d58761cf0ef8831b1b46f2368234f5f9f0b1b110a0ae370e942412a4;
mapping(address => bool) public isFactory;
address[] internal _factories;
address public factoryAdmin;
address public admin;
address public pendingAdmin;
/// @notice Q37: what an order into Solana pays (native wei of this chain) for its Fill PDA's
/// SOLANA_ORDER_RENT_DROP lamports, which our delivery bot puts there (no LayerZero drop).
uint256 public fillDropCostWei;
/// @notice Q37: our delivery fee recipient on this chain (where `fillDropCostWei` is paid).
address public deliveryFeeTo;
/// @notice Our counterpart on `eid`: set ONCE (`setRemoteBridge`). A remote is where every
/// order's tokens are sent, so a re-pointable one would be a key able to redirect user
/// funds. A wrong one is retired in two irreversible steps (audit L-1):
/// `revokeRemoteBridge` (no new orders or quotes to it; its arrivals still settle) and,
/// once nothing is in flight, `stopAcceptingRemoteBridge` (its arrivals are refused).
/// Fixing it means a new FastBridge.
mapping(uint32 => bytes32) public remoteBridge;
/// @notice An accepted source of arrivals: the remote set for `eid`, kept through a revocation
/// and cleared only by `stopAcceptingRemoteBridge`.
mapping(uint32 => mapping(bytes32 => bool)) public isRemoteBridge;
mapping(uint32 => bool) public solanaEverEnabled;
/// @notice `eid`'s remote was revoked: no new orders to it, and it can never be set again here.
mapping(uint32 => bool) public remoteRevoked;
/// @notice The remote `eid` had when it was revoked (what `stopAcceptingRemoteBridge` clears).
mapping(uint32 => bytes32) public revokedRemoteBridge;
/// @notice Arrivals from `eid`'s bridge are refused for good (`stopAcceptingRemoteBridge`).
mapping(uint32 => bool) public acceptStopped;
/// @notice The most lzReceive / lzCompose gas (toward Solana: lzReceive compute units) an eid's
/// limits may ask for.
uint128 public constant MAX_GAS_LIMIT = 1_000_000;
/// @notice The most a launch's (or the default) relayer-fee ceiling may be: 10%, as on Solana.
uint16 public constant MAX_RELAYER_FEE_CAP_BPS = 1000;
/// @notice Toward an EVM chain: lzReceive and lzCompose gas. Toward Solana: lzReceive compute
/// units; `composeGas` is always 0 there (owner Q60: no value, no compose option).
mapping(uint32 => GasLimits) public gasLimits;
struct GasLimits {
uint128 receiveGas;
uint128 composeGas;
}
mapping(address => uint64) public senderNonce;
struct Fill {
address relayer;
uint64 lzNonce;
uint32 blockNumber;
}
mapping(bytes32 => Fill) public fills;
mapping(bytes32 => uint8) public settlement;
uint8 public constant SETTLED_SLOW = 1;
uint8 public constant SETTLED_EARNED = 2;
uint8 public constant SETTLED_FEE_RETURNED = 3;
uint8 public constant SETTLED_REFUNDABLE = 4;
/// @notice Every compose guid this bridge has settled: a guid settles once. The endpoint
/// already delivers a compose once; this holds it on our side too.
mapping(bytes32 => bool) public guidSettled;
struct Refund {
bytes32 orderId;
address oft;
uint32 eid;
bytes32 sender;
uint256 amount;
}
mapping(bytes32 => Refund) public refunds;
uint16 public fastFeeBps = 20;
uint16 public constant MAX_FAST_FEE_BPS = 100;
uint16 public maxRelayerFeeBps = 1000;
struct LaunchFees {
bool set;
uint16 fastFeeBps;
uint16 maxRelayerFeeBps;
}
mapping(bytes32 => LaunchFees) public launchFees;
event OrderPosted(
bytes32 indexed orderId,
bytes32 indexed launchId,
uint32 dstEid,
bytes32 indexed sender,
uint64 senderNonce,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minCredited,
uint64 lzNonce
);
/// @notice The gap header the order's message carries (codec v3, spec §1): the token's
/// `gapSendQuote(dstEid, amountSD)` for this very send, read in the send's own
/// transaction with nothing between that moves a price, so it equals the message's
/// bytes 41..96 (minCreditedSD aside: the order's own), AMENDMENT 6's srcGasMicroUsd (byte 90)
/// and srcCoverCapCents (byte 94) included. What a relayer passes to `previewFill` on the
/// destination.
event OrderGapQuote(
bytes32 indexed orderId,
uint128 psE18,
uint32 feeSrcPpm,
uint32 bridgeFeePpm,
uint8 priceClass,
uint128 psClassE18,
uint32 srcGasMicroUsd,
uint16 srcCoverCapCents
);
event OrderFilled(bytes32 indexed orderId, address indexed relayer, address indexed to, uint256 paid);
event RelayerPaid(bytes32 indexed orderId, address indexed relayer, uint256 amount);
event SettledSlow(bytes32 indexed orderId, address indexed to, uint256 amount);
event FeeReturned(bytes32 indexed orderId, address indexed to, uint256 fee);
/// @notice The destination withheld `withheld` of the order's `gross`: the settlement paid
/// `gross - withheld`.
event GapBorne(bytes32 indexed orderId, bytes32 indexed guid, uint256 gross, uint256 withheld);
event RemoteBridgeSet(uint32 eid, bytes32 bridge);
event RemoteBridgeRevoked(uint32 eid, bytes32 bridge);
event RemoteBridgeStopped(uint32 eid, bytes32 bridge);
event Refundable(bytes32 indexed orderId, bytes32 indexed guid, uint32 srcEid, bytes32 sender, uint256 amount);
event Refunded(bytes32 indexed orderId, bytes32 indexed guid, uint32 dstEid, bytes32 sender, uint256 amount, uint64 lzNonce);
event ArrivedAgain(bytes32 indexed orderId, bytes32 indexed guid, uint256 amount);
event AdminProposed(address indexed from, address indexed to);
event AdminChanged(address indexed from, address indexed to);
event GasLimitsSet(uint32 eid, uint128 receiveGas, uint128 composeGas);
event FastFeeSet(uint16 bps);
event MaxRelayerFeeSet(uint16 bps);
/// @notice Q37: what an order into Solana pays for its Fill PDA's drop (native wei of this chain).
event FillDropCostSet(uint256 costWei);
/// @notice Q37: where that is paid (our delivery fee recipient on this chain).
event DeliveryFeeToSet(address indexed to);
/// @notice Q37: order `orderId` into Solana paid its Fill drop: our delivery bot funds its Fill PDA.
event OrderFillDropPaid(bytes32 indexed orderId, address indexed to, uint256 costWei);
event FactoryAdded(address indexed factory, uint256 index);
event FactoryAdminSet(address indexed previous, address indexed next);
event LaunchFeesSet(bytes32 indexed launchId, bool set, uint16 fastFeeBps, uint16 maxRelayerFeeBps);
error NotAdmin();
error NotPending();
error NotEndpoint();
error NotOurToken(address oApp);
error NotV3Token(address token);
error UnknownLaunch(bytes32 launchId);
error AlreadyFilled();
error AlreadySettled();
error GuidAlreadySettled(bytes32 guid);
error TooLateToFill();
error NoRemote(uint32 eid);
error ZeroAmount();
error ZeroAddress();
error FeeExceedsAmount();
error OrderMismatch();
error NotOurBridge(uint32 srcEid, bytes32 composeFrom);
error NoGasLimits(uint32 eid);
/// @notice Owner Q60: toward Solana this bridge adds lzReceive compute units only, never a value (the
/// GapReceipt's rent is in the token's prepay P).
error SolanaValueRefused(uint128 value);
error ReceivesTooLittle(uint256 receives, uint256 minReceived);
error FastFeeTooHigh(uint16 bps, uint16 max);
error RelayerFeeTooHigh(uint256 relayerFee, uint256 max);
error NotAShare(uint16 bps);
error ValueNotAccepted();
error TooManyFactories();
error ZeroFactory();
error FactoryAlreadyAdded(address factory);
error NotFactoryAdmin();
error BadRecipient(bytes32 to);
error NotARemoteBridge(uint32 eid, bytes32 bridge);
error NothingToRefund();
error TooLargeForSolana(uint256 value);
error BadPayload(uint256 length);
error MinCreditedTooHigh(uint256 minCredited, uint256 amount);
/// @notice The order's amount is more shared units than a gap message's amountSD holds.
error AmountSDOverflow(uint256 amount);
error RemoteAlreadySet(uint32 eid);
error AcceptAlreadyStopped(uint32 eid);
error GasLimitTooHigh(uint128 gas, uint128 max);
error MaxRelayerFeeTooHigh(uint16 bps, uint16 max);
error FillDropCostTooHigh(uint256 costWei, uint256 max);
error FillDropCostUnset();
error FillDropUnpaid(uint256 value, uint256 costWei);
error FillDropPayFailed(address to);
/// @dev An order's compose payload, decoded.
struct Payload {
bytes32 launchId;
bytes32 sender;
uint64 senderNonce;
bytes32 to;
uint256 relayerFee;
uint256 minCredited;
}
constructor(address endpoint_, address admin_) {
if (endpoint_ == address(0) || admin_ == address(0)) revert ZeroAddress();
localEid = IEndpointStateV3(endpoint_).eid();
endpoint = endpoint_;
admin = admin_;
factoryAdmin = admin_;
emit FactoryAdminSet(address(0), admin_);
(bool ok, bytes memory ret) =
address(0x64).staticcall{gas: ARBSYS_PROBE_GAS}(abi.encodeCall(IArbSysV3.arbBlockNumber, ()));
arbitrum = ok && ret.length == 32;
}
function isSolanaEid(uint32 eid) public pure returns (bool) {
return eid == 30168 || eid == 40168;
}
function _b32(address a) internal pure returns (bytes32) {
return bytes32(uint256(uint160(a)));
}
function chainBlockNumber() public view returns (uint256) {
return arbitrum ? IArbSysV3(address(0x64)).arbBlockNumber() : block.number;
}
modifier onlyAdmin() {
if (msg.sender != admin) revert NotAdmin();
_;
}
// ------------------------------------------------------------ which token
/// @notice The token launched under `launchId` on this chain by a listed factory, or zero.
/// Listed is not enough to be served: see `isV3Token`.
function tokenOf(bytes32 launchId) public view returns (address token) {
uint256 n = _factories.length;
for (uint256 i = 0; i < n; i++) {
(token,,,,) = ILaunchRegistryV3(_factories[i]).launches(launchId);
if (token != address(0)) return token;
}
return address(0);
}
/// @notice Whether `token` is a v3 (gap-fee) token: it answers `gapRegistry()` with a nonzero
/// address. A v1/v2 token has no such function (or a contract answering zero) and is
/// refused everywhere here -- it belongs on `PangeaFastBridge`, where its arrival's
/// amount is the whole order.
function isV3Token(address token) public view returns (bool) {
if (token.code.length == 0) return false;
(bool ok, bytes memory ret) =
token.staticcall{gas: V3_PROBE_GAS}(abi.encodeCall(IPangeaOFTV3Gap.gapRegistry, ()));
return ok && ret.length >= 32 && abi.decode(ret, (address)) != address(0);
}
/// @dev The launch's token, listed AND v3, else revert.
function _tokenOf(bytes32 launchId) internal view returns (address token) {
token = tokenOf(launchId);
if (token == address(0)) revert UnknownLaunch(launchId);
if (!isV3Token(token)) revert NotV3Token(token);
}
function feesOf(bytes32 launchId) public view returns (uint16 fastBps, uint16 maxRelayerBps) {
LaunchFees memory f = launchFees[launchId];
return f.set ? (f.fastFeeBps, f.maxRelayerFeeBps) : (fastFeeBps, maxRelayerFeeBps);
}
// ------------------------------------------------------------ ids and quotes
/// @notice An order's id. `amount` is the GROSS arriving amount: what the source's `quoteOFT`
/// says arrives, before any gap fee; on the destination `credited + gapWithheld(guid)`.
/// `minCredited` is the order's least credited amount (the gap header's).
function orderId(
uint32 srcEid,
bytes32 srcBridge,
bytes32 launchId,
bytes32 sender,
uint64 senderNonce_,
uint32 dstEid,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minCredited
) public pure returns (bytes32) {
return keccak256(
abi.encode(srcEid, srcBridge, launchId, sender, senderNonce_, dstEid, to, amount, relayerFee, minCredited)
);
}
/// @notice A Solana `GapReceipt`'s rent, in lamports, for a composeMsg of `composeLen` bytes.
function gapReceiptRent(uint256 composeLen) public pure returns (uint256) {
return (ACCOUNT_STORAGE_OVERHEAD + RECEIPT_BASE_LEN + RECEIPT_L4_LEN + composeLen) * LAMPORTS_PER_BYTE_EXEMPT;
}
/// @notice The executor options a settlement needs. Toward an EVM chain: lzReceive and lzCompose
/// gas. Toward Solana: lzReceive compute units only -- owner Q60: no value (the GapReceipt's
/// rent is paid once, in the token's prepay P; the token's own enforced SEND_AND_CALL value
/// is the route's token-account rent).
function optionsFor(uint32 dstEid) public view returns (bytes memory) {
GasLimits memory g = gasLimits[dstEid];
if (isSolanaEid(dstEid)) {
if (g.receiveGas == 0) revert NoGasLimits(dstEid);
return abi.encodePacked(uint16(3), uint8(1), uint16(17), uint8(1), g.receiveGas);
}
if (g.receiveGas == 0 || g.composeGas == 0) revert NoGasLimits(dstEid);
return abi.encodePacked(
uint16(3),
uint8(1), uint16(17), uint8(1), g.receiveGas,
uint8(1), uint16(19), uint8(3), uint16(0), g.composeGas
);
}
/// @notice An order's Fill PDA on Solana, `PDA(["fill", id])` under `SOLANA_FASTBRIDGE_PROGRAM`,
/// and its bump. Reverts `SolanaPda.NoPdaBump` past 16 bumps (odds 2^-16).
function solanaFillAddress(bytes32 id) public view returns (bytes32 fill, uint8 bump) {
return SolanaPda.findProgramAddress("fill", id, SOLANA_FASTBRIDGE_PROGRAM);
}
/// @notice The options of order `id`'s send of token `oft`: `optionsForToken(dstEid, oft)` (E6: the
/// receipt's rent paid once). Q37 (owner, main 2026-10-31): NO LayerZero native drop toward
/// Solana any more -- the Fill PDA's drop is paid to our delivery path (`fillDropCostWei`),
/// so LayerZero never also charges it. `id` is kept for the ABI (the order's options).
function optionsForOrder(uint32 dstEid, bytes32 id, address oft) public view returns (bytes memory) {
id;
return optionsForToken(dstEid, oft);
}
/// @notice Q37: what an order toward `dstEid` pays our delivery path on top of LayerZero's fee:
/// `fillDropCostWei` toward Solana (refused while unset: FillDropCostUnset), 0 elsewhere.
function fillDropCostOf(uint32 dstEid) public view returns (uint256) {
if (!isSolanaEid(dstEid)) return 0;
uint256 c = fillDropCostWei;
if (c == 0) revert FillDropCostUnset();
return c;
}
/// @notice Q37: the most `setFillDropCost` accepts on this chain.
function fillDropCostMax() public view returns (uint256) {
return block.chainid == 56 || block.chainid == 97 ? FILL_DROP_COST_MAX_BNB_WEI : FILL_DROP_COST_MAX_WEI;
}
/// @notice E6 (audit round 1 I-2): the options an order of `oft` toward `dstEid` carries. Toward
/// Solana the receipt's rent is paid ONCE (owner Q60: in the token's prepay P, which its
/// quoteSend / send charge for this composed send): compute units only, no value.
/// eth-fallback-fix (r1 M-1): toward a KEYS-ONLY EVM destination (`keysOnlyFor(oft, dstEid, 2)`:
/// Ethereum while the source registry charges our delivery) only our keys deliver, and the
/// user already pays that delivery to us; the token itself puts LayerZero's MINIMAL lzReceive
/// option (gas 1) in place of its floor. This bridge then adds NO lzReceive gas of its own
/// (LayerZero's executor could never use it): the lzCompose option only.
function optionsForToken(uint32 dstEid, address oft) public view returns (bytes memory) {
if (!isSolanaEid(dstEid)) {
if (!keysOnlyFor(oft, dstEid, 2)) return optionsFor(dstEid);
uint128 compose = gasLimits[dstEid].composeGas;
if (compose == 0) revert NoGasLimits(dstEid);
return abi.encodePacked(uint16(3), uint8(1), uint16(19), uint8(3), uint16(0), compose);
}
return optionsFor(dstEid);
}
/// @notice eth-fallback-fix (r1 M-1): whether a send of `oft` toward the EVM eid `dstEid` with message
/// type `msgType` (1 SEND: a refund; 2 SEND_AND_CALL: an order) goes to a KEYS-ONLY destination,
/// where the token's own enforced option is already LayerZero's minimal lzReceive (gas 1) and
/// any lzReceive gas this bridge added would be paid to LayerZero for a delivery it cannot make.
/// True exactly when the token's own `combineOptions` swaps its floor for the minimal option:
/// its registry (`gapRegistry()`) answers `deliveryCharge(dstEid)` with a non-zero cost AND the
/// token enforces options for (`dstEid`, `msgType`). False toward Solana and on anything
/// unreadable: the bridge then adds its own gas as before (never a send with no lzReceive
/// option at all), and the token's own send refuses an unreadable registry (DeliveryUnreadable).
function keysOnlyFor(address oft, uint32 dstEid, uint16 msgType) public view returns (bool) {
if (isSolanaEid(dstEid) || oft.code.length == 0) return false;
(bool ok, bytes memory ret) =
oft.staticcall{gas: V3_PROBE_GAS}(abi.encodeCall(IPangeaOFTV3Gap.gapRegistry, ()));
if (!ok || ret.length < 32) return false;
address reg = address(uint160(uint256(bytes32(ret))));
if (reg.code.length == 0) return false;
(ok, ret) = reg.staticcall{gas: DELIVERY_READ_GAS}(
abi.encodeCall(IGapDeliveryChargeV3.deliveryCharge, (dstEid))
);
if (!ok || ret.length != 64 || uint256(bytes32(ret)) == 0) return false;
(ok, ret) =
oft.staticcall{gas: V3_PROBE_GAS}(abi.encodeCall(IEnforcedOptionsV3.enforcedOptions, (dstEid, msgType)));
if (!ok || ret.length < 64) return false;
return abi.decode(ret, (bytes)).length != 0;
}
function fastFeeOf(bytes32 launchId, uint256 amount) public view returns (uint256) {
(uint16 bps,) = feesOf(launchId);
return (amount * bps) / 10_000;
}
/// @notice The GROSS amount of `amount` that arrives on `dstEid`: less this bridge's fee, the
/// token's bridge fee and dust, before the destination's gap fee (which the relayer of
/// a fill bears, and the recipient of an unfilled order).
function arrivingOf(bytes32 launchId, uint32 dstEid, uint256 amount) public view returns (uint256) {
IOFT oft = IOFT(_tokenOf(launchId));
(,, OFTReceipt memory receipt) = oft.quoteOFT(
SendParam({
dstEid: dstEid,
to: remoteBridge[dstEid],
amountLD: amount - fastFeeOf(launchId, amount),
minAmountLD: 0,
extraOptions: "",
composeMsg: "",
oftCmd: ""
})
);
return receipt.amountReceivedLD;
}
/// @notice The compose payload an order carries: six ABI words toward an EVM chain, packed
/// toward Solana (smaller receipt, less rent; under the 256-byte message cap there).
function payloadFor(
uint32 dstEid,
bytes32 launchId,
bytes32 sender,
uint64 n,
bytes32 to,
uint256 relayerFee,
uint256 minCredited
) public pure returns (bytes memory) {
if (isSolanaEid(dstEid)) {
if (relayerFee > type(uint64).max) revert TooLargeForSolana(relayerFee);
if (minCredited > type(uint64).max) revert TooLargeForSolana(minCredited);
return abi.encodePacked(launchId, sender, n, to, uint64(relayerFee), uint64(minCredited));
}
return abi.encode(launchId, sender, n, to, relayerFee, minCredited);
}
/// @notice An order's compose payload, any of its three forms: the 192 bytes of ABI words (an EVM
/// chain's order, what this bridge sends toward an EVM chain); the PACKED 120 bytes
/// (launchId 32 | sender 32 | senderNonce 8 | to 32 | relayerFee 8 | minCredited 8,
/// big-endian: what this bridge sends toward Solana); or the 76 bytes of a v3 Solana
/// store's post_order_v3 (`SOLANA_ORDER_PAYLOAD_LEN`; `sender` is then 0 -- it is the
/// compose's composeFrom). Any other length reverts. `lzCompose` takes only the form its
/// source sends: 76 from Solana, 192 from an EVM chain.
function decodePayload(bytes calldata p)
public
pure
returns (bytes32 launchId, bytes32 sender, uint64 senderNonce_, bytes32 to, uint256 relayerFee, uint256 minCredited)
{
Payload memory o = p.length == SOLANA_ORDER_PAYLOAD_LEN ? _decodeFromSolana(p) : _decodePayload(p);
return (o.launchId, o.sender, o.senderNonce, o.to, o.relayerFee, o.minCredited);
}
/// @dev A v3 Solana store's order (76 bytes); the sender is the caller's to fill (composeFrom).
function _decodeFromSolana(bytes calldata p) internal pure returns (Payload memory o) {
if (p.length != SOLANA_ORDER_PAYLOAD_LEN) revert BadPayload(p.length);
o.launchId = bytes32(p[0:32]);
o.senderNonce = uint64(bytes8(p[32:40]));
o.to = bytes32(uint256(uint160(bytes20(p[40:60]))));
o.relayerFee = uint64(bytes8(p[60:68]));
o.minCredited = uint64(bytes8(p[68:76]));
}
function _decodePayload(bytes calldata p) internal pure returns (Payload memory o) {
if (p.length == PACKED_PAYLOAD_LEN) {
o.launchId = bytes32(p[0:32]);
o.sender = bytes32(p[32:64]);
o.senderNonce = uint64(bytes8(p[64:72]));
o.to = bytes32(p[72:104]);
o.relayerFee = uint64(bytes8(p[104:112]));
o.minCredited = uint64(bytes8(p[112:120]));
return o;
}
if (p.length != PAYLOAD_LEN) revert BadPayload(p.length);
(o.launchId, o.sender, o.senderNonce, o.to, o.relayerFee, o.minCredited) =
abi.decode(p, (bytes32, bytes32, uint64, bytes32, uint256, uint256));
}
function _decodeABI(bytes calldata p) internal pure returns (Payload memory o) {
if (p.length != PAYLOAD_LEN) revert BadPayload(p.length);
return _decodePayload(p);
}
/// @dev What the gap message carries as the sender's least credited amount (spec §4): empty for
/// none, else abi.encode(uint256 minCreditedLD); E5: with `requireCover`, the token's
/// REQUIRE_COVER flag in the top byte (abi.encode(1 << 248 | minCreditedLD)): the send
/// reverts GapCoverNotGranted unless it carries the gas cover. minCredited <= the amount, so
/// it never reaches the flag byte.
function _oftCmd(uint256 minCredited, bool requireCover) internal pure returns (bytes memory) {
if (requireCover) return abi.encode((uint256(1) << 248) | minCredited);
return minCredited == 0 ? bytes("") : abi.encode(minCredited);
}
/// @notice What `postOrder` costs in native gas (toward Solana the token's prepay P included, which
/// carries the receipt's rent -- owner Q60; `optionsForOrder` for the order msg.sender would
/// post; Q37: plus `fillDropCostOf(dstEid)`,
/// the Fill PDA's drop paid to our delivery path). quote == what postOrder charges.
function quoteOrder(
bytes32 launchId,
uint32 dstEid,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minCredited
) external view returns (uint256 nativeFee) {
return _quoteOrder(launchId, dstEid, to, amount, relayerFee, minCredited, false);
}
/// @notice E6 (audit E5 I-c): what `postOrderCovered` costs in native gas: the same quote with the
/// token's REQUIRE_COVER flag, so it reverts GapCoverNotGranted exactly when
/// postOrderCovered would (the send would carry no gas cover).
function quoteOrderCovered(
bytes32 launchId,
uint32 dstEid,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minCredited
) external view returns (uint256 nativeFee) {
return _quoteOrder(launchId, dstEid, to, amount, relayerFee, minCredited, true);
}
function _quoteOrder(
bytes32 launchId,
uint32 dstEid,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minCredited,
bool covered
) internal view returns (uint256 nativeFee) {
bytes32 remote = remoteBridge[dstEid];
if (remote == bytes32(0)) revert NoRemote(dstEid);
IOFT oft = IOFT(_tokenOf(launchId));
uint256 arriving = arrivingOf(launchId, dstEid, amount);
bytes32 id = orderId(
localEid, _b32(address(this)), launchId, _b32(msg.sender), senderNonce[msg.sender], dstEid, to, arriving, relayerFee, minCredited
);
MessagingFee memory fee = oft.quoteSend(
SendParam({
dstEid: dstEid,
to: remote,
amountLD: amount - fastFeeOf(launchId, amount),
minAmountLD: arriving,
extraOptions: optionsForOrder(dstEid, id, address(oft)),
composeMsg: payloadFor(
dstEid, launchId, _b32(msg.sender), senderNonce[msg.sender], to, relayerFee, minCredited
),
oftCmd: _oftCmd(minCredited, covered)
}),
false
);
return fee.nativeFee + fillDropCostOf(dstEid);
}
/// @notice What a fill of this order would net its relayer if the message landed NOW: the
/// destination token's `gapPreview` (the receive's code path, as a view) on the order's
/// gross `amount` with the source's codec v3 header (`OrderGapQuote`, or the packet's
/// message bytes 41..96: psUsd, feeSrcPpm, bridgeFeePpm, then priceClass and psClass at
/// 73 and 74, srcGasMicroUsd and srcCoverCapCents at 90 and 94 (AMENDMENT 6: the gas
/// cover); minCreditedSD at 65 is the order's own `minCredited`).
/// @return withheld the gap the receive would withhold (0 when it `holds`)
/// @return credited what would arrive (`amount - withheld`): the relayer's repayment (0 when
/// it `holds`)
/// @return relayerNet `credited - (amount - relayerFee)` = `relayerFee - withheld`; negative
/// is a loss
/// @return reason GapMath's reason code (CHARGED, NO_GAP, ..., or why it holds)
/// @return lands whether the receive would land now: it does not hold, and `credited >=
/// minCredited`. When false the receive would revert (retriable) and nothing would
/// settle until it could; a relayer should not front it. Either way an earned fill is
/// repaid at least `minCredited`, so it can never net less than
/// `minCredited - (amount - relayerFee)`.
/// @return holds the destination's `gapPreview` says the receive would revert retriably now
/// (GapNoPool / GapUnreadable): not fillable, whatever the figures.
function previewFill(
bytes32 launchId,
uint128 psE18,
uint32 feeSrcPpm,
uint32 bridgeFeePpm,
uint8 priceClass,
uint128 psClassE18,
uint32 srcGasMicroUsd,
uint16 srcCoverCapCents,
uint256 amount,
uint256 relayerFee,
uint256 minCredited
)
external
view
returns (uint256 withheld, uint256 credited, int256 relayerNet, uint8 reason, bool lands, bool holds)
{
if (relayerFee >= amount) revert FeeExceedsAmount();
if (minCredited > amount) revert MinCreditedTooHigh(minCredited, amount);
IPangeaOFTV3GapQuote t = IPangeaOFTV3GapQuote(_tokenOf(launchId));
(withheld, credited,,,, reason, holds) =
t.gapPreview(psE18, feeSrcPpm, bridgeFeePpm, priceClass, psClassE18, srcGasMicroUsd, srcCoverCapCents, amount);
if (holds) (withheld, credited) = (0, 0);
relayerNet = int256(credited) - int256(amount - relayerFee);
lands = !holds && credited >= minCredited;
}
// ------------------------------------------------------------ posting
/// @notice Post a transfer of launch `launchId`'s v3 token that a relayer may deliver early.
/// @param minReceived the least a FILL may pay the recipient (`arriving - relayerFee`).
/// @param minCredited the least the destination may CREDIT (after its gap fee), at most what
/// arrives; 0 for none. Carried in the gap header: below it the receive reverts and is
/// retried later, so an unfilled order pays the recipient at least this.
function postOrder(
bytes32 launchId,
uint32 dstEid,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minReceived,
uint256 minCredited
) external payable nonReentrant returns (bytes32 id, uint64 lzNonce) {
return _postOrder(launchId, dstEid, to, amount, relayerFee, minReceived, minCredited);
}
/// @dev E5: set for the length of a `postOrderCovered` call (transient), read by `_send`.
bool transient private _requireCover;
/// @notice E5: `postOrder` with the token's REQUIRE_COVER flag: the order is posted only if its
/// send carries AMENDMENT 6's gas cover (the token's gapCoverAvailable(dstEid) in this
/// block); otherwise the whole call reverts GapCoverNotGranted and nothing moves.
function postOrderCovered(
bytes32 launchId,
uint32 dstEid,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minReceived,
uint256 minCredited
) external payable nonReentrant returns (bytes32 id, uint64 lzNonce) {
_requireCover = true;
(id, lzNonce) = _postOrder(launchId, dstEid, to, amount, relayerFee, minReceived, minCredited);
_requireCover = false;
}
function _postOrder(
bytes32 launchId,
uint32 dstEid,
bytes32 to,
uint256 amount,
uint256 relayerFee,
uint256 minReceived,
uint256 minCredited
) internal returns (bytes32 id, uint64 lzNonce) {
if (amount == 0) revert ZeroAmount();
if (to == bytes32(0) || (!isSolanaEid(dstEid) && uint256(to) >> 160 != 0)) revert BadRecipient(to);
if (remoteBridge[dstEid] == bytes32(0)) revert NoRemote(dstEid);
IOFT oft = IOFT(_tokenOf(launchId));
uint256 arriving = arrivingOf(launchId, dstEid, amount);
_checkOrder(launchId, dstEid, arriving, relayerFee, minReceived);
if (minCredited > arriving) revert MinCreditedTooHigh(minCredited, arriving);
uint256 toSend = _pull(oft, launchId, amount);
uint64 n = senderNonce[msg.sender]++;
id = orderId(localEid, _b32(address(this)), launchId, _b32(msg.sender), n, dstEid, to, arriving, relayerFee, minCredited);
// The header the send is about to carry: the same reads, in the same transaction, with
// nothing between them that moves the pool.
_emitGapQuote(id, address(oft), dstEid, arriving);
OFTReceipt memory receipt;
(lzNonce, receipt) = _send(
oft,
dstEid,
remoteBridge[dstEid],
toSend,
arriving,
payloadFor(dstEid, launchId, _b32(msg.sender), n, to, relayerFee, minCredited),
minCredited,
id
);
if (receipt.amountReceivedLD != arriving) revert OrderMismatch();
uint256 unsent = toSend - receipt.amountSentLD;
if (unsent != 0) IERC20(oft.token()).safeTransfer(msg.sender, unsent);
emit OrderPosted(id, launchId, dstEid, _b32(msg.sender), n, to, arriving, relayerFee, minCredited, lzNonce);
}
/// @dev Take `amount` of the launch's token from the sender, pay the fast fee; the rest is sent.
function _pull(IOFT oft, bytes32 launchId, uint256 amount) internal returns (uint256 toSend) {
IERC20 token = IERC20(oft.token());
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 fastFee = fastFeeOf(launchId, amount);
if (fastFee != 0) token.safeTransfer(_feeTo(address(oft)), fastFee);
toSend = amount - fastFee;
}
function _min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function _checkOrder(bytes32 launchId, uint32 dstEid, uint256 arriving, uint256 relayerFee, uint256 minReceived)
internal
view
{
if (relayerFee >= arriving) revert FeeExceedsAmount();
(, uint16 maxBps) = feesOf(launchId);
uint256 most = (arriving * maxBps) / 10_000;
if (relayerFee > most) revert RelayerFeeTooHigh(relayerFee, most);
if (arriving - relayerFee < minReceived) revert ReceivesTooLittle(arriving - relayerFee, minReceived);
if (isSolanaEid(dstEid) && arriving > type(uint64).max) revert TooLargeForSolana(arriving);
}
function _feeTo(address oft) internal view returns (address feeTo) {
feeTo = IBridgeFeeRecipientV3(oft).bridgeFeeTo();
if (feeTo == address(0)) revert ZeroAddress();
}
/// @dev The header the send below carries: the token's quote for THIS send -- its destination
/// and its amountSD, `arriving` (= the send's amountReceivedLD, already whole shared
/// units) in shared decimals, as OFTCore's `_toSD` makes the message's. The quote's
/// costPpm depends on the amount, so it is asked for this order's, never a generic one.
/// It reverts as the send would (GapSourceUnreadable / GapNoOfficialPool / GapGasTooLow).
function _emitGapQuote(bytes32 id, address oft, uint32 dstEid, uint256 arriving) internal {
uint256 sd = arriving / IOFTRateV3(oft).decimalConversionRate();
if (sd > type(uint64).max) revert AmountSDOverflow(arriving);
(uint128 ps, uint32 feeSrc, uint32 bridgeFee, uint8 cls, uint128 psCls, uint32 srcGasMicroUsd, uint16 srcCoverCapCents) =
IPangeaOFTV3GapQuote(oft).gapSendQuote(dstEid, uint64(sd));
emit OrderGapQuote(id, ps, feeSrc, bridgeFee, cls, psCls, srcGasMicroUsd, srcCoverCapCents);
}
function _send(
IOFT oft,
uint32 dstEid,
bytes32 remote,
uint256 toSend,
uint256 arriving,
bytes memory composeMsg,
uint256 minCredited,
bytes32 id
) internal returns (uint64 lzNonce, OFTReceipt memory receipt) {
// Q37: the Fill drop's figure goes to our delivery fee recipient; LayerZero gets the rest.
uint256 drop = fillDropCostOf(dstEid);
if (msg.value < drop) revert FillDropUnpaid(msg.value, drop);
MessagingReceipt memory sent;
(sent, receipt) = oft.send{value: msg.value - drop}(
SendParam({
dstEid: dstEid,
to: remote,
amountLD: toSend,
minAmountLD: arriving,
extraOptions: optionsForOrder(dstEid, id, address(oft)),
composeMsg: composeMsg,
// The order's least credited amount, into the gap header (codec v3); E5: the flag.
oftCmd: _oftCmd(minCredited, _requireCover)
}),
MessagingFee({nativeFee: msg.value - drop, lzTokenFee: 0}),
msg.sender
);
lzNonce = sent.nonce;
if (drop != 0) {
address to = deliveryFeeTo;
(bool ok,) = to.call{value: drop}("");
if (!ok) revert FillDropPayFailed(to);
emit OrderFillDropPaid(id, to, drop);
}
}
// ------------------------------------------------------------ filling
function notYetArrived(address token, uint32 srcEid, uint64 lzNonce) public view returns (bool) {
bytes32 peer = IOAppPeersV3(token).peers(srcEid);
if (peer == bytes32(0)) return false;
IEndpointStateV3 ep = IEndpointStateV3(endpoint);
if (ep.inboundPayloadHash(token, srcEid, peer, lzNonce) != bytes32(0)) return false;
return lzNonce > ep.lazyInboundNonce(token, srcEid, peer);
}
/// @notice Deliver an order now: pays `to` the GROSS order less the fee, `amount - relayerFee`.
/// The repayment is what arrives after the destination's gap fee (`previewFill`), at
/// least the order's `minCredited` (a receive below it reverts and waits).
function fillOrder(
uint32 srcEid,
bytes32 srcBridge,
bytes32 launchId,
bytes32 sender,
uint64 senderNonce_,
address to,
uint256 amount,
uint256 relayerFee,
uint256 minCredited,
uint64 lzNonce
) external nonReentrant returns (bytes32 id) {
if (!_acceptsFrom(srcEid, srcBridge, sender)) revert NotARemoteBridge(srcEid, srcBridge);
address token = _tokenOf(launchId);
if (to == address(0)) revert BadRecipient(bytes32(0));
if (minCredited > amount) revert MinCreditedTooHigh(minCredited, amount);
id = orderId(srcEid, srcBridge, launchId, sender, senderNonce_, localEid, _b32(to), amount, relayerFee, minCredited);
if (fills[id].relayer != address(0)) revert AlreadyFilled();
if (settlement[id] != 0) revert AlreadySettled();
if (relayerFee >= amount) revert FeeExceedsAmount();
if (!notYetArrived(token, srcEid, lzNonce)) revert TooLateToFill();
fills[id] = Fill({relayer: msg.sender, lzNonce: lzNonce, blockNumber: uint32(chainBlockNumber())});
uint256 paid = amount - relayerFee;
IERC20(IOFT(token).token()).safeTransferFrom(msg.sender, to, paid);
emit OrderFilled(id, msg.sender, to, paid);
}
// ------------------------------------------------------------ settlement
/// @notice The canonical message arriving. As `PangeaFastBridge.lzCompose`, except: `oApp` must
/// be a v3 token; the order id uses the GROSS amount `credited + gapWithheld(guid)` and
/// the payload's `minCredited`; the payout is `credited`, which this message minted
/// here; and a guid settles once. (A compose exists only for a receive that credited at
/// least the gap header's minimum, which our senders make the payload's.)
function lzCompose(
address oApp,
bytes32 guid,
bytes calldata message,
address, /* executor */
bytes calldata /* extraData */
) external payable nonReentrant {
if (msg.sender != endpoint) revert NotEndpoint();
if (msg.value != 0) revert ValueNotAccepted();
uint32 srcEid = OFTComposeMsgCodec.srcEid(message);
bytes32 from = OFTComposeMsgCodec.composeFrom(message);
bool fromSolana = isSolanaEid(srcEid);
if (
from == bytes32(0) || acceptStopped[srcEid]
|| (fromSolana ? !_solanaEnabled(srcEid) : !isRemoteBridge[srcEid][from])
) {
revert NotOurBridge(srcEid, from);
}
// From Solana the 76-byte form, its sender the compose's composeFrom; from an EVM chain
// the six ABI words. Not checked here: that the payload's minCredited is the gap header's
// (this compose cannot see the header, and its credit already landed). Our senders make
// them equal -- postOrder sends both; post_order_v3 checks the send's trailing minimum --
// but a Solana sender calling the OFT send directly may not, and a relayer that fronts an
// order must check the LayerZero message against it (script/fastbridge/relayer-v3.mjs
// v3MessageProblem; ours fronts no order from Solana). Reverting here when credited <
// minCredited would strand the credit with no way out, so it is not done.
Payload memory o;
if (fromSolana) {
o = _decodeFromSolana(message[COMPOSE_MSG_OFFSET:]);
o.sender = from;
} else {
o = _decodeABI(message[COMPOSE_MSG_OFFSET:]);
}
if (oApp == address(0) || tokenOf(o.launchId) != oApp) revert NotOurToken(oApp);
if (!isV3Token(oApp)) revert NotV3Token(oApp);
if (guidSettled[guid]) revert GuidAlreadySettled(guid);
guidSettled[guid] = true;
IERC20 token = IERC20(IOFT(oApp).token());
// What this message minted here, and what it would have without the gap fee. The token
// writes gapWithheld[guid] in the same lzReceive that queued this compose.
uint256 credited = OFTComposeMsgCodec.amountLD(message);
uint256 withheld = IPangeaOFTV3Gap(oApp).gapWithheld(guid);
uint256 gross = credited + withheld;
bytes32 id = orderId(
srcEid, from, o.launchId, o.sender, o.senderNonce, localEid, o.to, gross, o.relayerFee, o.minCredited
);
if (withheld != 0) emit GapBorne(id, guid, gross, withheld);
bool again = settlement[id] != 0;
if (again) emit ArrivedAgain(id, guid, credited);
if (o.to == bytes32(0) || uint256(o.to) >> 160 != 0) {
if (!again) settlement[id] = SETTLED_REFUNDABLE;
refunds[guid] = Refund({orderId: id, oft: oApp, eid: srcEid, sender: o.sender, amount: credited});
emit Refundable(id, guid, srcEid, o.sender, credited);
return;
}
address to = address(uint160(uint256(o.to)));
if (again) {
token.safeTransfer(to, credited);
emit SettledSlow(id, to, credited);
return;
}
Fill memory f = fills[id];
address relayer = f.relayer;
if (relayer != address(0)) {
bool earned = OFTComposeMsgCodec.nonce(message) == f.lzNonce && f.blockNumber != uint32(chainBlockNumber());
settlement[id] = earned ? SETTLED_EARNED : SETTLED_FEE_RETURNED;
// Earned: the relayer fronted on time and bears the gap (repaid credited). Not earned:
// the relayer is made whole out of what arrived, min(credited, gross - fee), and the
// recipient gets the rest, so its total is credited (owner (b); table above).
uint256 repaid = earned ? credited : _min(credited, gross - o.relayerFee);
uint256 fee = credited - repaid;
if (repaid != 0) token.safeTransfer(relayer, repaid);
emit RelayerPaid(id, relayer, repaid);
if (fee > 0) {
token.safeTransfer(to, fee);
emit FeeReturned(id, to, fee);
}
} else {
settlement[id] = SETTLED_SLOW;
if (credited != 0) token.safeTransfer(to, credited);
emit SettledSlow(id, to, credited);
}
}
function refund(bytes32 guid) external payable nonReentrant returns (uint64 lzNonce) {
Refund memory r = refunds[guid];
if (r.amount == 0) revert NothingToRefund();
delete refunds[guid];
SendParam memory p = _refundParam(r);
MessagingReceipt memory sent;
OFTReceipt memory receipt;
(sent, receipt) = IOFT(r.oft).send{value: msg.value}(p, MessagingFee({nativeFee: msg.value, lzTokenFee: 0}), msg.sender);
lzNonce = sent.nonce;
emit Refunded(r.orderId, guid, r.eid, r.sender, receipt.amountSentLD, lzNonce);
}
function quoteRefund(bytes32 guid) external view returns (uint256) {
Refund memory r = refunds[guid];
if (r.amount == 0) revert NothingToRefund();
return IOFT(r.oft).quoteSend(_refundParam(r), false).nativeFee;
}
/// @dev eth-fallback-fix (r1 M-1): a refund back into a KEYS-ONLY destination carries no lzReceive gas
/// of this bridge's (the token's minimal enforced option only; our keys deliver it).
function _refundParam(Refund memory r) internal view returns (SendParam memory p) {
uint128 g = keysOnlyFor(r.oft, r.eid, 1) ? 0 : gasLimits[r.eid].receiveGas;
p = SendParam({
dstEid: r.eid,
to: r.sender,
amountLD: r.amount,
minAmountLD: 0,
extraOptions: g == 0 ? bytes("") : abi.encodePacked(uint16(3), uint8(1), uint16(17), uint8(1), g),
composeMsg: "",
oftCmd: ""
});
(,, OFTReceipt memory q) = IOFT(r.oft).quoteOFT(p);
p.minAmountLD = q.amountReceivedLD;
}
function _acceptsFrom(uint32 srcEid, bytes32 srcBridge, bytes32 sender) internal view returns (bool) {
if (srcBridge == bytes32(0) || acceptStopped[srcEid]) return false;
if (isSolanaEid(srcEid)) return srcBridge == sender && _solanaEnabled(srcEid);
return isRemoteBridge[srcEid][srcBridge];
}
function _solanaEnabled(uint32 srcEid) internal view returns (bool) {
return solanaEverEnabled[srcEid];
}
function settled(bytes32 id) external view returns (bool) {
return settlement[id] != 0;
}
function filledBy(bytes32 id) external view returns (address) {
return fills[id].relayer;
}
function filledLzNonce(bytes32 id) external view returns (uint64) {
return fills[id].lzNonce;
}
// ------------------------------------------------------------ admin
/// @notice Name our counterpart on `eid`, once. Refused (`RemoteAlreadySet`) when `eid` has a
/// remote or had one revoked: a remote receives every order's tokens, so it is never
/// re-pointed. A wrong one is revoked (`revokeRemoteBridge`), and a new FastBridge is the fix.
function setRemoteBridge(uint32 eid, bytes32 bridge) external onlyAdmin {
if (bridge == bytes32(0)) revert ZeroAddress();
if (remoteBridge[eid] != bytes32(0) || remoteRevoked[eid]) revert RemoteAlreadySet(eid);
remoteBridge[eid] = bridge;
isRemoteBridge[eid][bridge] = true;
if (isSolanaEid(eid)) solanaEverEnabled[eid] = true;
emit RemoteBridgeSet(eid, bridge);
}
/// @notice Step 1 of 2 of retiring `eid`'s remote (audit L-1): REVOKE. No new orders or quotes
/// to it (`NoRemote`), and it can never be set again (`RemoteAlreadySet`). Its arrivals
/// are STILL accepted -- `lzCompose` settles them and relayers may front them -- so an
/// order in flight across the revocation settles and its relayer is repaid. Refusing
/// them is step 2, `stopAcceptingRemoteBridge`. Irreversible.
///
/// Safe order across chains: revoke on the SOURCE chain(s) first, wait until every
/// message already sent has landed (and settled) on the destination, then stop
/// accepting there.
function revokeRemoteBridge(uint32 eid) external onlyAdmin {
bytes32 bridge = remoteBridge[eid];
if (bridge == bytes32(0)) revert NoRemote(eid);
_revoke(eid, bridge);
}
/// @notice Step 2 of 2 (audit L-1): STOP ACCEPTING arrivals from `eid`'s bridge, for good:
/// `lzCompose` refuses its composes (`NotOurBridge`, the compose stays queued at the
/// endpoint) and `fillOrder` its orders (`NotARemoteBridge`). Toward Solana this is
/// every Solana sender (an arrival from Solana is accepted by its composeFrom). Also
/// revokes a remote still set (step 1). Irreversible, and the eid can never get a remote
/// again. Run it only after the source revoked and everything in flight has landed.
/// What already settled -- fills, refunds owed, repayments -- is untouched.
function stopAcceptingRemoteBridge(uint32 eid) external onlyAdmin {
bytes32 bridge = remoteBridge[eid];
if (bridge != bytes32(0)) _revoke(eid, bridge);
else bridge = revokedRemoteBridge[eid];
if (bridge == bytes32(0)) revert NoRemote(eid);
if (acceptStopped[eid]) revert AcceptAlreadyStopped(eid);
acceptStopped[eid] = true;
isRemoteBridge[eid][bridge] = false;
emit RemoteBridgeStopped(eid, bridge);
}
function _revoke(uint32 eid, bytes32 bridge) internal {
remoteBridge[eid] = bytes32(0);
remoteRevoked[eid] = true;
revokedRemoteBridge[eid] = bridge;
emit RemoteBridgeRevoked(eid, bridge);
}
/// @notice Toward an EVM chain: lzReceive and lzCompose gas, each at most `MAX_GAS_LIMIT`.
/// Toward Solana: lzReceive compute units (at most `MAX_GAS_LIMIT`) and `composeGas` 0 --
/// owner Q60: no lzReceive value (the GapReceipt's rent is in the token's prepay P);
/// anything else reverts SolanaValueRefused.
function setGasLimits(uint32 eid, uint128 receiveGas, uint128 composeGas) external onlyAdmin {
if (receiveGas > MAX_GAS_LIMIT) revert GasLimitTooHigh(receiveGas, MAX_GAS_LIMIT);
if (isSolanaEid(eid)) {
if (composeGas != 0) revert SolanaValueRefused(composeGas);
} else if (composeGas > MAX_GAS_LIMIT) {
revert GasLimitTooHigh(composeGas, MAX_GAS_LIMIT);
}
gasLimits[eid] = GasLimits(receiveGas, composeGas);
emit GasLimitsSet(eid, receiveGas, composeGas);
}
/// @notice Q37: our delivery fee recipient on this chain (never zero).
function setDeliveryFeeTo(address to) external onlyAdmin {
if (to == address(0)) revert ZeroAddress();
deliveryFeeTo = to;
emit DeliveryFeeToSet(to);
}
/// @notice Q37: what an order into Solana pays for its Fill drop, at most `fillDropCostMax()`;
/// non-zero needs `deliveryFeeTo`. 0 refuses every order into Solana (never unpaid).
function setFillDropCost(uint256 costWei) external onlyAdmin {
uint256 max = fillDropCostMax();
if (costWei > max) revert FillDropCostTooHigh(costWei, max);
if (costWei != 0 && deliveryFeeTo == address(0)) revert ZeroAddress();
fillDropCostWei = costWei;
emit FillDropCostSet(costWei);
}
function setFastFee(uint16 bps) external onlyAdmin {
if (bps > MAX_FAST_FEE_BPS) revert FastFeeTooHigh(bps, MAX_FAST_FEE_BPS);
fastFeeBps = bps;
emit FastFeeSet(bps);
}
function setMaxRelayerFee(uint16 bps) external onlyAdmin {
if (bps > MAX_RELAYER_FEE_CAP_BPS) revert MaxRelayerFeeTooHigh(bps, MAX_RELAYER_FEE_CAP_BPS);
maxRelayerFeeBps = bps;
emit MaxRelayerFeeSet(bps);
}
function setLaunchFees(bytes32 launchId, bool set, uint16 fastBps, uint16 maxRelayerBps) external onlyAdmin {
if (fastBps > MAX_FAST_FEE_BPS) revert FastFeeTooHigh(fastBps, MAX_FAST_FEE_BPS);
if (maxRelayerBps > MAX_RELAYER_FEE_CAP_BPS) revert MaxRelayerFeeTooHigh(maxRelayerBps, MAX_RELAYER_FEE_CAP_BPS);
launchFees[launchId] = LaunchFees(set, set ? fastBps : 0, set ? maxRelayerBps : 0);
emit LaunchFeesSet(launchId, set, fastBps, maxRelayerBps);
}
/// @notice List a v3 factory. Append-only. Its launches are served only if their token is v3.
function addFactory(address factory_) external {
if (msg.sender != factoryAdmin) revert NotFactoryAdmin();
if (factory_ == address(0)) revert ZeroFactory();
if (isFactory[factory_]) revert FactoryAlreadyAdded(factory_);
if (_factories.length >= MAX_FACTORIES) revert TooManyFactories();
isFactory[factory_] = true;
_factories.push(factory_);
emit FactoryAdded(factory_, _factories.length - 1);
}
function setFactoryAdmin(address next) external {
if (msg.sender != factoryAdmin) revert NotFactoryAdmin();
if (next == address(0)) revert ZeroAddress();
emit FactoryAdminSet(factoryAdmin, next);
factoryAdmin = next;
}
function factories() external view returns (address[] memory) {
return _factories;
}
function factoryCount() external view returns (uint256) {
return _factories.length;
}
function factoryAt(uint256 index) external view returns (address) {
return _factories[index];
}
function proposeAdmin(address to) external onlyAdmin {
if (to == address(0)) revert ZeroAddress();
pendingAdmin = to;
emit AdminProposed(admin, to);
}
function acceptAdmin() external {
if (msg.sender != pendingAdmin) revert NotPending();
emit AdminChanged(admin, msg.sender);
admin = msg.sender;
pendingAdmin = address(0);
}
}
lib/layerzero/oapp-evm/contracts/oapp/OAppCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOAppCore, ILayerZeroEndpointV2 } from "./interfaces/IOAppCore.sol";
/**
* @title OAppCore
* @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.
*/
abstract contract OAppCore is IOAppCore, Ownable {
// The LayerZero endpoint associated with the given OApp
ILayerZeroEndpointV2 public immutable endpoint;
// Mapping to store peers associated with corresponding endpoints
mapping(uint32 eid => bytes32 peer) public peers;
/**
* @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.
* @param _endpoint The address of the LOCAL Layer Zero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
*/
constructor(address _endpoint, address _delegate) {
endpoint = ILayerZeroEndpointV2(_endpoint);
if (_delegate == address(0)) revert InvalidDelegate();
endpoint.setDelegate(_delegate);
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/
function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {
_setPeer(_eid, _peer);
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/
function _setPeer(uint32 _eid, bytes32 _peer) internal virtual {
peers[_eid] = _peer;
emit PeerSet(_eid, _peer);
}
/**
* @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.
* ie. the peer is set to bytes32(0).
* @param _eid The endpoint ID.
* @return peer The address of the peer associated with the specified endpoint.
*/
function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {
bytes32 peer = peers[_eid];
if (peer == bytes32(0)) revert NoPeer(_eid);
return peer;
}
/**
* @notice Sets the delegate address for the OApp.
* @param _delegate The address of the delegate to be set.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.
*/
function setDelegate(address _delegate) public onlyOwner {
endpoint.setDelegate(_delegate);
}
}
lib/layerzero/oapp-evm/contracts/oapp/OAppSender.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessagingParams, MessagingFee, MessagingReceipt } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { OAppCore } from "./OAppCore.sol";
/**
* @title OAppSender
* @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.
*/
abstract contract OAppSender is OAppCore {
using SafeERC20 for IERC20;
// Custom error messages
error NotEnoughNative(uint256 msgValue);
error LzTokenUnavailable();
// @dev The version of the OAppSender implementation.
// @dev Version is bumped when changes are made to this contract.
uint64 internal constant SENDER_VERSION = 1;
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.
* ie. this is a SEND only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions
*/
function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
return (SENDER_VERSION, 0);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
* @return fee The calculated MessagingFee for the message.
* - nativeFee: The native fee for the message.
* - lzTokenFee: The LZ token fee for the message.
*/
function _quote(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
bool _payInLzToken
) internal view virtual returns (MessagingFee memory fee) {
return
endpoint.quote(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),
address(this)
);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _fee The calculated LayerZero fee for the message.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess fee values sent to the endpoint.
* @return receipt The receipt for the sent message.
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function _lzSend(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
MessagingFee memory _fee,
address _refundAddress
) internal virtual returns (MessagingReceipt memory receipt) {
// @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.
uint256 messageValue = _payNative(_fee.nativeFee);
if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);
return
// solhint-disable-next-line check-send-result
endpoint.send{ value: messageValue }(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),
_refundAddress
);
}
/**
* @dev Internal function to pay the native fee associated with the message.
* @param _nativeFee The native fee to be paid.
* @return nativeFee The amount of native currency paid.
*
* @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,
* this will need to be overridden because msg.value would contain multiple lzFees.
* @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.
* @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.
* @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.
*/
function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {
if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);
return _nativeFee;
}
/**
* @dev Internal function to pay the LZ token fee associated with the message.
* @param _lzTokenFee The LZ token fee to be paid.
*
* @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.
* @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().
*/
function _payLzToken(uint256 _lzTokenFee) internal virtual {
// @dev Cannot cache the token because it is not immutable in the endpoint.
address lzToken = endpoint.lzToken();
if (lzToken == address(0)) revert LzTokenUnavailable();
// Pay LZ token fee by sending tokens to the endpoint.
IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);
}
}
lib/layerzero/oapp-evm/contracts/oapp/interfaces/IOAppComposer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ILayerZeroComposer } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroComposer.sol";
/**
* @title IOAppComposer
* @dev This interface defines the OApp Composer, allowing developers to inherit only the OApp package without the protocol.
*/
// solhint-disable-next-line no-empty-blocks
interface IOAppComposer is ILayerZeroComposer {}
lib/layerzero/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ILayerZeroEndpointV2 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
/**
* @title IOAppCore
*/
interface IOAppCore {
// Custom error messages
error OnlyPeer(uint32 eid, bytes32 sender);
error NoPeer(uint32 eid);
error InvalidEndpointCall();
error InvalidDelegate();
// Event emitted when a peer (OApp) is set for a corresponding endpoint
event PeerSet(uint32 eid, bytes32 peer);
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*/
function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);
/**
* @notice Retrieves the LayerZero endpoint associated with the OApp.
* @return iEndpoint The LayerZero endpoint as an interface.
*/
function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);
/**
* @notice Retrieves the peer (OApp) associated with a corresponding endpoint.
* @param _eid The endpoint ID.
* @return peer The peer address (OApp instance) associated with the corresponding endpoint.
*/
function peers(uint32 _eid) external view returns (bytes32 peer);
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*/
function setPeer(uint32 _eid, bytes32 _peer) external;
/**
* @notice Sets the delegate address for the OApp Core.
* @param _delegate The address of the delegate to be set.
*/
function setDelegate(address _delegate) external;
}
lib/layerzero/oft-evm/contracts/interfaces/IOFT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { MessagingReceipt, MessagingFee } from "@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol";
/**
* @dev Struct representing token parameters for the OFT send() operation.
*/
struct SendParam {
uint32 dstEid; // Destination endpoint ID.
bytes32 to; // Recipient address.
uint256 amountLD; // Amount to send in local decimals.
uint256 minAmountLD; // Minimum amount to send in local decimals.
bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
bytes composeMsg; // The composed message for the send() operation.
bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}
/**
* @dev Struct representing OFT limit information.
* @dev These amounts can change dynamically and are up the specific oft implementation.
*/
struct OFTLimit {
uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.
uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.
}
/**
* @dev Struct representing OFT receipt information.
*/
struct OFTReceipt {
uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.
// @dev In non-default implementations, the amountReceivedLD COULD differ from this value.
uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}
/**
* @dev Struct representing OFT fee details.
* @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.
*/
struct OFTFeeDetail {
int256 feeAmountLD; // Amount of the fee in local decimals.
string description; // Description of the fee.
}
/**
* @title IOFT
* @dev Interface for the OftChain (OFT) token.
* @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.
* @dev This specific interface ID is '0x02e49c2c'.
*/
interface IOFT {
// Custom error messages
error InvalidLocalDecimals();
error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);
error AmountSDOverflowed(uint256 amountSD);
// Events
event OFTSent(
bytes32 indexed guid, // GUID of the OFT message.
uint32 dstEid, // Destination Endpoint ID.
address indexed fromAddress, // Address of the sender on the src chain.
uint256 amountSentLD, // Amount of tokens sent in local decimals.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
event OFTReceived(
bytes32 indexed guid, // GUID of the OFT message.
uint32 srcEid, // Source Endpoint ID.
address indexed toAddress, // Address of the recipient on the dst chain.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/
function oftVersion() external view returns (bytes4 interfaceId, uint64 version);
/**
* @notice Retrieves the address of the token associated with the OFT.
* @return token The address of the ERC20 token implementation.
*/
function token() external view returns (address);
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev Allows things like wallet implementers to determine integration requirements,
* without understanding the underlying token implementation.
*/
function approvalRequired() external view returns (bool);
/**
* @notice Retrieves the shared decimals of the OFT.
* @return sharedDecimals The shared decimals of the OFT.
*/
function sharedDecimals() external view returns (uint8);
/**
* @notice Provides the fee breakdown and settings data for an OFT. Unused in the default implementation.
* @param _sendParam The parameters for the send operation.
* @return limit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return receipt The OFT receipt information.
*/
function quoteOFT(
SendParam calldata _sendParam
) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return fee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/
function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);
/**
* @notice Executes the send() operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The fee information supplied by the caller.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds from fees etc. on the src.
* @return receipt The LayerZero messaging receipt from the send() operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function send(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) external payable returns (MessagingReceipt memory, OFTReceipt memory);
}
lib/layerzero/oft-evm/contracts/libs/OFTComposeMsgCodec.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library OFTComposeMsgCodec {
// Offset constants for decoding composed messages
uint8 private constant NONCE_OFFSET = 8;
uint8 private constant SRC_EID_OFFSET = 12;
uint8 private constant AMOUNT_LD_OFFSET = 44;
uint8 private constant COMPOSE_FROM_OFFSET = 76;
/**
* @dev Encodes a OFT composed message.
* @param _nonce The nonce value.
* @param _srcEid The source endpoint ID.
* @param _amountLD The amount in local decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded Composed message.
*/
function encode(
uint64 _nonce,
uint32 _srcEid,
uint256 _amountLD,
bytes memory _composeMsg // 0x[composeFrom][composeMsg]
) internal pure returns (bytes memory _msg) {
_msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);
}
/**
* @dev Retrieves the nonce for the composed message.
* @param _msg The message.
* @return The nonce value.
*/
function nonce(bytes calldata _msg) internal pure returns (uint64) {
return uint64(bytes8(_msg[:NONCE_OFFSET]));
}
/**
* @dev Retrieves the source endpoint ID for the composed message.
* @param _msg The message.
* @return The source endpoint ID.
*/
function srcEid(bytes calldata _msg) internal pure returns (uint32) {
return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));
}
/**
* @dev Retrieves the amount in local decimals from the composed message.
* @param _msg The message.
* @return The amount in local decimals.
*/
function amountLD(bytes calldata _msg) internal pure returns (uint256) {
return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));
}
/**
* @dev Retrieves the composeFrom value from the composed message.
* @param _msg The message.
* @return The composeFrom value.
*/
function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {
return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);
}
/**
* @dev Retrieves the composed message.
* @param _msg The message.
* @return The composed message.
*/
function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
return _msg[COMPOSE_FROM_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/
function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
return address(uint160(uint256(_b)));
}
}
lib/layerzero/protocol-v2/contracts/interfaces/ILayerZeroComposer.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/**
* @title ILayerZeroComposer
*/
interface ILayerZeroComposer {
/**
* @notice Composes a LayerZero message from an OApp.
* @dev To ensure non-reentrancy, implementers of this interface MUST assert msg.sender is the corresponding EndpointV2 contract (i.e., onlyEndpointV2).
* @param _from The address initiating the composition, typically the OApp where the lzReceive was called.
* @param _guid The unique identifier for the corresponding LayerZero src/dst tx.
* @param _message The composed message payload in bytes. NOT necessarily the same payload passed via lzReceive.
* @param _executor The address of the executor for the composed message.
* @param _extraData Additional arbitrary data in bytes passed by the entity who executes the lzCompose.
*/
function lzCompose(
address _from,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable;
}
lib/layerzero/protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { IMessageLibManager } from "./IMessageLibManager.sol";
import { IMessagingComposer } from "./IMessagingComposer.sol";
import { IMessagingChannel } from "./IMessagingChannel.sol";
import { IMessagingContext } from "./IMessagingContext.sol";
struct MessagingParams {
uint32 dstEid;
bytes32 receiver;
bytes message;
bytes options;
bool payInLzToken;
}
struct MessagingReceipt {
bytes32 guid;
uint64 nonce;
MessagingFee fee;
}
struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}
struct Origin {
uint32 srcEid;
bytes32 sender;
uint64 nonce;
}
interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
event PacketDelivered(Origin origin, address receiver);
event LzReceiveAlert(
address indexed receiver,
address indexed executor,
Origin origin,
bytes32 guid,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
event LzTokenSet(address token);
event DelegateSet(address sender, address delegate);
function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
function send(
MessagingParams calldata _params,
address _refundAddress
) external payable returns (MessagingReceipt memory);
function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
function lzReceive(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
bytes calldata _message,
bytes calldata _extraData
) external payable;
// oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
function setLzToken(address _lzToken) external;
function lzToken() external view returns (address);
function nativeToken() external view returns (address);
function setDelegate(address _delegate) external;
}
lib/layerzero/protocol-v2/contracts/interfaces/IMessageLibManager.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
struct SetConfigParam {
uint32 eid;
uint32 configType;
bytes config;
}
interface IMessageLibManager {
struct Timeout {
address lib;
uint256 expiry;
}
event LibraryRegistered(address newLib);
event DefaultSendLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
event SendLibrarySet(address sender, uint32 eid, address newLib);
event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
function registerLibrary(address _lib) external;
function isRegisteredLibrary(address _lib) external view returns (bool);
function getRegisteredLibraries() external view returns (address[] memory);
function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
function defaultSendLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external;
function defaultReceiveLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
function isSupportedEid(uint32 _eid) external view returns (bool);
function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
/// ------------------- OApp interfaces -------------------
function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external;
function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
function getConfig(
address _oapp,
address _lib,
uint32 _eid,
uint32 _configType
) external view returns (bytes memory config);
}
lib/layerzero/protocol-v2/contracts/interfaces/IMessagingChannel.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingChannel {
event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
function eid() external view returns (uint32);
// this is an emergency function if a message cannot be verified for some reasons
// required to provide _nextNonce to avoid race condition
function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
function inboundPayloadHash(
address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce
) external view returns (bytes32);
function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
}
lib/layerzero/protocol-v2/contracts/interfaces/IMessagingComposer.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingComposer {
event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
event LzComposeAlert(
address indexed from,
address indexed to,
address indexed executor,
bytes32 guid,
uint16 index,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
function composeQueue(
address _from,
address _to,
bytes32 _guid,
uint16 _index
) external view returns (bytes32 messageHash);
function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
function lzCompose(
address _from,
address _to,
bytes32 _guid,
uint16 _index,
bytes calldata _message,
bytes calldata _extraData
) external payable;
}
lib/layerzero/protocol-v2/contracts/interfaces/IMessagingContext.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingContext {
function isSendingMessage() external view returns (bool);
function getSendContext() external view returns (uint32 dstEid, address sender);
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/v3/SolanaPda.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
/// @title SolanaPda
/// @notice Solana's `Pubkey::find_program_address` on an EVM chain, for one 2-seed shape (a short
/// byte string and a 32-byte value): sha256(seed0 || seed1 || [bump] || programId ||
/// "ProgramDerivedAddress") for bump = 255, 254, ... -- the first hash that is NOT a point
/// of ed25519 (curve25519-dalek's `CompressedEdwardsY::decompress` fails) is the address.
/// Used by PangeaFastBridgeV3 to name an EVM -> Solana order's own Fill PDA as the receiver
/// of the order's rent drop (audit r1 I-1). Pinned by test/fixtures/solana-fill-pda-vectors.json
/// (made with Solana's own derivation) in forge and in the Solana program's tests.
/// @dev On-curve, as dalek decides it: y = the 32 bytes little-endian with bit 255 (x's sign)
/// cleared, taken mod p; u = y^2 - 1, v = d*y^2 + 1; a point iff u/v is a square mod p (u = 0
/// included; v = 0 with u != 0 is not). The square test is Euler's criterion through the modexp
/// precompile (0x05), present on every chain we deploy to.
/// Non-canonical y (the masked 255 bits at or above p): the validator (curve25519-dalek, which
/// Solana's find_program_address runs) reduces it mod p, as this does; the JS web3 library (noble)
/// refuses it as no point. They disagree only there -- a sha256 output lands there with odds of
/// 19 in 2^255 -- and this follows the chain (script/gen-solana-fill-pda-vectors.mjs leaves such
/// values out of the vectors for that reason).
library SolanaPda {
uint256 internal constant P = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed;
/// @dev ed25519's d = -121665 / 121666 mod p.
uint256 internal constant D = 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3;
/// @notice The most bumps tried (255 down to 240). A bump below them has odds of 2^-16 per
/// address; such an order reverts `NoPdaBump` instead of spending all its gas.
uint256 internal constant MAX_BUMP_TRIES = 16;
error NoPdaBump();
error ModExpFailed();
function _modexp(uint256 base, uint256 e) private view returns (uint256 r) {
bytes memory input = abi.encode(uint256(32), uint256(32), uint256(32), base, e, P);
(bool ok, bytes memory out) = address(0x05).staticcall(input);
if (!ok || out.length != 32) revert ModExpFailed();
r = abi.decode(out, (uint256));
}
/// @notice Whether 32 bytes are an ed25519 point (Solana's `bytes_are_curve_point`).
function isOnCurve(bytes32 b) internal view returns (bool) {
uint256 y;
for (uint256 i = 0; i < 32; i++) {
y |= uint256(uint8(b[i])) << (8 * i);
}
y &= (uint256(1) << 255) - 1;
y %= P;
uint256 yy = mulmod(y, y, P);
uint256 u = addmod(yy, P - 1, P);
uint256 v = addmod(mulmod(D, yy, P), 1, P);
if (u == 0) return true;
if (v == 0) return false;
uint256 w = mulmod(u, _modexp(v, P - 2), P);
return _modexp(w, (P - 1) / 2) == 1;
}
/// @notice `Pubkey::find_program_address(&[seed0, seed1], program)`, trying at most
/// `MAX_BUMP_TRIES` bumps.
function findProgramAddress(bytes memory seed0, bytes32 seed1, bytes32 program)
internal
view
returns (bytes32 addr, uint8 bump)
{
for (uint256 i = 0; i < MAX_BUMP_TRIES; i++) {
bump = uint8(255 - i);
addr = sha256(abi.encodePacked(seed0, seed1, bump, program, "ProgramDerivedAddress"));
if (!isOnCurve(addr)) return (addr, bump);
}
revert NoPdaBump();
}
}
src/v3/gap/IPangeaOFTV3Gap.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
/// @title IPangeaOFTV3Gap -- the gap-fee surface of a v3 token (docs/v3c-gap-spec.md, codec v3)
/// @notice Implemented by the v3 EVM OFT (its gap module); read by FastBridge V3, the web and the
/// server. All amounts are local decimals (LD); USD prices are USD per whole token 1e18,
/// class prices are the class asset per whole token 1e18.
interface IPangeaOFTV3Gap {
/// @notice A v3 message was received and the formula withheld something (`withheldLD` may be 0
/// by rounding). `psE18`/`pdE18` are the pair compared: USD when `pairClass == 0`, else
/// the class asset of class `pairClass` (both quotes of that class, no hop).
event GapCharged(
bytes32 indexed guid,
uint32 indexed srcEid,
address indexed to,
uint256 amountLD,
uint256 withheldLD,
uint128 psE18,
uint256 pdE18,
uint32 gapPpm,
uint64 allowPpm,
uint8 pairClass
);
/// @notice A receive credited in full for `reason` (GapMath: ESCAPED 9, SEED_NO_POOL 10, REFUND 11,
/// NO_GAP 6 or WITHIN_ALLOWANCE 7). Every other outcome either charged (GapCharged) or reverted.
event GapSkipped(bytes32 indexed guid, uint32 indexed srcEid, uint8 reason);
/// @notice gasleft() was below what the gap reads need, on send or receive: a starved read
/// would mean a lower fee, so it reverts instead (retriable).
error GapGasTooLow(uint256 needed, uint256 left);
/// @notice The message is not codec v3 (any other version byte, or a header below 96 bytes).
error GapBadVersion();
/// @notice No official pool on this chain yet and `to` is not a listed seeder: retriable.
error GapNoPool();
/// @notice A price, fee, margin or route the receive needs is unreadable (GapMath reason):
/// retriable, never fee 0. A fixed route, a new reader or the escape lands it.
error GapUnreadable(uint8 reason);
/// @notice The send could price neither in USD nor in its quote's class (fails closed).
error GapSourceUnreadable();
/// @notice v3c-evm-log: the price log has too few entries or too little unused capacity for
/// this send (nothing moves) or receive (it holds); retriable: anyone pokes, and it
/// lands from the next second.
error GapNeedRecords();
/// @notice The registry this token reads (immutable).
function gapRegistry() external view returns (address);
/// @notice The bridge fee the source takes before sending, ppm: the registry's live bridgeFeeBps() x 100
/// (default 20 bps = 2,000 ppm; v3c-evm-final).
function bridgeFeePpm() external view returns (uint32);
/// @notice Exactly what a send of `amountSD` (net of the bridge fee, shared decimals) to
/// `dstEid` now carries: psE18 = the lower of the two recorded closes (rounded up)
/// times the route (0 = unreadable); feeSrcPpm = this pool's fee (held rule) + the
/// bridge cost (costPpm: LayerZero's quote for the ENFORCED SEND options of `dstEid`, capped at
/// the registry's costMaxUsdE18); bridgeFeePpm_ = the live bridge fee; priceClass = the pool quote's class (0 none); psClassE18 = the
/// lower close in quote units (0 unless class != 0); srcGasMicroUsd / srcCoverCapCents = AMENDMENT 6's source gas cover
/// (this chain's swap + send gas at this block's basefee, micro-USD, and its cover cap in
/// cents; (0, 0) when no cover is set or the route's window cover is spent). Reverts
/// GapSourceUnreadable (also: psUsd 0, or the native price unreadable on a granted cover),
/// GapNoOfficialPool, GapRegistryUnreadable or GapGasTooLow as the send does.
function gapSendQuote(uint32 dstEid, uint64 amountSD)
external
view
returns (
uint128 psE18,
uint32 feeSrcPpm,
uint32 bridgeFeePpm_,
uint8 priceClass,
uint128 psClassE18,
uint32 srcGasMicroUsd,
uint16 srcCoverCapCents
);
/// @notice The receive's code path as a view, for a v3 message carrying these header values.
/// `holds == true`: the receive would revert retriably (GapNoPool: reason DST_NO_POOL;
/// GapUnreadable: reason PS_ZERO / DST_FEE_FAILED / DST_PRICE_FAILED); withheld and
/// credited are then 0. The escape on: reason ESCAPED, withheld 0. A no-pool chain
/// answers holds (a seeder `to` is credited in full by the receive; the preview has no
/// `to`). `pdE18` is the pair's destination price (class units when the class pair is
/// used). Never reverts except GapGasTooLow. minCredited is the caller's.
function gapPreview(
uint128 psE18,
uint32 feeSrcPpm,
uint32 bridgeFeePpm_,
uint8 priceClass,
uint128 psClassE18,
uint32 srcGasMicroUsd,
uint16 srcCoverCapCents,
uint256 amountLD
)
external
view
returns (
uint256 withheldLD,
uint256 creditedLD,
uint256 pdE18,
uint32 gapPpm,
uint64 allowPpm,
uint8 reason,
bool holds
);
/// @notice What the receive of `guid` withheld (0 if none, or not received yet). For
/// FastBridge V3, which fronts the credit and reconciles against this.
function gapWithheld(bytes32 guid) external view returns (uint256 withheldLD);
/// @notice Everything this token has withheld (= never minted) since deploy.
function gapBurnedLD() external view returns (uint256);
}
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.