Verified contractPartialBUSL-1.1
SuperchainBridgeAdapter
Address0xc7565d41f5f9206201dc3fd01f32df234560e797
- Balance
0 ETH
- Transactions
14
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,849,840
- Creation transaction
- 0xf03116f473…708ae97d00
- Libraries
- src/bridge/adapters/SuperchainBridgeAdapter.sol:InvoiceDataLib0x6772…9c67b3
23 files
- src/bridge/adapters/SuperchainBridgeAdapter.solmain45.37 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/AccessControl.sol7.02 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol879 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/optimism/packages/contracts-bedrock/src/libraries/Types.sol3.26 KB
- src/bridge/BridgeAdapter.sol12.47 KB
- src/bridge/IBridgeAdapter.sol3.46 KB
- src/bridge/IBridgeEscrow.sol16.46 KB
- src/bridge/InvoiceDataLib.sol6.67 KB
- src/bridge/adapters/interfaces/ISuperchainBridgeAdapter.sol14.38 KB
- src/bridge/adapters/interfaces/ISuperchainInterfaces.sol10.07 KB
- src/constants.sol666 B
- src/errors.sol3.05 KB
src/bridge/adapters/SuperchainBridgeAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BridgeAdapter} from "../BridgeAdapter.sol";
import {IBridgeEscrow} from "../IBridgeEscrow.sol";
import {InvoiceDataLib} from "../InvoiceDataLib.sol";
import {
IL1StandardBridge,
IL2StandardBridge,
IOptimismPortal,
ICrossDomainMessenger
} from "./interfaces/ISuperchainInterfaces.sol";
import {Types} from "@optimism/libraries/Types.sol";
import {ISuperchainBridgeAdapter} from "./interfaces/ISuperchainBridgeAdapter.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";
/// @title SuperchainBridgeAdapter
/// @notice Bridge adapter for Optimism Superchain canonical bridges (L1 <-> L2, both directions).
/// @dev The destination recipient is always the sibling adapter (`address(this)`, same address across chains
/// via CREATE2) for both L1->L2 deposits and L2->L1 withdrawals, so delivered ETH/tokens land on the
/// adapter and the destination custody record (hold-then-claim, ADR 0024) is funded from the adapter's own balance.
///
/// Provenance (ADR 0012, D1/D2): there is no escrow fallback dispatcher. Each inbound completion path
/// authenticates the genuine OP Stack contract and the source-chain sender:
/// - L1->L2 deposit: the L1 adapter initiates the canonical bridge deposit AND sends an authenticated
/// `completeDeposit` message via the destination L2's L1CrossDomainMessenger (`l1MessengerForL2`, per-L2 —
/// OP and Base differ) to its L2 sibling. On L2 the deposit's funds are ordered ahead of that message, so
/// `completeDeposit` sees the funds; it requires `msg.sender == l2Messenger` AND
/// `l2Messenger.xDomainMessageSender() == trustedRemoteAdapter[srcChainId]`.
/// (The MANAGER `completeBridge` path remains a backstop if the message is delayed/stuck.)
/// - L2->L1 withdrawal: proof-gated through the OptimismPortal. The adapter computes the REAL OP
/// withdrawal hash (`keccak256(abi.encode(nonce, sender, target, value, gasLimit, data))`,
/// matching `Hashing.hashWithdrawal`) and only completes once the portal reports the withdrawal proven.
/// A real `withdrawTo` withdrawal's portal `target` is the L1CrossDomainMessenger (which relays the
/// L1-bridge call that pays this adapter), NOT this adapter — so completion finalizes idempotently
/// (skipping a front-run finalize) and binds the amount by the adapter's measured balance delta.
/// @author KPK
contract SuperchainBridgeAdapter is BridgeAdapter, ISuperchainBridgeAdapter {
using SafeERC20 for IERC20;
//
// State Variables
//
/// @notice L1 Standard Bridge per destination L2 chain id (L1 side only).
/// @dev OP and Base have distinct L1 standard bridges, so one same-address L1 adapter keys the bridge by
/// the destination L2 chain id. Used on L1 → L2 deposits, selected by `data.destinationChainId`.
mapping(uint256 => IL1StandardBridge) public l1BridgeForL2;
/// @notice L2 Standard Bridge contract address
IL2StandardBridge public l2Bridge;
/// @notice L1 Cross-Domain Messenger contract address (legacy single value; kept for config compatibility).
/// @dev OUTBOUND deposit completion messages use the per-destination-L2 messenger `l1MessengerForL2` instead —
/// OP and Base have DISTINCT L1CrossDomainMessengers, so one same-address L1 adapter must key the messenger
/// by the destination L2. This field is no longer read on the L1 execution path.
address public l1Messenger;
/// @notice L1 Cross-Domain Messenger per L2 chain id (L1 side only). Used in BOTH directions.
/// @dev OP and Base have distinct L1CrossDomainMessengers. Deposit (L1 → L2): the adapter sends the authenticated
/// `completeDeposit` message through this messenger, selected by `data.destinationChainId`. Withdrawal
/// finalize (L2 → L1): the already-finalized (front-run) branch binds the withdrawal's `target` to this
/// messenger, selected by `data.sourceChainId`. So it MUST be wired for every L2 the adapter serves in
/// EITHER direction — not just deposit destinations — or a front-run withdrawal completion reverts
/// `MessengerNotConfigured`. Seeded post-init via `setL1MessengerForL2` (like `l1BridgeForL2`).
mapping(uint256 => address) public l1MessengerForL2;
/// @notice L2 Cross-Domain Messenger contract address
address public l2Messenger;
/// @notice Optimism Portal per source L2 chain id (L1 side only).
/// @dev OP and Base have distinct L1 OptimismPortals; the L1 adapter keys the portal by the source L2
/// chain id. Used on L2 → L1 withdrawal prove/finalize, selected by `data.sourceChainId`.
mapping(uint256 => IOptimismPortal) public optimismPortalForL2;
/// @notice The chain ID where this adapter is deployed (`block.chainid` at init).
uint256 public chainId;
/// @notice The chain id that is "the L1 side" for this Superchain deployment (mainnet = 1).
/// @dev The adapter plays the L1 role when `chainId == l1ChainId` and the L2 role otherwise. Set at init
/// (identically on both siblings, so the CREATE2 same-address guarantee is unaffected — it is an init
/// arg, not a constructor arg) so direction dispatch + L1-only guards work on any L1 host, not just mainnet.
uint256 public l1ChainId;
/// @notice Mapping to store message payloads by invoice ID
/// @dev Used to retrieve payloads on destination chain
mapping(bytes32 => bytes) public messagePayloads;
/// @notice Mapping from withdrawal hash to invoice ID
/// @dev Used to correlate withdrawal transactions with invoice IDs. The key is the REAL OP withdrawal
/// hash (see `_hashWithdrawal`), set on L1 when the manager proves the withdrawal.
mapping(bytes32 => bytes32) public withdrawalHashToInvoiceId;
/// @notice Mapping from invoice ID to withdrawal hash
/// @dev Used to track which withdrawal hash was used for each invoice
mapping(bytes32 => bytes32) public invoiceToWithdrawalHash;
/// @notice Full `WithdrawalTransaction` stored at prove time, keyed by the PER-OPERATION invoice HASH (ADR 0025).
/// @dev Lets the settlement keeper read back the exact struct needed to FINALIZE an already-proven L2->L1
/// withdrawal via `getWithdrawalTransaction`, instead of re-deriving it from the source L2 `MessagePassed`
/// log over a >7-day window. Keyed by the invoice HASH (the checksum, unique per operation), NOT the route
/// `invoiceId` (reused by every same-lane transfer): two same-lane withdrawals proven in the same window
/// would otherwise collide, the second overwriting the first's tx. MUST be `private` with an explicit struct
/// getter: a `public` auto-getter silently drops the struct's dynamic `data` member.
mapping(bytes32 => Types.WithdrawalTransaction) private _withdrawalTxByInvoiceHash;
/// @notice Marks a withdrawal hash whose funds have already settled an invoice on this adapter.
/// @dev One-shot settlement guard: a single L2->L1 withdrawal delivers its funds once and must settle exactly one
/// invoice. The normal finalize branch is naturally one-shot (the portal reverts on a second
/// `finalizeWithdrawalTransaction`), but the already-finalized skip-branch keys off the messenger's
/// `successfulMessages` flag, which is set PERMANENTLY and never consumed — so without this guard the same
/// proven+finalized withdrawal filed under two invoice hashes could settle both from the adapter's balance.
/// Set on first settlement in `_finalizeWithdrawal`; a re-use reverts.
mapping(bytes32 => bool) private _settledWithdrawals;
/// @notice L1 token -> L2 token per destination L2 chain id (L1 side only).
/// @dev Used for ERC20 deposits (L1 → L2). Unmapped (zero) is FAIL-CLOSED: `_depositToL2` reverts
/// `L2TokenNotConfigured` — there is NO same-address fallback, so every ERC20 route must be wired via
/// `setL2TokenForL2` first. Keyed per L2 because the same L1 token maps to different L2 token addresses.
mapping(uint256 => mapping(address => address)) public l1ToL2TokenForL2;
/// @notice Default L2 gas limit for deposits
uint32 public defaultL2GasLimit = 200000;
/// @notice Default L1 gas limit for withdrawals
uint32 public defaultL1GasLimit = 200000;
/// @notice Min-gas limit for the authenticated `completeDeposit` cross-domain message (L1 → L2).
/// @dev Sized for the L2 relay to run `completeDeposit` → `escrow.recordDelivery` (heavier than a bare deposit),
/// so 200k (`defaultL2GasLimit`) would risk a failed relay. Set in `initialize` (an inline initializer does
/// not reach proxy storage); adjustable via `setCompleteDepositGasLimit`.
uint32 public completeDepositGasLimit;
/// @param expectedInitializer_ Address permitted to call initialize (address(0) allows anyone).
constructor(address expectedInitializer_) BridgeAdapter(expectedInitializer_) {}
/// @inheritdoc ISuperchainBridgeAdapter
/// @dev The L1 per-L2 bridges/portals are seeded post-init via setL1BridgeForL2 / setOptimismPortalForL2
/// (one call per destination/source L2), since a single value cannot key a map by L2 chain id.
function initialize(
address admin_,
address bridgeEscrow_,
address l2Bridge_,
address l1Messenger_,
address l2Messenger_,
uint256 l1ChainId_,
string memory version_
) external {
// Initialize parent BridgeAdapter (single source of truth for admin, bridgeEscrow, provider name, version)
super._initializeBridgeAdapter(admin_, bridgeEscrow_, "Superchain", version_);
chainId = block.chainid;
if (l1ChainId_ == 0) revert InvalidChainId();
l1ChainId = l1ChainId_;
// Set here (not as an inline initializer, which does not reach proxy storage).
completeDepositGasLimit = 500000;
// The adapter plays the L1 role when it is deployed on the configured L1 chain. On L1 the per-L2 bridges /
// portals / messengers are seeded post-init via setters; the legacy single `l1Messenger` is stored for
// config compatibility but the OUTBOUND deposit message uses `l1MessengerForL2` (per destination L2).
if (chainId == l1ChainId_) {
// Fail closed on a deploy-config role flip: L1 mode must NOT be given L2-only contracts. If an L2
// deployment mis-sets `l1ChainId_ == block.chainid`, its L2-shaped args (l2Bridge/l2Messenger, always
// supplied on an L2 deploy) trip this immediately at init instead of failing on the first bridge (RE5-L-01).
if (l2Bridge_ != address(0) || l2Messenger_ != address(0)) revert InvalidChainId();
l1Messenger = l1Messenger_;
} else {
// On L2, only initialize L2 contracts
if (l2Bridge_ == address(0)) revert InvalidL2Bridge();
if (l2Messenger_ == address(0)) revert InvalidCrossDomainMessenger();
l2Bridge = IL2StandardBridge(l2Bridge_);
l2Messenger = l2Messenger_;
}
}
//
// Configuration
//
/// @inheritdoc ISuperchainBridgeAdapter
function setL1BridgeForL2(uint256 l2ChainId, address l1Bridge_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (chainId != l1ChainId) revert InvalidChainId();
if (l1Bridge_ == address(0)) revert InvalidL1Bridge();
l1BridgeForL2[l2ChainId] = IL1StandardBridge(l1Bridge_);
}
/// @inheritdoc ISuperchainBridgeAdapter
function setL2Bridge(address l2Bridge_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (chainId == l1ChainId) revert InvalidChainId();
if (l2Bridge_ == address(0)) revert InvalidL2Bridge();
l2Bridge = IL2StandardBridge(l2Bridge_);
}
/// @inheritdoc ISuperchainBridgeAdapter
function setL1Messenger(address l1Messenger_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (chainId != l1ChainId) revert InvalidChainId();
if (l1Messenger_ == address(0)) revert InvalidCrossDomainMessenger();
l1Messenger = l1Messenger_;
}
/// @inheritdoc ISuperchainBridgeAdapter
function setL1MessengerForL2(uint256 l2ChainId, address l1Messenger_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (chainId != l1ChainId) revert InvalidChainId();
if (l1Messenger_ == address(0)) revert InvalidCrossDomainMessenger();
l1MessengerForL2[l2ChainId] = l1Messenger_;
}
/// @inheritdoc ISuperchainBridgeAdapter
function setL2Messenger(address l2Messenger_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (chainId == l1ChainId) revert InvalidChainId();
if (l2Messenger_ == address(0)) revert InvalidCrossDomainMessenger();
l2Messenger = l2Messenger_;
}
/// @inheritdoc ISuperchainBridgeAdapter
function setOptimismPortalForL2(uint256 l2ChainId, address optimismPortal_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (chainId != l1ChainId) revert InvalidChainId();
if (optimismPortal_ == address(0)) revert InvalidOptimismPortal();
optimismPortalForL2[l2ChainId] = IOptimismPortal(optimismPortal_);
}
/// @notice Sets the default L2 gas limit for deposits
/// @param gasLimit The gas limit to use
/// @dev Only callable by admin role
function setDefaultL2GasLimit(uint32 gasLimit) external onlyRole(DEFAULT_ADMIN_ROLE) {
defaultL2GasLimit = gasLimit;
}
/// @notice Sets the default L1 gas limit for withdrawals
/// @param gasLimit The gas limit to use
/// @dev Only callable by admin role
function setDefaultL1GasLimit(uint32 gasLimit) external onlyRole(DEFAULT_ADMIN_ROLE) {
defaultL1GasLimit = gasLimit;
}
/// @notice Sets the min-gas limit for the authenticated `completeDeposit` cross-domain message.
/// @param gasLimit The gas limit to use (sized for the L2 `completeDeposit` → `recordDelivery` relay).
/// @dev Only callable by admin role.
function setCompleteDepositGasLimit(uint32 gasLimit) external onlyRole(DEFAULT_ADMIN_ROLE) {
completeDepositGasLimit = gasLimit;
}
/// @notice Sets the L2 token address for a given (destination L2 chain id, L1 token).
/// @param l2ChainId The destination L2 chain id
/// @param l1Token The L1 token address
/// @param l2Token The corresponding L2 token address
/// @dev Only callable by admin role. L1-only (the map is read only in the L1→L2 deposit path), so it enforces
/// `chainId == l1ChainId` like `setL1BridgeForL2`/`setOptimismPortalForL2`. An unmapped ERC20 fails closed
/// in `_depositToL2` (it must NOT default to the L1 address).
function setL2TokenForL2(uint256 l2ChainId, address l1Token, address l2Token)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
if (chainId != l1ChainId) revert InvalidChainId();
l1ToL2TokenForL2[l2ChainId][l1Token] = l2Token;
}
//
// BridgeAdapter Implementation (outbound)
//
/// @inheritdoc BridgeAdapter
/// @dev Handles both L1 → L2 deposits and L2 → L1 withdrawals
function _bridge(InvoiceDataLib.InvoiceData memory data) internal override {
// Encode messagePayload for Cross-Domain Messenger
bytes memory messagePayload = InvoiceDataLib.encode(data);
// Get asset address from registry
address asset = IBridgeEscrow(bridgeEscrow).assetRegistry(InvoiceDataLib.bytes6ToStr(data.assetSymbol));
bool isEth = _isNativeToken(asset);
// If we're on L1 (mainnet), it's an L1 → L2 deposit; otherwise an L2 → L1 withdrawal.
if (chainId == l1ChainId) {
if (address(l1BridgeForL2[data.destinationChainId]) == address(0)) revert InvalidL1Bridge();
_depositToL2(data, asset, isEth, messagePayload);
} else {
if (address(l2Bridge) == address(0)) revert InvalidL2Bridge();
_withdrawToL1(data, asset, isEth, messagePayload);
}
}
/// @notice Handles L1 → L2 deposit
/// @dev Recipient on L2 is the sibling adapter (`address(this)`, same address via CREATE2). The canonical
/// bridge delivers the ETH/tokens to the L2 sibling; the L1 adapter also sends an AUTHENTICATED
/// `completeDeposit` message through the L1CrossDomainMessenger so the L2 sibling records the delivery
/// with provenance (not merely a MANAGER-attested balance check). Deposit funds are ordered ahead of
/// the message on L2 (portal deposit nonce order), so `completeDeposit` sees the funds already present.
function _depositToL2(
InvoiceDataLib.InvoiceData memory data,
address asset,
bool isEth,
bytes memory messagePayload
) internal {
address receiver = address(this);
// Select the L1 standard bridge for the destination L2 (OP vs Base have distinct bridges).
IL1StandardBridge bridge = l1BridgeForL2[data.destinationChainId];
if (isEth) {
bridge.depositETHTo{value: data.amount}(receiver, defaultL2GasLimit, messagePayload);
} else {
// Resolve the L2 token BEFORE pulling funds. Fail closed: an unmapped ERC20 must NOT default to the
// L1 address (wrong on L2 for tokens like WETH → the deposit would be unfinalizable / locked). Any ERC20
// Superchain route must be wired via `setL2TokenForL2` first.
address l2Token = l1ToL2TokenForL2[data.destinationChainId][asset];
if (l2Token == address(0)) revert L2TokenNotConfigured(data.destinationChainId, asset);
// Pull ERC20 tokens from escrow (escrow approved us in depositAndBridge), approve, and deposit to L2.
IERC20(asset).safeTransferFrom(bridgeEscrow, address(this), data.amount);
IERC20(asset).forceApprove(address(bridge), data.amount);
bridge.depositERC20To(asset, l2Token, receiver, data.amount, defaultL2GasLimit, messagePayload);
// Reset the allowance (the standard bridge pulls exactly `amount`; leave no dangling approval).
IERC20(asset).forceApprove(address(bridge), 0);
}
// Deliver an authenticated completion to the L2 sibling via the destination L2's L1CrossDomainMessenger.
// OP and Base have DISTINCT L1 messengers, so it MUST be keyed per destination L2 (a single messenger would
// route Base deposits through OP's messenger). The canonical bridge deposit above is ordered ahead of this
// message on L2, so when the sibling's `completeDeposit` runs the funds have landed. Without this message the
// L2-side authenticated path is unreachable (the standard bridge relays to the L2 bridge with empty calldata,
// never the adapter), leaving only the un-provenanced MANAGER `completeBridge` backstop.
address messenger = l1MessengerForL2[data.destinationChainId];
if (messenger == address(0)) revert MessengerNotConfigured(data.destinationChainId);
ICrossDomainMessenger(messenger)
.sendMessage(
address(this),
abi.encodeWithSelector(this.completeDeposit.selector, messagePayload),
completeDepositGasLimit
);
// Store messagePayload for later retrieval, keyed by the per-operation invoice hash (concurrent same-lane
// transfers reuse the route invoiceId, so keying by it would overwrite a sibling operation's payload).
messagePayloads[bytes32(uint256(uint192(data.checksum24)))] = messagePayload;
emit SuperchainBridgeInitiated(data.invoiceId, uint64(data.destinationChainId), bytes32(data.amount), isEth);
}
/// @notice Handles L2 → L1 withdrawal
/// @dev Recipient on L1 is the sibling adapter (`address(this)`). The real OP withdrawal hash is only
/// known on L1 (it depends on the L2ToL1MessagePasser nonce), so invoice↔withdrawalHash correlation
/// is established on L1 at prove time (see `proveWithdrawal`) from the actual WithdrawalTransaction.
function _withdrawToL1(
InvoiceDataLib.InvoiceData memory data,
address asset,
bool isEth,
bytes memory messagePayload
) internal {
address receiver = address(this);
if (isEth) {
// For ETH, _l2Token is the legacy ERC20 ETH predeploy.
address legacyErc20Eth = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000;
l2Bridge.withdrawTo{value: data.amount}(
legacyErc20Eth, receiver, data.amount, defaultL1GasLimit, messagePayload
);
} else {
// Pull ERC20 tokens from escrow (escrow approved us in depositAndBridge)
IERC20(asset).safeTransferFrom(bridgeEscrow, address(this), data.amount);
IERC20(asset).forceApprove(address(l2Bridge), data.amount);
l2Bridge.withdrawTo(asset, receiver, data.amount, defaultL1GasLimit, messagePayload);
// Reset the allowance (leave no dangling approval to the L2 bridge).
IERC20(asset).forceApprove(address(l2Bridge), 0);
}
// Store messagePayload for later retrieval (withdrawal hash is set on L1 at prove time), keyed by the
// per-operation invoice hash so concurrent same-lane withdrawals don't overwrite each other's payload.
messagePayloads[bytes32(uint256(uint192(data.checksum24)))] = messagePayload;
emit SuperchainWithdrawalInitiated(
data.invoiceId, uint64(data.destinationChainId), bytes32(data.amount), bytes32(0)
);
}
//
// Provenance helpers
//
/// @notice Computes the canonical OP Stack withdrawal hash for a withdrawal transaction.
/// @dev Matches `Hashing.hashWithdrawal`: `keccak256(abi.encode(nonce, sender, target, value, gasLimit, data))`.
function _hashWithdrawal(Types.WithdrawalTransaction memory wtx) internal pure returns (bytes32) {
// forge-lint: disable-next-line(asm-keccak256)
return keccak256(abi.encode(wtx.nonce, wtx.sender, wtx.target, wtx.value, wtx.gasLimit, wtx.data));
}
/// @notice Authenticates an inbound cross-domain message relayed by the L2CrossDomainMessenger.
/// @dev Provenance check for L1 → L2 deposit completion: the genuine messenger must be the caller and the
/// original source-chain sender (revealed by `xDomainMessageSender()`) must be the trusted sibling
/// adapter configured for `srcChainId`.
/// @param srcChainId The source chain id carried in the invoice (the L1 chain for a deposit).
function _authenticateMessengerSource(uint64 srcChainId) internal view {
if (msg.sender != l2Messenger) revert NotAuthorized();
bytes32 expected = trustedRemoteAdapter[srcChainId];
if (expected == bytes32(0)) revert NotAuthorized();
address xSender = ICrossDomainMessenger(l2Messenger).xDomainMessageSender();
if (_toBytes32(xSender) != expected) revert NotAuthorized();
}
//
// BridgeAdapter Implementation (inbound completion)
//
/// @inheritdoc BridgeAdapter
/// @dev MANAGER-operated completion. Performs only protocol verification here; the base
/// (`completeBridge`) then funds the escrow, which records the delivery into custody (hold-then-claim, ADR 0024).
/// - On L1 (an L2 → L1 withdrawal completion): finalize the proven withdrawal through the portal,
/// which delivers the ETH to this adapter; the base then releases.
/// - On L2 (an L1 → L2 deposit completion fallback): the canonical bridge already delivered the
/// tokens to this adapter; nothing to do here beyond bookkeeping. (The trust-minimized auto path
/// is `completeDeposit`, authenticated against the L2CrossDomainMessenger.)
function _completeBridge(
bytes calldata messagePayload,
bytes calldata /* protocolData */
)
internal
override
{
if (messagePayload.length == 0) revert InvalidCompletionData();
InvoiceDataLib.InvoiceData memory data = InvoiceDataLib.decode(messagePayload);
if (chainId == l1ChainId) {
// L2 → L1 withdrawal: finalize via the portal (proof-gated). Bind the withdrawal to THIS invoice by
// reading the tx stored at prove time under the per-operation invoice hash (ADR 0025), rather than
// trusting the operator-supplied protocolData — the route invoiceId is reused per lane and cannot
// distinguish concurrent same-lane withdrawals, so an unbound protocolData could settle invoice B with
// invoice A's withdrawal. `protocolData` is now ignored (kept for ABI parity).
bytes32 invoiceHash = bytes32(uint256(uint192(data.checksum24)));
Types.WithdrawalTransaction memory withdrawalTx = _withdrawalTxByInvoiceHash[invoiceHash];
// A real stored tx targets the L1CrossDomainMessenger (nonzero); a zero target means nothing was proven
// for this exact invoice.
if (withdrawalTx.target == address(0)) revert WithdrawalNotProven();
address asset = IBridgeEscrow(bridgeEscrow).assetRegistry(InvoiceDataLib.bytes6ToStr(data.assetSymbol));
// Finalize through the portal for the SOURCE L2 (the same L2 whose portal proved it).
_finalizeWithdrawal(withdrawalTx, data.amount, asset, uint256(data.sourceChainId));
// Clear the per-operation prove-time state now that the withdrawal is finalized (storage hygiene; the
// escrow's replay guard already prevents re-completion). The route-keyed correlation map is left as-is
// (reused per lane, overwritten on the next prove).
delete withdrawalHashToInvoiceId[_hashWithdrawal(withdrawalTx)];
delete _withdrawalTxByInvoiceHash[invoiceHash];
delete messagePayloads[invoiceHash];
} else {
// On L2 the tokens were delivered to this adapter by the canonical bridge; the base verifies the adapter
// balance covers `amount` in `_fundAndRelease`. Record the payload (keyed per-op) for bookkeeping.
messagePayloads[bytes32(uint256(uint192(data.checksum24)))] = messagePayload;
}
emit SuperchainBridgeCompleted(data.invoiceId, uint64(data.sourceChainId));
}
/// @notice Trust-minimized L1 → L2 deposit completion: the L2CrossDomainMessenger relays the deposit
/// message to this adapter, which authenticates the messenger + source sender, then funds the
/// escrow, which records the delivery into custody (hold-then-claim, ADR 0024).
/// @param messagePayload The encoded invoice payload authored on L1 (forwarded through the messenger).
/// @dev Authenticated path (no MANAGER role): `msg.sender == l2Messenger` and
/// `l2Messenger.xDomainMessageSender() == trustedRemoteAdapter[srcChainId]`. The canonical bridge
/// credits the adapter with the bridged ETH/tokens before the messenger relays this call.
function completeDeposit(bytes calldata messagePayload) external nonReentrant {
if (messagePayload.length == 0) revert InvalidCompletionData();
InvoiceDataLib.InvoiceData memory data = InvoiceDataLib.decode(messagePayload);
// Provenance: genuine L2 messenger + trusted sibling adapter as the L1 source sender.
_authenticateMessengerSource(uint64(data.sourceChainId));
address asset = IBridgeEscrow(bridgeEscrow).assetRegistry(InvoiceDataLib.bytes6ToStr(data.assetSymbol));
// Keyed by the per-operation invoice hash (concurrent same-lane deposits reuse the route invoiceId).
messagePayloads[bytes32(uint256(uint192(data.checksum24)))] = messagePayload;
// Funds-and-releases: the escrow validates checksum/replay/account and forwards to the account.
_fundAndRelease(messagePayload, asset, data.amount);
emit SuperchainBridgeCompleted(data.invoiceId, uint64(data.sourceChainId));
}
/// @notice Finalizes a proven withdrawal (L2 → L1) through the portal so the funds are delivered to this adapter.
/// @param withdrawalTx The withdrawal transaction, read from storage bound to the invoice (see `_completeBridge`).
/// @param amount The invoiced amount.
/// @param asset The delivered asset (native sentinel or ERC20); selects the balance to measure.
/// @param l2ChainId The source L2 chain id selecting the OptimismPortal.
/// @dev A withdrawal initiated via `L2StandardBridge.withdrawTo` does NOT produce a portal transaction whose
/// `target` is this adapter: the L2 messenger sends it to the L1CrossDomainMessenger (the portal `target`),
/// which relays `finalizeBridge{ETH,ERC20}` to the L1 StandardBridge, and only that nested call pays this
/// adapter (the `withdrawTo` receiver). Two consequences handled here:
/// 1. Idempotency (H-01): the portal's finalize is PERMISSIONLESS and reverts on a second call, so a
/// third party can front-run it. If already finalized, skip the re-finalize instead of reverting the
/// whole completion — but confirm the withdrawal's relay was delivered (see 3; recipient axis is a
/// documented MANAGER-gated residual, not bound on-chain).
/// 2. Amount binding (M-02): the amount is bound not by the portal `target`/`value` but by what the
/// adapter actually receives across the finalize — measure the asset-balance delta and require it to
/// cover `amount` (for BOTH native and ERC20).
/// 3. Front-run delivery check (RE4-M-01): the portal marks a withdrawal finalized even if its inner
/// relay FAILED (funds undelivered). For an already-finalized withdrawal (no measurable delta), require
/// the L1CrossDomainMessenger to report the withdrawal's inner message delivered (a FAILED relay is
/// rejected). NOTE this proves the relay reached its ENCODED recipient, not that the recipient is this
/// adapter — the inner `to` is not decoded here; a MANAGER mis-pairing to a genuine third-party-paying
/// withdrawal remains a documented residual (see the skip-branch body + ADR 0026), MANAGER-gated, no theft.
/// Provenance comes from the proven withdrawal hash (keyed by this adapter as proof submitter, fault-proof
/// OP2) + portal Merkle proof; the portal enforces the proof-maturity + dispute-game-finality air-gap.
function _finalizeWithdrawal(
Types.WithdrawalTransaction memory withdrawalTx,
uint256 amount,
address asset,
uint256 l2ChainId
) internal {
// Select the OptimismPortal for the source L2 (the same L2 whose portal the withdrawal was proven on).
IOptimismPortal portal = optimismPortalForL2[l2ChainId];
if (address(portal) == address(0)) revert InvalidOptimismPortal();
bytes32 withdrawalHash = _hashWithdrawal(withdrawalTx);
// Verify the withdrawal has been proven (fault-proof OP2: keyed by hash AND proof submitter — this adapter,
// which called `proveWithdrawalTransaction`; proven ⟺ a non-zero dispute game is recorded).
(address disputeGameProxy,) = portal.provenWithdrawals(withdrawalHash, address(this));
if (disputeGameProxy == address(0)) revert WithdrawalNotProven();
// One-shot settlement: a withdrawal delivers its funds once, so it settles exactly one invoice. This makes
// the already-finalized skip-branch (which keys off the messenger's PERMANENT `successfulMessages` flag) as
// reuse-proof as the normal branch (where the portal reverts on a second finalize) — the same proven+finalized
// withdrawal filed under two invoice hashes cannot settle both from the adapter's balance. Set before any
// external call; a revert below rolls it back.
if (_settledWithdrawals[withdrawalHash]) revert InvalidWithdrawalFinalization();
_settledWithdrawals[withdrawalHash] = true;
// Finalize idempotently: skip if a front-run already finalized it (the portal's finalize is permissionless
// and reverts on a second call).
if (!portal.finalizedWithdrawals(withdrawalHash)) {
bool isEth = _isNativeToken(asset);
uint256 balanceBefore = isEth ? address(this).balance : IERC20(asset).balanceOf(address(this));
portal.finalizeWithdrawalTransaction(withdrawalTx);
uint256 balanceAfter = isEth ? address(this).balance : IERC20(asset).balanceOf(address(this));
// Bind the amount to THIS finalize: the delivered delta must cover `amount` (not merely the adapter's
// total balance, which stray/donated funds could satisfy).
if (balanceAfter < balanceBefore + amount) revert InvalidWithdrawalFinalization();
} else {
// Already finalized (front-run): the delivered delta cannot be measured for a past finalize, and the
// portal marks a withdrawal finalized even when its inner relay FAILED (funds not delivered) — so a bare
// absolute-balance check could settle THIS invoice from stray/sibling funds. Confirm the withdrawal's
// relay message was successfully delivered: the L1CrossDomainMessenger (the withdrawal `target`) records a
// message as successful only if its nested `finalizeBridge{ETH,ERC20}` call did not revert. For a Bedrock v1
// message the versioned hash equals keccak256 of the relayMessage calldata, which is exactly
// `withdrawalTx.data` (what the portal delivered to the messenger). Bind the `target` to THIS L2's
// configured L1CrossDomainMessenger first, so `successfulMessages` is read from the genuine messenger and
// not an attacker-authored withdrawal whose `target` is a contract returning a spoofed `true`.
// ⚠ RESIDUAL (MANAGER-gated, no theft): `successfulMessages` proves the relay succeeded to the recipient
// ENCODED IN `withdrawalTx.data`, NOT that that recipient is THIS adapter — the inner `to` is not decoded
// here (a version-brittle relayMessage→finalizeBridge decode). Combined with the base's ABSOLUTE-balance
// settle, a MANAGER mis-pairing invoice B to a genuine third-party-paying withdrawal, while the adapter
// holds another invoice's funds, could settle B from those funds (cross-invoice MISALLOCATION, not
// exfiltration). Same class as the ERC20 amount residual — validated at the real L2->L1 e2e before deploy
// (ADR 0026). The normal (non-front-run) branch has no such gap (its measured balance delta binds delivery).
// The source L2's L1CrossDomainMessenger must be wired (l1MessengerForL2 is used for BOTH deposit dest-L2
// routing AND this withdrawal-finalize target binding). A distinct error makes a partial config (portal
// wired via setOptimismPortalForL2 but messenger not) obvious rather than a generic finalize revert.
if (l1MessengerForL2[l2ChainId] == address(0)) revert MessengerNotConfigured(l2ChainId);
if (withdrawalTx.target != l1MessengerForL2[l2ChainId]) revert InvalidWithdrawalFinalization();
// Bind the delivered amount the normal branch's delta would have enforced. For a StandardBridge ETH
// withdrawal the portal delivers `withdrawalTx.value` to the adapter, so a mis-paired smaller withdrawal
// (value < amount) settling this invoice from stray/sibling funds is rejected here. (ERC20 carries the
// amount inside the relay calldata with value==0, so this native-only check can't bind it — Superchain is
// ETH-primary + ERC20 deposits are fail-closed; the ERC20 amount/recipient binding is validated at the
// real L2->L1 e2e before the lane deploys.)
if (_isNativeToken(asset) && withdrawalTx.value < amount) revert InvalidWithdrawalFinalization();
// forge-lint: disable-next-line(asm-keccak256)
bytes32 innerMessageHash = keccak256(withdrawalTx.data);
if (!ICrossDomainMessenger(withdrawalTx.target).successfulMessages(innerMessageHash)) {
revert InvalidWithdrawalFinalization();
}
}
}
/// @notice Proves a withdrawal transaction and correlates it to its invoice.
/// @param l2ChainId The source L2 chain id selecting the OptimismPortal. MUST equal the invoice's
/// `sourceChainId` — completion (`_finalizeWithdrawal`) selects the portal from the invoice's
/// `sourceChainId`, so proving against a different L2's portal here would make finalize revert
/// `WithdrawalNotProven` (no fund loss, but the withdrawal cannot be completed until re-proven).
/// Enforced on-chain against the payload's encoded source chain id (reverts `WithdrawalChainIdMismatch`).
/// @param withdrawalTx The withdrawal transaction to prove (its `target` is the L1CrossDomainMessenger, which
/// relays the L1-bridge call that pays this adapter as the `withdrawTo` receiver — see `_finalizeWithdrawal`).
/// @param disputeGameIndex The dispute-game index the withdrawal is proven against (fault-proof OP2; was the L2
/// output index on the legacy portal)
/// @param outputRootProof The output root proof
/// @param withdrawalProof The withdrawal proof
/// @param messagePayload The encoded invoice payload (the same bytes used at deposit/completion). BOTH keys — the
/// route `invoiceId` and the per-operation `invoiceHash` (ADR 0025) — are DERIVED from it on-chain, exactly
/// as `_completeBridge` derives them, so an operator can never supply a mismatched/typo'd key that overwrites
/// another operation's stored tx or files the tx under a key completion never looks up.
/// @dev MANAGER-driven on L1 after the withdrawal is initiated on L2. Computes the REAL OP withdrawal
/// hash and records the invoice correlation so completion can be tracked.
function proveWithdrawal(
uint256 l2ChainId,
Types.WithdrawalTransaction memory withdrawalTx,
uint256 disputeGameIndex,
Types.OutputRootProof memory outputRootProof,
bytes[] calldata withdrawalProof,
bytes calldata messagePayload
) external onlyRole(MANAGER_ROLE) {
// Derive BOTH invoice keys on-chain from the invoice payload — EXACTLY as `_completeBridge` does — so the
// operator cannot supply a mismatched/typo'd `invoiceHash` that overwrites another op's stored tx (or files
// the tx under a key completion never looks up). This removes the operator-supplied-key mis-correlation class.
if (messagePayload.length == 0) revert InvalidWithdrawalProof();
InvoiceDataLib.InvoiceData memory data = InvoiceDataLib.decode(messagePayload);
// Mirror the escrow's `recordDelivery` payload validation at prove time (amount + checksum), because the
// `WithdrawalTransaction` is STORED here with no later validation of the key's genuineness — completion trusts
// the stored tx. Two guards, in the escrow's order:
// 1. amount != 0 — a zero-amount payload can never complete (recordDelivery rejects it), so storing a tx
// under its key is pure un-completable dust; reject it at the source.
// 2. checksum bound to the payload's OWN (invoiceId, amount, timestamp, nonce) — without this, an
// internally-inconsistent payload whose checksum (hence `invoiceHash` key) is borrowed from another live
// operation but whose `invoiceId` differs would derive that operation's key and overwrite its stored tx
// (and cross-wire the correlation maps). Anchoring the key to a self-consistent checksum makes the two
// keys jointly non-forgeable, not merely non-typo'able.
if (data.amount == 0) revert InvalidWithdrawalProof();
if (
data.checksum24 != InvoiceDataLib.calculateChecksum(data.invoiceId, data.amount, data.timestamp, data.nonce)
) {
revert InvalidWithdrawalProof();
}
bytes32 invoiceId = data.invoiceId;
bytes32 invoiceHash = bytes32(uint256(uint192(data.checksum24)));
if (invoiceId == bytes32(0) || invoiceHash == bytes32(0)) revert InvalidWithdrawalProof();
// Enforce the payload's encoded source chain id matches l2ChainId (top 3 bytes of
// the invoice id — see BridgeEscrow._generateInvoiceId). Finalize selects the portal from the invoice's
// sourceChainId, so proving against a different L2's portal would strand the withdrawal (WithdrawalNotProven
// until re-proven). Fail fast on the operator mistake instead of proving on the wrong portal.
uint256 encodedSrc = uint256(invoiceId) >> 232;
if (encodedSrc != l2ChainId) revert WithdrawalChainIdMismatch(l2ChainId, encodedSrc);
// Prove against the portal for the source L2; finalize must later use the SAME l2ChainId
// (the invoice's sourceChainId flows through both, so they match).
IOptimismPortal portal = optimismPortalForL2[l2ChainId];
if (address(portal) == address(0)) revert InvalidOptimismPortal();
bytes32 withdrawalHash = _hashWithdrawal(withdrawalTx);
portal.proveWithdrawalTransaction(withdrawalTx, disputeGameIndex, outputRootProof, withdrawalProof);
// Correlate invoice ↔ real withdrawal hash (both keys are guaranteed non-zero by the guard above).
withdrawalHashToInvoiceId[withdrawalHash] = invoiceId;
invoiceToWithdrawalHash[invoiceId] = withdrawalHash;
emit SuperchainWithdrawalProven(invoiceId, withdrawalHash);
// Store the tx under the PER-OPERATION invoice hash (ADR 0025) so the keeper can finalize without an L2 log
// re-read. The hash is derived on-chain above (from the payload), so it is exactly the key completion looks up
// — no operator mismatch and no cross-operation overwrite is possible.
_withdrawalTxByInvoiceHash[invoiceHash] = withdrawalTx;
}
//
// View Functions
//
/// @inheritdoc ISuperchainBridgeAdapter
function getMessagePayload(bytes32 invoiceHash) external view returns (bytes memory) {
return messagePayloads[invoiceHash];
}
/// @inheritdoc ISuperchainBridgeAdapter
function getWithdrawalTransaction(bytes32 invoiceHash) external view returns (Types.WithdrawalTransaction memory) {
return _withdrawalTxByInvoiceHash[invoiceHash];
}
/// @inheritdoc ISuperchainBridgeAdapter
function getWithdrawalHashByInvoiceId(bytes32 invoiceId) external view returns (bytes32) {
return invoiceToWithdrawalHash[invoiceId];
}
/// @inheritdoc ISuperchainBridgeAdapter
function getInvoiceIdByWithdrawalHash(bytes32 withdrawalHash) external view returns (bytes32) {
return withdrawalHashToInvoiceId[withdrawalHash];
}
/// @inheritdoc ISuperchainBridgeAdapter
function isWithdrawalProven(uint256 l2ChainId, bytes32 withdrawalHash) external view returns (bool) {
IOptimismPortal portal = optimismPortalForL2[l2ChainId];
if (address(portal) == address(0)) return false;
// Fault-proof OP2: proven ⟺ a non-zero dispute game is recorded for (hash, this adapter as proof submitter).
(address disputeGameProxy,) = portal.provenWithdrawals(withdrawalHash, address(this));
return disputeGameProxy != address(0);
}
/// @inheritdoc ISuperchainBridgeAdapter
function canFinalizeWithdrawal(uint256 l2ChainId, bytes32 withdrawalHash) external view returns (bool) {
// The portal enforces the actual proof-maturity + dispute-game air-gap at finalize; this reports proven-ness.
IOptimismPortal portal = optimismPortalForL2[l2ChainId];
if (address(portal) == address(0)) return false;
(address disputeGameProxy,) = portal.provenWithdrawals(withdrawalHash, address(this));
return disputeGameProxy != address(0);
}
/// @notice Computes the canonical OP Stack withdrawal hash for a withdrawal transaction.
/// @param withdrawalTx The withdrawal transaction
/// @return The real OP withdrawal hash (matches `Hashing.hashWithdrawal`)
function hashWithdrawal(Types.WithdrawalTransaction memory withdrawalTx) external pure returns (bytes32) {
return _hashWithdrawal(withdrawalTx);
}
//
// Receive Function
//
/// @notice Receives native ETH (canonical bridge deposits / portal withdrawal finalization deliver here).
receive() external payable {}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
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-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @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-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @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 {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 relies 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 relies 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}.
* Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts-upgradeable/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-upgradeable/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev A uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/optimism/packages/contracts-bedrock/src/libraries/Types.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Types
/// @notice Contains various types used throughout the Optimism contract system.
library Types {
/// @notice OutputProposal represents a commitment to the L2 state. The timestamp is the L1
/// timestamp that the output root is posted. This timestamp is used to verify that the
/// finalization period has passed since the output root was submitted.
/// @custom:field outputRoot Hash of the L2 output.
/// @custom:field timestamp Timestamp of the L1 block that the output root was submitted in.
/// @custom:field l2BlockNumber L2 block number that the output corresponds to.
struct OutputProposal {
bytes32 outputRoot;
uint128 timestamp;
uint128 l2BlockNumber;
}
/// @notice Struct representing the elements that are hashed together to generate an output root
/// which itself represents a snapshot of the L2 state.
/// @custom:field version Version of the output root.
/// @custom:field stateRoot Root of the state trie at the block of this output.
/// @custom:field messagePasserStorageRoot Root of the message passer storage trie.
/// @custom:field latestBlockhash Hash of the block this output was generated from.
struct OutputRootProof {
bytes32 version;
bytes32 stateRoot;
bytes32 messagePasserStorageRoot;
bytes32 latestBlockhash;
}
/// @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end
/// user (as opposed to a system deposit transaction generated by the system).
/// @custom:field from Address of the sender of the transaction.
/// @custom:field to Address of the recipient of the transaction.
/// @custom:field isCreation True if the transaction is a contract creation.
/// @custom:field value Value to send to the recipient.
/// @custom:field mint Amount of ETH to mint.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
/// @custom:field l1BlockHash Hash of the block the transaction was submitted in.
/// @custom:field logIndex Index of the log in the block the transaction was submitted in.
struct UserDepositTransaction {
address from;
address to;
bool isCreation;
uint256 value;
uint256 mint;
uint64 gasLimit;
bytes data;
bytes32 l1BlockHash;
uint256 logIndex;
}
/// @notice Struct representing a withdrawal transaction.
/// @custom:field nonce Nonce of the withdrawal transaction
/// @custom:field sender Address of the sender of the transaction.
/// @custom:field target Address of the recipient of the transaction.
/// @custom:field value Value to send to the recipient.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
struct WithdrawalTransaction {
uint256 nonce;
address sender;
address target;
uint256 value;
uint256 gasLimit;
bytes data;
}
}
src/bridge/BridgeAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IBridgeAdapter} from "./IBridgeAdapter.sol";
import {IBridgeEscrow} from "./IBridgeEscrow.sol";
import {InvoiceDataLib} from "./InvoiceDataLib.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/constants.sol";
/// @title BridgeAdapter
/// @notice Abstract base for bridge adapters (non-upgradeable, single-initialize).
/// @dev See ADR 0012 and ADR 0024. There is no escrow fallback dispatcher. A bridge is completed via the
/// MANAGER-gated `completeBridge`, which runs the adapter's protocol-specific `_completeBridge` and then
/// funds the escrow per-invoice and calls `BridgeEscrow.recordDelivery` (re-validated by the escrow), which
/// records the delivery into escrow custody; a subsequent MANAGER `BridgeEscrow.claim` pays the account.
/// Each adapter is the direct on-chain recipient; its authenticated completion path verifies the real
/// protocol message + source sender (against `trustedRemoteAdapter`) before recording.
/// @author KPK
abstract contract BridgeAdapter is AccessControl, ReentrancyGuard, IBridgeAdapter {
using SafeERC20 for IERC20;
//
// Constants
//
/// @notice Role for managers who can complete bridges and recover assets
bytes32 public constant MANAGER_ROLE = MANAGER;
/// @notice ERC-7528 convention for ETH address representation (used in some L2s)
address public constant NATIVE_ADDRESS_ERC7528 = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
//
// State Variables
//
/// @notice The BridgeEscrow contract address
address public bridgeEscrow;
/// @notice Bridge provider name (e.g., "CCTP", "Gnosis")
string public bridgeProviderName;
/// @notice Adapter version
string public adapterVersion;
/// @notice Allowlist of trusted sibling adapters on remote chains, keyed by a protocol-specific source key
/// (chainId / CCIP selector / CCTP domain / LZ eid — the adapter defines the key).
/// @dev The inbound value is the remote adapter identity as bytes32 (address widened, or raw bytes32).
/// Concrete adapters consult this in their authenticated callback to verify message provenance.
mapping(uint64 => bytes32) public trustedRemoteAdapter;
bool private _initialized;
/// @notice The only address permitted to call initialize, or address(0) to allow anyone.
/// @dev Set at CREATE2 time (baked into the adapter's creationCode identically on every chain, so the
/// deterministic address is preserved). The adapter address is precomputable and initialize grants
/// DEFAULT_ADMIN_ROLE, so an unrestricted initializer can be front-run: a bot deploys the identical
/// bytecode at the deterministic address and initializes it first. Pinning the initializer closes
/// that window — a bot cannot initialize even after pre-deploying. A zero value disables the guard
/// (used in tests); production bakes the deployer EOA.
address public immutable expectedInitializer;
/// @notice Emitted when a trusted remote adapter is set/updated for a source key
event TrustedRemoteAdapterSet(uint64 indexed sourceKey, bytes32 remoteAdapter);
/// @param expectedInitializer_ The address permitted to call initialize (address(0) allows anyone).
constructor(address expectedInitializer_) {
expectedInitializer = expectedInitializer_;
}
/// @notice One-time initializer for the BridgeAdapter (internal; only for use by derived adapters)
/// @dev Derived adapters expose their own initialize() and call this via super._initializeBridgeAdapter().
function _initializeBridgeAdapter(
address admin_,
address bridgeEscrow_,
string memory providerName_,
string memory version_
) internal {
if (expectedInitializer != address(0) && msg.sender != expectedInitializer) {
revert NotAuthorized();
}
if (_initialized) revert AlreadyInitialized();
if (admin_ == address(0) || bridgeEscrow_ == address(0)) revert InvalidArguments();
_initialized = true;
_grantRole(DEFAULT_ADMIN_ROLE, admin_);
bridgeEscrow = bridgeEscrow_;
bridgeProviderName = providerName_;
adapterVersion = version_;
}
//
// Config
//
/// @notice Sets the trusted remote adapter for a source key (admin only)
/// @param sourceKey Protocol-specific source identifier (chainId / selector / domain / eid)
/// @param remoteAdapter The remote sibling adapter identity (bytes32). bytes32(0) clears it.
function setTrustedRemoteAdapter(uint64 sourceKey, bytes32 remoteAdapter) external onlyRole(DEFAULT_ADMIN_ROLE) {
trustedRemoteAdapter[sourceKey] = remoteAdapter;
emit TrustedRemoteAdapterSet(sourceKey, remoteAdapter);
}
//
// Helper Functions
//
/// @notice Checks if an address represents a native token
function _isNativeToken(address token) internal pure returns (bool) {
return token == address(0) || token == NATIVE_ADDRESS_ERC7528;
}
/// @notice Widens an address to a bytes32 identity (for trustedRemoteAdapter comparisons)
function _toBytes32(address a) internal pure returns (bytes32) {
return bytes32(uint256(uint160(a)));
}
//
// IBridgeAdapter Implementation
//
/// @inheritdoc IBridgeAdapter
function bridge(bytes calldata messagePayload) external override {
if (msg.sender != bridgeEscrow) revert NotAuthorized();
InvoiceDataLib.InvoiceData memory data = InvoiceDataLib.decode(messagePayload);
_bridge(data);
emit BridgeInitiated(data.invoiceId, data.amount);
}
/// @inheritdoc IBridgeAdapter
/// @dev MANAGER-operated completion path. The adapter's `_completeBridge` performs protocol-specific
/// verification (e.g. CCTP attestation, OP withdrawal finalization) and ensures the adapter holds
/// the delivered `amount` of the asset; the base then funds the escrow's per-invoice custody record via
/// `_fundAndRelease` → `recordDelivery` (ADR 0024 hold-then-claim). It does **not** pay the account here —
/// the escrow HOLDS the funds until a separate MANAGER `BridgeEscrow.claim(invoiceHash)`.
function completeBridge(bytes calldata messagePayload, bytes calldata protocolData) external override nonReentrant {
if (!hasRole(MANAGER_ROLE, msg.sender)) revert NotAuthorized();
if (messagePayload.length == 0) revert InvalidCompletionData();
InvoiceDataLib.InvoiceData memory data = InvoiceDataLib.decode(messagePayload);
_completeBridge(messagePayload, protocolData);
address asset = IBridgeEscrow(bridgeEscrow).assetRegistry(InvoiceDataLib.bytes6ToStr(data.assetSymbol));
_fundAndRelease(messagePayload, asset, data.amount);
emit BridgeCompleted(data.invoiceId);
}
/// @notice Hands the escrow exactly `amount` of `asset` and records the delivery into escrow custody (ADR 0024).
/// @dev The adapter must already hold `amount` of `asset` (delivered by the protocol). For ERC20 the escrow
/// pulls via transferFrom (exact approval, reset to 0 after); for native the value is forwarded with the
/// call. The escrow validates checksum/replay/account, MEASURES the received amount, and HOLDS the funds
/// under the invoice until `claim` — it no longer forwards to the account here. Name kept for a minimal
/// diff: every adapter completion path (auto callbacks + the MANAGER `completeBridge`) funnels through
/// this one helper, so this single retarget converts all six adapters to the hold-then-claim model.
function _fundAndRelease(bytes memory messagePayload, address asset, uint256 amount) internal {
if (_isNativeToken(asset)) {
uint256 bal = address(this).balance;
if (bal < amount) revert InsufficientBalance(asset, amount, bal);
IBridgeEscrow(bridgeEscrow).recordDelivery{value: amount}(messagePayload);
} else {
uint256 bal = IERC20(asset).balanceOf(address(this));
if (bal < amount) revert InsufficientBalance(asset, amount, bal);
IERC20(asset).forceApprove(bridgeEscrow, amount);
IBridgeEscrow(bridgeEscrow).recordDelivery(messagePayload);
IERC20(asset).forceApprove(bridgeEscrow, 0);
}
}
/// @inheritdoc IBridgeAdapter
function bridgeProvider() external view override returns (string memory) {
return bridgeProviderName;
}
/// @inheritdoc IBridgeAdapter
function version() external view override returns (string memory) {
return adapterVersion;
}
//
// Abstract Functions
//
/// @notice Implement bridge-specific outbound logic
function _bridge(InvoiceDataLib.InvoiceData memory data) internal virtual;
/// @notice Pushes `amount` of `asset` held by the adapter straight to the escrow and emits TokensTransferredToEscrow.
/// @dev Legacy push-to-escrow helper, NOT on the shipped completion path. `completeBridge` instead calls
/// `_fundAndRelease` (ADR 0024 hold-then-claim), which leaves the funds on the adapter for the escrow
/// to pull on `recordDelivery`. No shipped adapter (CCTP included) calls this; it is retained for
/// derived adapters that would rather hand the escrow the tokens before recording. Reverts InsufficientBalance
/// if the adapter holds less than `amount`, or TransferFailed on a failed native send.
function _transferTokensToEscrow(bytes32 invoiceId, address asset, uint256 amount) internal {
if (_isNativeToken(asset)) {
uint256 adapterBalance = address(this).balance;
if (adapterBalance < amount) revert InsufficientBalance(asset, amount, adapterBalance);
(bool success,) = bridgeEscrow.call{value: amount}("");
if (!success) revert TransferFailed();
} else {
uint256 adapterBalance = IERC20(asset).balanceOf(address(this));
if (adapterBalance < amount) revert InsufficientBalance(asset, amount, adapterBalance);
IERC20(asset).safeTransfer(bridgeEscrow, amount);
}
emit TokensTransferredToEscrow(invoiceId, asset, amount);
}
/// @notice Implement bridge-specific completion logic (protocol verification); the base then releases
function _completeBridge(bytes calldata messagePayload, bytes calldata protocolData) internal virtual;
/// @inheritdoc IBridgeAdapter
/// @dev Recipient-restricted (ADR 0012, H11): recovered funds may only go to the escrow or an
/// escrow-authorized account, never an arbitrary address.
function recoverStuckAssets(address asset, uint256 amount, address to)
external
virtual
override
onlyRole(MANAGER_ROLE)
nonReentrant
{
if (amount == 0) revert InvalidArguments();
if (to != bridgeEscrow && !IBridgeEscrow(bridgeEscrow).isAuthorizedAccount(to)) revert NotAuthorized();
if (_isNativeToken(asset)) {
uint256 balance = address(this).balance;
if (balance < amount) revert InsufficientBalance(asset, amount, balance);
(bool success,) = to.call{value: amount}("");
if (!success) revert TransferFailed();
} else {
uint256 balance = IERC20(asset).balanceOf(address(this));
if (balance < amount) revert InsufficientBalance(asset, amount, balance);
IERC20(asset).safeTransfer(to, amount);
}
emit AssetsRecovered(asset, amount, to);
}
//
// ERC165 Support
//
/// @notice Checks if the contract supports an interface
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IBridgeAdapter).interfaceId || super.supportsInterface(interfaceId);
}
}
src/bridge/IBridgeAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IBridgeAdapter Interface
/// @notice Interface for bridge adapter implementations
/// @author KPK
interface IBridgeAdapter {
//
// Errors
//
/// @notice Thrown when invalid arguments are provided
error InvalidArguments();
/// @notice Thrown when caller is not authorized
error NotAuthorized();
/// @notice Thrown when transfer operation fails
error TransferFailed();
/// @notice Thrown when contract has insufficient balance
/// @param asset The asset address
/// @param required The required amount
/// @param available The available amount
error InsufficientBalance(address asset, uint256 required, uint256 available);
/// @notice Thrown when completion data is invalid
error InvalidCompletionData();
//
// Events
//
/// @notice Event emitted when a bridge is initiated
event BridgeInitiated(bytes32 indexed invoiceId, uint256 amount);
/// @notice Event emitted when a bridge is completed
event BridgeCompleted(bytes32 indexed invoiceId);
/// @notice Event emitted when assets are recovered from an adapter
event AssetsRecovered(address indexed asset, uint256 amount, address indexed to);
/// @notice Event emitted when tokens are transferred from adapter to escrow
event TokensTransferredToEscrow(bytes32 indexed invoiceId, address indexed asset, uint256 amount);
//
// Functions
//
/// @notice Initiates a bridge operation
/// @param messagePayload Encoded payload from BridgeEscrow (exactly 4 slots: invoiceId, amount, nonce, meta)
/// @dev Adapter should decode messagePayload to extract invoiceId, amount, and derive other needed data
function bridge(bytes calldata messagePayload) external;
/// @notice Completes a bridge operation on destination chain
/// @param messagePayload The message payload (exactly 4 slots: invoiceId, amount, nonce, meta)
/// @param protocolData Bridge-specific protocol data (e.g., CCTP message+attestation, CCIP Any2EVMMessage)
/// @dev The base adapter calls BridgeEscrow.recordDelivery(messagePayload) after _completeBridge returns, which records the delivery into escrow custody (ADR 0024); a subsequent MANAGER BridgeEscrow.claim pays the account. Adapter implementations must not call recordDelivery; they only perform protocol-specific completion in _completeBridge.
function completeBridge(bytes calldata messagePayload, bytes calldata protocolData) external;
/// @notice Returns the bridge provider name (e.g., "CCTP", "Gnosis")
/// @return The bridge provider name
function bridgeProvider() external view returns (string memory);
/// @notice Returns the bridge adapter version
/// @return The adapter version
function version() external view returns (string memory);
/// @notice Recovers stuck assets from the adapter
/// @param asset The asset address to recover (address(0) for native tokens)
/// @param amount The amount to recover
/// @param to The address to send recovered assets to; must be the escrow or an escrow-authorized account
/// @dev Only the MANAGER_ROLE can call this. Recipient-restricted (ADR 0012, H11): recovered funds may
/// only go to the escrow or an escrow-authorized account, never an arbitrary address.
function recoverStuckAssets(address asset, uint256 amount, address to) external;
}
src/bridge/IBridgeEscrow.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IBridgeEscrow Interface
/// @notice Interface for BridgeEscrow contract
/// @author KPK
/// @dev Contract Invariants:
/// - `_inTransitBalances[safe][asset]` equals the sum of amounts from all BRIDGING invoices for that safe and asset
/// - `_inTransitBalancesAllAccounts[asset]` equals the sum of `_inTransitBalances[safe][asset]` across all safes
/// - `_activeInvoices[safe]` only contains invoice hashes with status BRIDGING
/// - `completedInvoices[invoiceHash]` is true once a delivery has been recorded on the destination chain
/// (`recordDelivery`) or the invoice marked completed on the source chain (`markInvoiceCompleted`)
/// - All invoices in `_activeInvoices` have a corresponding entry in `invoices`
/// - Destination custody (ADR 0024, supersedes the ADR-0012 funded pass-through on the destination): the
/// delivered funds are HELD by the escrow in a per-invoice `destinationCustody` record and released to the
/// account only by `claim`. Invariants:
/// (I1) for every asset, `balanceOf(asset) >= _heldClaimable[asset]`, and `_heldClaimable[asset]` equals
/// both the sum of unclaimed `destinationCustody` amounts and `Σ _heldByAccount[*][asset]`;
/// (I2) a custody record is writable only via `recordDelivery`, callable only by an authorized adapter
/// (no `fallback()`; MANAGER cannot record) — provenance stays in the adapter, the checksum is
/// integrity/replay only; (I3) `claimed` flips once; (I4) `claim` pays only the recorded account exactly
/// the recorded amount; (I6) funds not recorded via `recordDelivery` are never claimable; (I7) the
/// recorded amount is the measured balance-delta received (≤ requested).
interface IBridgeEscrow {
//
// Errors
//
/// @notice Thrown when invalid arguments are provided
error InvalidArguments();
/// @notice Thrown when caller is not authorized
error NotAuthorized();
/// @notice Thrown when an invoice is not found
error InvoiceNotFound();
/// @notice Thrown when an invoice already exists (duplicate)
error InvoiceAlreadyExists();
/// @notice Thrown when invoice status is invalid for the operation
error InvalidInvoiceStatus();
/// @notice Thrown when transfer operation fails
error TransferFailed();
/// @notice Thrown when contract has insufficient balance
/// @param asset The asset address
/// @param required The required amount
/// @param available The available amount
error InsufficientBalance(address asset, uint256 required, uint256 available);
/// @notice Thrown when completion data is invalid
error InvalidCompletionData();
/// @notice Thrown when checksum validation fails
/// @param invoiceId The invoice ID
/// @param provided The provided checksum
/// @param calculated The calculated checksum
error InvalidChecksum(bytes32 invoiceId, bytes24 provided, bytes24 calculated);
/// @notice Thrown when timestamp is invalid
/// @param provided The provided timestamp
/// @param current The current timestamp
error InvalidTimestamp(uint64 provided, uint64 current);
/// @notice Thrown when attempting to unregister or repoint an asset with active invoices
/// @param symbol The asset symbol (string)
error AssetHasActiveInvoices(string symbol);
/// @notice Thrown when attempting to revoke an account that still has active (BRIDGING) invoices
/// @param account The account address
error AccountHasActiveInvoices(address account);
/// @notice Thrown when attempting to revoke an adapter that still has in-flight (BRIDGING) invoices
/// @param adapter The bridge adapter address
error AdapterHasActiveInvoices(address adapter);
/// @notice Thrown when attempting to unregister a symbol that was never registered
/// @param symbol The asset symbol (string)
error AssetNotRegistered(string symbol);
/// @notice Thrown when the native value sent is wrong for the asset: `msg.value` must equal the
/// release/deposit amount for native assets, and must be zero for ERC20 assets
error InvalidValue();
/// @notice Thrown when attempting to claim a destination custody record that has already been claimed
error AlreadyClaimed();
//
// Types
//
/// @notice Status of a bridge invoice
enum InvoiceStatus {
BRIDGING, // Bridge adapter has initiated the bridge
COMPLETED, // Assets successfully received on destination
CANCELLED // Invoice cancelled (e.g., bridge failure recovery)
}
/// @notice Invoice structure tracking a bridge operation (source-chain ledger)
struct Invoice {
bytes32 invoiceId; // Route+account+symbol identity (32 bytes, excludes amount and nonce)
uint64 sourceChainId; // Chain ID where assets originate
uint64 destinationChainId; // Chain ID where assets are destined
address account; // Account address
address asset; // Token address (address(0) for native)
uint256 amount; // Amount being bridged
uint256 nonce; // Per-account monotonic nonce (unique per operation)
uint256 timestamp; // Block timestamp when invoice created
InvoiceStatus status; // Current status of the invoice
address adapter; // Adapter address used for this invoice
}
/// @notice Destination-side custody record (ADR 0024). Written by `recordDelivery` when an authorized
/// adapter hands the escrow the delivered funds; the escrow HOLDS them until `claim`.
struct DestinationCustody {
address account; // Authenticated payee from the invoice — `claim` pays ONLY this
address asset; // Resolved destination asset (address(0)/ERC7528 = native)
uint256 amount; // MEASURED balance-delta actually received (fee-on-transfer / post-fee safe)
address adapter; // msg.sender at recordDelivery — provenance stamp
uint64 deliveredAt; // Block timestamp of recordDelivery
bool claimed; // false = held in escrow; true = moved to the safe (terminal)
}
//
// Events
//
/// @notice Event emitted when a new invoice is created
event InvoiceCreated(
bytes32 indexed invoiceId,
address indexed account,
address indexed asset,
uint256 amount,
uint64 sourceChainId,
uint64 destinationChainId
);
/// @notice Event emitted when invoice status changes
event InvoiceStatusUpdated(bytes32 indexed invoiceId, InvoiceStatus oldStatus, InvoiceStatus newStatus);
/// @notice Event emitted when assets are deposited into escrow
event AssetsDeposited(bytes32 indexed invoiceId, address indexed asset, uint256 amount);
/// @notice Event emitted when assets are released from escrow
event AssetsReleased(
bytes32 indexed invoiceId, uint64 indexed sourceChainId, address asset, uint256 amount, address recipient
);
/// @notice Event emitted when an account is authorized
event AccountAuthorized(address indexed safe);
/// @notice Event emitted when an account is revoked
event AccountRevoked(address indexed safe);
/// @notice Event emitted when an adapter is authorized
event AdapterAuthorized(address indexed adapter);
/// @notice Event emitted when an adapter is revoked
event AdapterRevoked(address indexed adapter);
/// @notice Event emitted when an asset is registered
event AssetRegistered(bytes6 indexed symbol, address indexed asset);
/// @notice Event emitted when an asset is unregistered
event AssetUnregistered(bytes6 indexed symbol);
/// @notice Event emitted when invoice completion attempts fail during batch operation
event InvoiceCompletionFailed(bytes32[] invoiceIds);
/// @notice Event emitted when an invoice is completed (destination delivery recorded, or source marked)
event InvoiceCompleted(bytes32 indexed invoiceHash, bytes32 indexed invoiceId);
/// @notice Event emitted when a destination delivery is recorded and the funds held in escrow custody
event DeliveryRecorded(
bytes32 indexed invoiceId,
bytes32 indexed invoiceHash,
address indexed asset,
uint256 amount,
address account,
address adapter
);
/// @notice Event emitted when held funds are claimed from escrow custody to the recorded account (the safe)
event AssetsClaimed(bytes32 indexed invoiceHash, address indexed asset, uint256 amount, address indexed account);
/// @notice Event emitted when emergency withdrawal is performed
event EmergencyWithdrawal(address indexed asset, uint256 amount, address indexed to);
//
// Core
//
/// @notice Deposits assets from an account and immediately bridges them
/// @param destinationChainId The destination chain ID
/// @param assetSymbol The asset symbol as string (e.g. "USDC" or "WETH"; max 6 chars)
/// @param amount The amount to bridge
/// @param adapter The bridge adapter address to use
/// @return invoiceHash The hashed invoice identifier (checksum: invoiceId + amount + timestamp + nonce)
function depositAndBridge(uint64 destinationChainId, string calldata assetSymbol, uint256 amount, address adapter)
external
payable
returns (bytes32 invoiceHash);
/// @notice Records a destination delivery and HOLDS the funds in escrow custody (ADR 0024).
/// @param messagePayload The message payload (invoiceId, amount, nonce, meta)
/// @dev Callable ONLY by an authorized adapter (the adapter has already authenticated the genuine inbound
/// protocol message + source sender); there is no fallback dispatcher and MANAGER cannot call this
/// directly (C1). The escrow pulls `amount` of the asset from the caller (or requires `msg.value ==
/// amount` for native), MEASURES the balance-delta actually received, writes a `destinationCustody`
/// record, and holds the funds. It does NOT pay the account — release happens only via `claim`.
/// Validates checksum (incl. nonce), destination chain, authorized account, and replay.
function recordDelivery(bytes calldata messagePayload) external payable;
/// @notice Releases a held destination delivery from escrow custody to the recorded account (the safe).
/// @param invoiceHash The destination custody key (checksum-derived invoice hash)
/// @dev MANAGER-gated. Because it can only ever pay the account recorded at `recordDelivery` (and exactly
/// the recorded amount), the gate controls only the TIMING of when funds enter the safe (NAV
/// sequencing), never the destination. Reverts if no record exists or it was already claimed.
function claim(bytes32 invoiceHash) external;
/// @notice Batch form of {claim} for keeper gas efficiency.
/// @param invoiceHashes The destination custody keys to claim
function claim(bytes32[] calldata invoiceHashes) external;
/// @notice Cancels an invoice and returns assets (source chain, bridge-failure recovery)
/// @param invoiceHash The hashed invoice ID (checksum) to cancel
/// @dev Refunds only from the surplus over destination held custody (never touches funds backing a recorded
/// delivery, I1). There is NO on-chain source↔destination interlock, so this MUST only be called once the
/// destination has provably not delivered and will not: cancelling a still-live invoice while the escrow
/// holds unrelated surplus (e.g. stray funds) could refund the source AND let the destination later
/// deliver, double-paying from that surplus. Enforced by MANAGER / settlement-keeper discipline.
function cancelInvoice(bytes32 invoiceHash) external;
/// @notice Marks invoices as completed for bookkeeping purposes (source chain only)
/// @param invoiceHashes Array of hashed invoice IDs to mark as completed
function markInvoiceCompleted(bytes32[] calldata invoiceHashes) external;
//
// Views
//
/// @notice Gets an invoice by its hashed ID
function getInvoice(bytes32 invoiceHash) external view returns (Invoice memory);
/// @notice Returns the current (next) bridge nonce for an account
function bridgeNonce(address account) external view returns (uint256);
/// @notice Decodes a 32-byte invoice ID into its components
function decodeInvoiceId(bytes32 invoiceId)
external
pure
returns (uint24 sourceChainId, uint24 destinationChainId, address account, string memory assetSymbol);
/// @notice Validates the (invoiceId, amount, timestamp, nonce) checksum
function validateInvoiceIdChecksum(
bytes32 invoiceId,
uint256 amount,
uint64 timestamp,
uint256 nonce,
bytes24 checksum24
) external pure returns (bool);
/// @notice Gets all active invoices for an account
function getActiveInvoices(address account) external view returns (Invoice[] memory);
/// @notice Held (delivered-but-unclaimed) invoice hashes for `account` — the destination-side enumeration the
/// settlement operator uses to discover claimable invoices in ONE call, instead of reconstructing them
/// from `DeliveryRecorded` logs over a bounded window (ADR 0025). A hash appears after `recordDelivery`
/// and is removed on `claim`. Returns the raw hashes; pair each with `destinationCustody(hash)`.
function getHeldInvoices(address account) external view returns (bytes32[] memory);
/// @notice Total in-transit balance for an asset (optionally filtered by account; address(0) = all)
function getInTransitBalanceForAsset(address asset, address account) external view returns (uint256);
/// @notice Checks if an account is authorized
function isAuthorizedAccount(address safe) external view returns (bool);
/// @notice Checks if an adapter is authorized
function isAuthorizedAdapter(address adapter) external view returns (bool);
/// @notice Checks if an invoice (by hash) has been completed
function isInvoiceCompleted(bytes32 invoiceHash) external view returns (bool);
/// @notice Gets the asset address for a given asset symbol
function assetRegistry(string calldata symbol) external view returns (address);
/// @notice Returns all registered asset symbol-address pairs
function registeredAssets() external view returns (string[] memory symbols, address[] memory assets);
/// @notice Returns all assets in-transit for a specific account with their amounts
function getInTransitBalancesForAccount(address account)
external
view
returns (address[] memory assets, uint256[] memory amounts);
/// @notice Gets the completion status for an array of invoices
function getInvoicesCompletionStatus(bytes32[] calldata invoiceHashes)
external
view
returns (bool[] memory isCompleted);
/// @notice Returns all authorized adapters
function getAuthorizedAdapters() external view returns (address[] memory adapters);
/// @notice Held-but-unclaimed destination custody for an asset (optionally filtered by account;
/// address(0) = all accounts). Mirrors {getInTransitBalanceForAsset} for the destination side so a
/// balance adapter can count delivered-but-not-yet-claimed value in NAV.
/// @dev Native dual-key: the aggregate (account == address(0)) path sums BOTH native representations
/// (`address(0)` + the ERC-7528 sentinel); the per-account path returns the single exact key.
/// `BridgeHeldBalanceAdapter` sums both native keys itself per account (so NAV is unaffected) — but a
/// direct caller reading a specific account's native custody should query both keys (or use the adapter),
/// otherwise it under-reports native held under the "other" key.
function getHeldBalanceForAsset(address asset, address account) external view returns (uint256);
/// @notice Returns all assets held-but-unclaimed for a specific account with their amounts (destination).
function getHeldBalancesForAccount(address account)
external
view
returns (address[] memory assets, uint256[] memory amounts);
}
src/bridge/InvoiceDataLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title InvoiceDataLib
/// @notice Library for encoding and decoding invoice message payloads and symbol conversion
/// @dev Provides a standardized way to encode/decode invoice data and convert bytes6/string symbols.
/// The wire format is `abi.encode(invoiceId, amount, nonce, meta)` (4 slots), where
/// `meta = timestamp (uint64, bits 192-255) || checksum24 (bytes24, bits 0-191)`.
/// The `nonce` is a per-account monotonic counter included in the checksum preimage so that
/// invoice identity is unique per bridge operation (see ADR 0012). The checksum is
/// `bytes24(keccak256(invoiceId, amount, timestamp, nonce))`.
/// @author KPK
library InvoiceDataLib {
/// @notice Converts a bytes6 symbol (e.g. right-padded "USDC ") to a string, trimming trailing spaces and null bytes
function bytes6ToStr(bytes6 symbol) public pure returns (string memory) {
bytes memory b = abi.encodePacked(symbol);
uint256 length = 6;
while (length > 0 && (b[length - 1] == 0x20 || b[length - 1] == 0)) {
length--;
}
if (length == 0) return "";
bytes memory trimmed = new bytes(length);
for (uint256 i; i < length; i++) {
trimmed[i] = b[i];
}
return string(trimmed);
}
/// @notice Converts a string symbol to bytes6, right-padding with spaces to 6 bytes
/// @param symbol The symbol string (max 6 characters); reverts with SymbolTooLong if length > 6
function strToBytes6(string memory symbol) public pure returns (bytes6) {
bytes memory b = bytes(symbol);
if (b.length > 6) revert SymbolTooLong();
bytes memory padded = new bytes(6);
for (uint256 i; i < 6; i++) {
padded[i] = i < b.length ? b[i] : bytes1(0x20);
}
uint256 word;
for (uint256 i; i < 6; i++) {
word |= uint256(uint8(padded[i])) << (8 * (5 - i));
}
return bytes6(uint48(word));
}
error SymbolTooLong();
//
/// @notice Struct containing all invoice data components
struct InvoiceData {
bytes32 invoiceId; // The route+account+symbol identity (32 bytes, excludes amount and nonce)
uint24 sourceChainId; // Source chain ID
uint24 destinationChainId; // Destination chain ID
address account; // Account address
bytes6 assetSymbol; // Asset symbol
uint256 amount; // Amount being bridged
uint256 nonce; // Per-account monotonic nonce (unique per bridge operation)
uint64 timestamp; // Timestamp (uint64, 8 bytes)
bytes24 checksum24; // 24-byte checksum over (invoiceId, amount, timestamp, nonce)
}
/// @notice Decodes a message payload into a complete InvoiceData struct
/// @param messagePayload The message payload to decode
/// @return data The complete invoice data struct
function decode(bytes memory messagePayload) internal pure returns (InvoiceData memory data) {
// Decode messagePayload (exactly 4 slots: invoiceId, amount, nonce, meta)
bytes32 meta;
(data.invoiceId, data.amount, data.nonce, meta) =
abi.decode(messagePayload, (bytes32, uint256, uint256, bytes32));
// Decode meta: timestamp (uint64, 8 bytes) + checksum24 (bytes24, 24 bytes) = 32 bytes total
// timestamp is in the first 8 bytes (bits 192-255, shifted right by 192 to get first 8 bytes)
data.timestamp = uint64(uint256(meta) >> 192);
// checksum24 is in the last 24 bytes (bits 0-191)
// Truncation to 24 bytes by design (checksum layout)
// forge-lint: disable-next-line(unsafe-typecast)
data.checksum24 = bytes24(uint192(uint256(meta)));
// Decode invoiceId into its components
uint256 id = uint256(data.invoiceId);
data.sourceChainId = SafeCast.toUint24(id >> 232); // Bits 232-255 (3 bytes)
data.destinationChainId = SafeCast.toUint24((id >> 208) & type(uint24).max); // Bits 208-231 (3 bytes); mask to avoid 48-bit value overflowing uint24
data.account = address(uint160((id >> 48) & type(uint160).max)); // Bits 48-207 (20 bytes); mask so chain IDs don't overflow uint160
// casting to uint48/bytes6 is safe: id & type(uint48).max keeps only low 48 bits, so no truncation
// forge-lint: disable-next-line(unsafe-typecast)
data.assetSymbol = bytes6(uint48(id & type(uint48).max)); // Bits 0-47 (6 bytes)
}
/// @notice Encodes an InvoiceData struct into a message payload
/// @param data The invoice data struct to encode
/// @return messagePayload The encoded message payload
function encode(InvoiceData memory data) internal pure returns (bytes memory messagePayload) {
// Encode meta from timestamp (uint64, 8 bytes) and checksum24 (bytes24, 24 bytes)
// timestamp goes in bits 192-255 (leftmost 8 bytes), checksum24 goes in bits 0-191 (rightmost 24 bytes)
bytes32 meta = bytes32(uint256(uint256(data.timestamp) << 192 | uint256(uint192(data.checksum24))));
// Encode messagePayload (4 slots: invoiceId, amount, nonce, meta)
return abi.encode(data.invoiceId, data.amount, data.nonce, meta);
}
/// @notice Calculates the 24-byte checksum over (invoiceId, amount, timestamp, nonce)
/// @dev Single source of truth for the checksum preimage, shared by escrow and any validator.
/// The nonce makes the preimage unique per bridge operation; it is NOT a security
/// authenticator (all inputs are public) — provenance is enforced by the adapter layer
/// (ADR 0012). The checksum only guards payload integrity + replay (completedInvoices).
/// @param invoiceId The 32-byte invoice ID (route+account+symbol identity)
/// @param amount The amount being bridged
/// @param timestamp The timestamp (uint64)
/// @param nonce The per-account monotonic nonce
/// @return checksum24 The first 24 bytes of keccak256(invoiceId, amount, timestamp, nonce)
function calculateChecksum(bytes32 invoiceId, uint256 amount, uint64 timestamp, uint256 nonce)
internal
pure
returns (bytes24 checksum24)
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 fullHash = keccak256(abi.encodePacked(invoiceId, amount, timestamp, nonce));
// casting to 'bytes24' is safe because we're truncating the last 8 bytes of a 32-byte hash
// forge-lint: disable-next-line(unsafe-typecast)
return bytes24(fullHash);
}
}
src/bridge/adapters/interfaces/ISuperchainBridgeAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBridgeAdapter} from "../../IBridgeAdapter.sol";
import {IL1StandardBridge, IL2StandardBridge, IOptimismPortal} from "./ISuperchainInterfaces.sol";
import {Types} from "@optimism/libraries/Types.sol";
/// @title ISuperchainBridgeAdapter Interface
/// @notice Interface for Superchain (Optimism Canonical Bridge) Adapter
/// @dev Documents all events, errors, and public functions for the Superchain bridge adapter
/// @dev Supports Optimism, Base, Unichain, and other Superchain networks
/// @author KPK
interface ISuperchainBridgeAdapter is IBridgeAdapter {
//
// Events
//
/// @notice Event emitted when a Superchain bridge is initiated (L1 → L2 deposit)
/// @param invoiceId The invoice ID (32 bytes) - indexed
/// @param destinationChainId The destination chain ID (L2)
/// @param amount The amount being bridged
/// @param isEth Whether the asset is native ETH
event SuperchainBridgeInitiated(bytes32 indexed invoiceId, uint64 destinationChainId, bytes32 amount, bool isEth);
/// @notice Event emitted when a Superchain bridge is initiated (L2 → L1 withdrawal)
/// @param invoiceId The invoice ID (32 bytes) - indexed
/// @param destinationChainId The destination chain ID (L1)
/// @param amount The amount being withdrawn
/// @param withdrawalHash Always bytes32(0) at initiation; the real OP withdrawal hash is only known on L1
/// and is set later at prove time (see SuperchainWithdrawalProven)
event SuperchainWithdrawalInitiated(
bytes32 indexed invoiceId, uint64 destinationChainId, bytes32 amount, bytes32 withdrawalHash
);
/// @notice Event emitted when a withdrawal is proven
/// @param invoiceId The invoice ID (32 bytes) - indexed
/// @param withdrawalHash The withdrawal transaction hash - indexed
event SuperchainWithdrawalProven(bytes32 indexed invoiceId, bytes32 indexed withdrawalHash);
/// @notice Event emitted when a Superchain bridge is completed
/// @param invoiceId The invoice ID (32 bytes) - indexed
/// @param sourceChainId The source chain ID
event SuperchainBridgeCompleted(bytes32 indexed invoiceId, uint64 sourceChainId);
//
// Errors
//
/// @notice Thrown when an invalid L1 Standard Bridge address is provided
error InvalidL1Bridge();
/// @notice Thrown when an invalid L2 Standard Bridge address is provided
error InvalidL2Bridge();
/// @notice Thrown when an invalid Cross-Domain Messenger address is provided
error InvalidCrossDomainMessenger();
/// @notice Thrown when an invalid Optimism Portal address is provided
error InvalidOptimismPortal();
/// @notice Thrown when an invalid chain ID is provided
error InvalidChainId();
/// @notice Thrown when attempting to bridge to an unsupported chain
/// @param chainId The unsupported chain ID
error UnsupportedChain(uint64 chainId);
/// @notice Thrown when attempting to bridge an unsupported asset
error UnsupportedAsset();
/// @notice Thrown when an ERC20 L1→L2 deposit has no configured L2 token for the destination L2
/// @dev Fail-closed guard: the adapter refuses to default the L2 token to the L1 address (wrong for tokens
/// like WETH). Wire the mapping via `setL2TokenForL2` before routing that ERC20 over Superchain.
/// @param l2ChainId The destination L2 chain id
/// @param l1Token The L1 token that has no L2 mapping
error L2TokenNotConfigured(uint256 l2ChainId, address l1Token);
/// @notice Thrown when an L1→L2 deposit has no configured L1CrossDomainMessenger for the destination L2
/// @dev Each destination L2 (OP, Base) has a DISTINCT L1CrossDomainMessenger; wire it via `setL1MessengerForL2`
/// before routing a deposit to that L2 (a single messenger would route other L2s through the wrong one).
/// @param l2ChainId The destination L2 chain id with no configured messenger
error MessengerNotConfigured(uint256 l2ChainId);
/// @notice Thrown when withdrawal proof data is invalid
error InvalidWithdrawalProof();
/// @notice Thrown when withdrawal finalization data is invalid
error InvalidWithdrawalFinalization();
/// @notice Thrown when withdrawal has not been proven yet
error WithdrawalNotProven();
/// @notice Thrown when `proveWithdrawal`'s `l2ChainId` does not match the invoice's encoded source chain id
/// @param provided The `l2ChainId` passed to `proveWithdrawal`
/// @param encoded The source chain id encoded in the invoice id (top 3 bytes)
error WithdrawalChainIdMismatch(uint256 provided, uint256 encoded);
//
// State Variables (Public)
//
/// @notice L1 Standard Bridge for a destination L2 chain id (L1 side)
/// @return The L1 Standard Bridge contract instance for that L2
function l1BridgeForL2(uint256 l2ChainId) external view returns (IL1StandardBridge);
/// @notice L2 Standard Bridge contract address
/// @return The L2 Standard Bridge contract instance
function l2Bridge() external view returns (IL2StandardBridge);
/// @notice Cross-Domain Messenger contract address (L1) — legacy single value; outbound deposit messages use
/// the per-L2 `l1MessengerForL2` instead
/// @return The Cross-Domain Messenger contract address
function l1Messenger() external view returns (address);
/// @notice L1 Cross-Domain Messenger for a destination L2 chain id (L1 side)
/// @param l2ChainId The destination L2 chain id
/// @return The L1CrossDomainMessenger address the deposit completion message is sent through for that L2
function l1MessengerForL2(uint256 l2ChainId) external view returns (address);
/// @notice The chain id treated as "the L1 side" for this deployment (mainnet = 1)
/// @return The configured L1 chain id
function l1ChainId() external view returns (uint256);
/// @notice Min-gas limit for the authenticated `completeDeposit` cross-domain message
/// @return The gas limit
function completeDepositGasLimit() external view returns (uint32);
/// @notice Cross-Domain Messenger contract address (L2)
/// @return The Cross-Domain Messenger contract address
function l2Messenger() external view returns (address);
/// @notice Optimism Portal for a source L2 chain id (L1 side)
/// @return The Optimism Portal contract instance for that L2
function optimismPortalForL2(uint256 l2ChainId) external view returns (IOptimismPortal);
/// @notice The chain ID where this adapter is deployed
/// @return The chain ID
function chainId() external view returns (uint256);
/// @notice Gets the stored message payload for an operation, keyed by the per-operation invoice hash
/// @param invoiceHash The per-operation invoice hash (checksum, 32 bytes)
/// @return The message payload, or empty bytes if not found
function messagePayloads(bytes32 invoiceHash) external view returns (bytes memory);
/// @notice Gets the withdrawal hash for a given invoice ID
/// @param invoiceId The invoice ID (32 bytes)
/// @return The withdrawal hash, or bytes32(0) if not found
function invoiceToWithdrawalHash(bytes32 invoiceId) external view returns (bytes32);
/// @notice Gets the invoice ID for a given withdrawal hash
/// @param withdrawalHash The withdrawal transaction hash
/// @return The invoice ID, or bytes32(0) if not found
function withdrawalHashToInvoiceId(bytes32 withdrawalHash) external view returns (bytes32);
//
// Configuration Functions
//
/// @notice Initializes the Superchain Bridge Adapter
/// @param admin_ The admin address
/// @param bridgeEscrow_ The BridgeEscrow contract address
/// @param l2Bridge_ The L2 Standard Bridge contract address (L2 side only)
/// @param l1Messenger_ The L1 Cross-Domain Messenger contract address (L1 side only; legacy — outbound uses
/// the per-L2 `l1MessengerForL2`, seeded via `setL1MessengerForL2`)
/// @param l2Messenger_ The L2 Cross-Domain Messenger contract address (L2 side only)
/// @param l1ChainId_ The chain id that is "the L1 side" (mainnet = 1); the adapter plays the L1 role when
/// `block.chainid == l1ChainId_`. Pass the SAME value to both siblings so the CREATE2 address is unaffected.
/// @param version_ The adapter version
/// @dev L1 per-L2 bridges/portals/messengers are seeded after init via setL1BridgeForL2 / setOptimismPortalForL2
/// / setL1MessengerForL2.
function initialize(
address admin_,
address bridgeEscrow_,
address l2Bridge_,
address l1Messenger_,
address l2Messenger_,
uint256 l1ChainId_,
string memory version_
) external;
/// @notice Sets the L1 Standard Bridge for a destination L2 chain id
/// @param l2ChainId The destination L2 chain id
/// @param l1Bridge_ The L1 Standard Bridge contract address for that L2
/// @dev Only callable by admin role; only valid on the L1 deployment (reverts InvalidChainId on an L2)
function setL1BridgeForL2(uint256 l2ChainId, address l1Bridge_) external;
/// @notice Sets the L2 Standard Bridge contract address
/// @param l2Bridge_ The L2 Standard Bridge contract address
/// @dev Only callable by admin role; only valid on an L2 deployment (reverts InvalidChainId on L1)
function setL2Bridge(address l2Bridge_) external;
/// @notice Sets the L1 Cross-Domain Messenger contract address (legacy single value)
/// @param l1Messenger_ The L1 Cross-Domain Messenger contract address
/// @dev Only callable by admin role; only valid on the L1 deployment (reverts InvalidChainId on an L2)
function setL1Messenger(address l1Messenger_) external;
/// @notice Sets the L1 Cross-Domain Messenger for a destination L2 chain id (used for the deposit message)
/// @param l2ChainId The destination L2 chain id
/// @param l1Messenger_ The L1CrossDomainMessenger address for that L2 (OP and Base differ)
/// @dev Only callable by admin role; only valid on the L1 deployment (reverts InvalidChainId on an L2)
function setL1MessengerForL2(uint256 l2ChainId, address l1Messenger_) external;
/// @notice Sets the min-gas limit for the authenticated `completeDeposit` cross-domain message
/// @param gasLimit The gas limit to use
/// @dev Only callable by admin role
function setCompleteDepositGasLimit(uint32 gasLimit) external;
/// @notice Sets the L2 Cross-Domain Messenger contract address
/// @param l2Messenger_ The L2 Cross-Domain Messenger contract address
/// @dev Only callable by admin role; only valid on an L2 deployment (reverts InvalidChainId on L1)
function setL2Messenger(address l2Messenger_) external;
/// @notice Sets the Optimism Portal for a source L2 chain id
/// @param l2ChainId The source L2 chain id
/// @param optimismPortal_ The Optimism Portal contract address for that L2
/// @dev Only callable by admin role; only valid on the L1 deployment (reverts InvalidChainId on an L2). When
/// enabling a NEW withdrawal-source L2, also wire its `setL1MessengerForL2` — the L2→L1 finalize path binds a
/// front-run withdrawal's target to `l1MessengerForL2[sourceChainId]`, so a portal-only config would revert
/// `MessengerNotConfigured` at completion. (The `05` deploy seeds both together, index-aligned.)
function setOptimismPortalForL2(uint256 l2ChainId, address optimismPortal_) external;
/// @notice Sets the L2 token for a (destination L2 chain id, L1 token)
/// @param l2ChainId The destination L2 chain id
/// @param l1Token The L1 token address
/// @param l2Token The corresponding L2 token address (unset falls back to the same address)
/// @dev Only callable by admin role; only valid on the L1 deployment.
function setL2TokenForL2(uint256 l2ChainId, address l1Token, address l2Token) external;
//
// View Functions
//
/// @notice Gets the stored message payload for an operation, keyed by the per-operation invoice hash
/// @param invoiceHash The per-operation invoice hash (checksum, 32 bytes)
/// @return The message payload, or empty bytes if not found
function getMessagePayload(bytes32 invoiceHash) external view returns (bytes memory);
/// @notice Gets the full `WithdrawalTransaction` stored at prove time for an invoice (ADR 0025)
/// @dev Lets the settlement keeper finalize an already-proven L2->L1 withdrawal without re-deriving the
/// transaction from the source L2 `MessagePassed` log. Keyed by the per-operation invoice HASH (not the
/// reusable route `invoiceId`). Returns a zero-valued struct if not proven.
/// @param invoiceHash The per-operation invoice hash (checksum, 32 bytes)
/// @return The stored withdrawal transaction
function getWithdrawalTransaction(bytes32 invoiceHash) external view returns (Types.WithdrawalTransaction memory);
/// @notice Gets the withdrawal hash for a given invoice ID
/// @param invoiceId The invoice ID (32 bytes)
/// @return The withdrawal hash, or bytes32(0) if not found
function getWithdrawalHashByInvoiceId(bytes32 invoiceId) external view returns (bytes32);
/// @notice Gets the invoice ID for a given withdrawal hash
/// @param withdrawalHash The withdrawal transaction hash
/// @return The invoice ID, or bytes32(0) if not found
function getInvoiceIdByWithdrawalHash(bytes32 withdrawalHash) external view returns (bytes32);
/// @notice Checks if a withdrawal has been proven
/// @param withdrawalHash The withdrawal transaction hash
/// @return True if proven, false otherwise
function isWithdrawalProven(uint256 l2ChainId, bytes32 withdrawalHash) external view returns (bool);
/// @notice Reports whether a withdrawal has been proven (a prerequisite for finalization)
/// @dev Does not check the challenge period; the Optimism Portal enforces that at finalize time
/// @param withdrawalHash The withdrawal transaction hash
/// @return True if the withdrawal has been proven, false otherwise
function canFinalizeWithdrawal(uint256 l2ChainId, bytes32 withdrawalHash) external view returns (bool);
}
src/bridge/adapters/interfaces/ISuperchainInterfaces.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {Types} from "@optimism/libraries/Types.sol";
/// @title Superchain (Optimism) Bridge Interfaces
/// @notice Aggregated interfaces for Optimism Superchain canonical bridge integration
/// @author KPK
// ============================================================================
// Optimism L1 Standard Bridge Interface
// ============================================================================
/// @title IL1StandardBridge Interface
/// @notice Interface for Optimism L1 Standard Bridge
/// @dev Used for bridging ETH and ERC20 tokens from L1 to L2
interface IL1StandardBridge {
/// @notice Deposits ETH to a recipient's balance on L2
/// @param _to Address on L2 to receive the ETH
/// @param _l2Gas Gas limit for the L2 execution
/// @param _data Optional data to forward to L2
// forge-lint: disable-next-line(mixed-case-function)
function depositETHTo(address _to, uint32 _l2Gas, bytes calldata _data) external payable;
/// @notice Deposits an amount of ERC20 tokens to a recipient's balance on L2
/// @param _l1Token Address of the L1 token
/// @param _l2Token Address of the corresponding L2 token
/// @param _to Address on L2 to receive the tokens
/// @param _amount Amount of tokens to deposit
/// @param _l2Gas Gas limit for the L2 execution
/// @param _data Optional data to forward to L2
function depositERC20To(
address _l1Token,
address _l2Token,
address _to,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
) external;
/// @notice Event emitted when ETH deposit is initiated
event ETHDepositInitiated(address indexed _from, address indexed _to, uint256 _amount, bytes _data);
/// @notice Event emitted when ERC20 deposit is initiated
event ERC20DepositInitiated(
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
}
// ============================================================================
// Optimism L2 Standard Bridge Interface
// ============================================================================
/// @title IL2StandardBridge Interface
/// @notice Interface for Optimism L2 Standard Bridge
/// @dev Used for bridging ETH and ERC20 tokens from L2 to L1
interface IL2StandardBridge {
/// @notice Withdraws ETH to a recipient on L1
/// @param _l1Gas Gas limit for the L1 execution
/// @param _data Optional data to forward to L1
function withdraw(uint32 _l1Gas, bytes calldata _data) external payable;
/// @notice Withdraws ETH to a specific recipient on L1
/// @param _to Address on L1 to receive the ETH
/// @param _l1Gas Gas limit for the L1 execution
/// @param _data Optional data to forward to L1
function withdrawTo(address _to, uint32 _l1Gas, bytes calldata _data) external payable;
/// @notice Withdraws ERC20 tokens to a recipient on L1
/// @param _l2Token Address of the L2 token
/// @param _amount Amount of tokens to withdraw
/// @param _l1Gas Gas limit for the L1 execution
/// @param _data Optional data to forward to L1
function withdraw(address _l2Token, uint256 _amount, uint32 _l1Gas, bytes calldata _data) external payable;
/// @notice Withdraws ERC20 tokens to a specific recipient on L1
/// @param _l2Token Address of the L2 token
/// @param _to Address on L1 to receive the tokens
/// @param _amount Amount of tokens to withdraw
/// @param _l1Gas Gas limit for the L1 execution
/// @param _data Optional data to forward to L1
function withdrawTo(address _l2Token, address _to, uint256 _amount, uint32 _l1Gas, bytes calldata _data)
external
payable;
/// @notice Event emitted when ETH withdrawal is initiated
event ETHWithdrawalInitiated(address indexed _from, address indexed _to, uint256 _amount, bytes _data);
/// @notice Event emitted when ERC20 withdrawal is initiated
event ERC20WithdrawalInitiated(
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
}
// ============================================================================
// Optimism Cross-Domain Messenger Interface
// ============================================================================
/// @title ICrossDomainMessenger Interface
/// @notice Minimal interface for the OP Stack Cross-Domain Messenger (L1 and L2)
/// @dev Used to authenticate the provenance of a relayed cross-domain message. On the destination chain the
/// messenger relays the message and exposes the original sender on the source chain via
/// `xDomainMessageSender()` (only meaningful during the relayed call). The Superchain adapter, as the
/// destination recipient, verifies `msg.sender == <messenger>` and
/// `messenger.xDomainMessageSender() == trustedRemoteAdapter[srcChainId]`.
interface ICrossDomainMessenger {
/// @notice Returns the address of the sender of the currently-being-relayed cross-domain message.
/// @return The source-chain sender address (the sibling adapter for an authenticated bridge message).
// forge-lint: disable-next-line(mixed-case-function)
function xDomainMessageSender() external view returns (address);
/// @notice Sends a cross-domain message to `_target` on the other chain (optionally carrying native value).
/// @dev Used on L1 by the Superchain adapter to deliver an authenticated `completeDeposit` call to its L2
/// sibling: the L2CrossDomainMessenger relays it with `xDomainMessageSender()` set to this adapter, so
/// the L2 sibling can authenticate provenance (the deposit's funds are ordered ahead of this message).
/// @param _target The destination contract on the other chain (the sibling adapter).
/// @param _message The calldata to relay to `_target`.
/// @param _minGasLimit Minimum gas to relay with on the destination chain.
function sendMessage(address _target, bytes calldata _message, uint32 _minGasLimit) external payable;
/// @notice Reports whether a relayed cross-domain message was delivered successfully.
/// @dev Keyed by the versioned message hash (`Hashing.hashCrossDomainMessageV1`), which for a Bedrock v1
/// message equals `keccak256(relayMessageCalldata)`. The Superchain adapter uses this on L1 to confirm that
/// an already-finalized withdrawal's inner relay actually paid this adapter (the `finalizeBridge*` receiver)
/// before settling — the finalize skip-branch cannot measure a balance delta for a front-run finalize.
/// @param _messageHash The versioned cross-domain message hash.
/// @return True if the message was relayed successfully (funds delivered), false otherwise.
function successfulMessages(bytes32 _messageHash) external view returns (bool);
}
// ============================================================================
// Optimism Portal Interface
// ============================================================================
/// @title IOptimismPortal Interface
/// @notice Interface for Optimism Portal (used for proving and finalizing withdrawals)
/// @dev Used for the two-step withdrawal process from L2 to L1
interface IOptimismPortal {
/// @notice Proves a withdrawal transaction against a dispute game (fault-proof OP2).
/// @param _tx Withdrawal transaction to prove
/// @param _disputeGameIndex Index of the dispute game the withdrawal is proven against (was the L2 output
/// index in the legacy portal; on fault-proof portals it selects the dispute game)
/// @param _outputRootProof Proof of the L2 output root
/// @param _withdrawalProof Proof of the withdrawal
function proveWithdrawalTransaction(
Types.WithdrawalTransaction memory _tx,
uint256 _disputeGameIndex,
Types.OutputRootProof memory _outputRootProof,
bytes[] calldata _withdrawalProof
) external;
/// @notice Finalizes a withdrawal transaction
/// @dev Fault-proof portal: uses `msg.sender` as the proof submitter and internally enforces the proof-maturity
/// delay, the dispute game being resolved in the defender's favour, and the dispute-game-finality air-gap.
/// @param _tx Withdrawal transaction to finalize
function finalizeWithdrawalTransaction(Types.WithdrawalTransaction memory _tx) external;
/// @notice Returns the proven-withdrawal record for a (withdrawal hash, proof submitter) pair (fault-proof OP2).
/// @dev The fault-proof portal keys proven withdrawals by BOTH the hash and the submitter (this adapter, which
/// called `proveWithdrawalTransaction`). A withdrawal is proven ⟺ `disputeGameProxy != address(0)`.
/// @param _withdrawalHash Hash of the withdrawal transaction
/// @param _proofSubmitter The address that proved the withdrawal (this adapter)
/// @return disputeGameProxy The dispute game the withdrawal was proven against (zero if not proven)
/// @return timestamp The time at which the withdrawal was proven
function provenWithdrawals(bytes32 _withdrawalHash, address _proofSubmitter)
external
view
returns (address disputeGameProxy, uint64 timestamp);
/// @notice Checks if a withdrawal transaction has already been finalized on the portal
/// @dev The portal's finalize is permissionless and reverts on a second call for the same hash. The adapter
/// reads this to stay idempotent: if a third party front-ran the finalize (funds already delivered to the
/// adapter), it skips the re-finalize instead of reverting the whole completion.
/// @param _withdrawalHash Hash of the withdrawal transaction
/// @return True if already finalized, false otherwise
function finalizedWithdrawals(bytes32 _withdrawalHash) external view returns (bool);
}
src/constants.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
uint8 constant NAV_DECIMALS = 8;
// Maximum safe exponent for 10^N calculations (max uint8 is 255)
// Used to prevent overflow in decimal exponentiation operations
uint256 constant MAX_DECIMAL_EXPONENT = 255;
// Maximum exponent such that 10^N fits in int256 (10^77 > type(int256).max)
uint256 constant MAX_DECIMAL_EXPONENT_INT256 = 76;
// Define the MANAGER role ID, used across NAVCalculator and bridge system for operational management
bytes32 constant MANAGER = keccak256("MANAGER"); // 0xaf290d8680820aad922855f39b306097b20e28774d6c1ad35a20325630c3a02c
bytes32 constant DEFAULT_ADMIN_ROLE = 0x00;
src/errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
error InvalidArguments();
error InvalidArgumentsWithContext(string context);
/// @notice A constructor argument expected to be a deployed contract has no code. `name` is the dependency label.
error NotAContract(string name);
error NotAuthorized();
error NotChainlinkOracle();
/// @notice Thrown when an assistant entrypoint that must be delegatecalled is called directly on the singleton
/// (`address(this) == SELF`). Canonical delegatecall-guard error for the assistant-fed family (`BalanceAdapterAssistant`).
error NotDelegateCall();
/// @notice An assistant entrypoint was told to track/act for an account other than the executing context
/// (`address(this)`, i.e. the delegatecalling Safe). Canonical assistant self-scope check (`_requireSelf`).
error AssistantAccountMismatch(address expected, address provided);
// Permissionless assistant-fed assisted balance-adapter family (ADR 0018) — shared coordinate-cache errors, used by the
// single {AssistedCoordCache} base (every coordinate is an `abi.encode`d blob). The coordinate is identified by `id`
// (a tokenId / requestId / positionTicket, from `_coordId`); the full tuple, where richer, rides in the cache's events.
/// @notice `submit` was given a coordinate not currently owned by the caller (`msg.sender`).
error CoordinateNotOwned(address account, uint256 id);
/// @notice `submit` would grow the caller's cache past its per-account cap.
error CoordinateCacheFull(address account, uint256 maxCoordinates);
/// @notice `remove` targeted a coordinate not in the caller's cache.
error CoordinateNotCached(address account, uint256 id);
/// @notice `remove` targeted a coordinate the caller still owns (a live position) — refused so a live position is never
/// dropped (would under-report the caller's own NAV). Only a claimed/consumed coordinate may be removed.
error CoordinateStillLive(address account, uint256 id);
/// @notice `submit` was given a coordinate that failed the adapter's write-time protocol validation (e.g. an
/// unregistered target). Distinct from {CoordinateNotOwned} (ownership) — this is a malformed/invalid coordinate.
error InvalidCoordinate(address account, uint256 id);
// Bridge-specific errors
error AlreadyInitialized();
error InvoiceNotFound();
error InvoiceAlreadyExists();
error InvalidInvoiceStatus();
error InvalidInvoice();
error TransferFailed();
error InsufficientBalance(address asset, uint256 required, uint256 available);
error InvalidChainId();
error InvalidNonce();
error InvalidCompletionData();
error InvalidChecksum(bytes32 invoiceId, bytes24 provided, bytes24 calculated);
error InvalidTimestamp(uint64 provided, uint64 current);
error AssetHasActiveInvoices(string symbol);
error AssetNotRegistered(string symbol);
// NAV Calculator / registry errors
error PriceFeedNotSet(address asset);
error AssetNotFound();
error OnlyNAVCalculator();
error ArrayLengthMismatch();
error InvalidAssetDecimals();
error InvalidDecimalExponent();
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {
"src/bridge/adapters/SuperchainBridgeAdapter.sol": {
"InvoiceDataLib": "0x67722a2821e249b888c4b608295e4975d99c67b3"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@chainlink/=lib/chainlink-brownie-contracts/contracts/",
"chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"@optimism/=lib/optimism/packages/contracts-bedrock/src/",
"comet-contracts/=lib/comet/contracts/",
"aave-v3-core/=lib/aave-v3-core/contracts/",
"gmx-contracts/=lib/gmx-contracts/contracts/",
"morpho-blue/=lib/morpho-blue/",
"@comet-contracts/=lib/comet/contracts/",
"@forge-std/=lib/comet/forge/lib/forge-std/",
"clones-with-immutable-args/=lib/optimism/packages/contracts-bedrock/lib/clones-with-immutable-args/src/",
"comet/=lib/comet/",
"ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"eth-gas-reporter/=lib/comet/node_modules/eth-gas-reporter/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/comet/node_modules/hardhat/",
"kontrol-cheatcodes/=lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/",
"lib-keccak/=lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/",
"optimism/=lib/optimism/",
"safe-contracts/=lib/optimism/packages/contracts-bedrock/lib/safe-contracts/contracts/",
"solady/=lib/optimism/packages/contracts-bedrock/lib/solady/",
"solmate/=lib/optimism/packages/contracts-bedrock/lib/solmate/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.