Verified contractExactMIT
StargateSwapAdapter
Address0x8376f2e420701e63a2ac19a0212e6c7d2d38457a
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.19
- Same code
Only this contract
Details
- Compiler
- solc 0.8.19+commit.7dd6d404
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,381,927
- Creation transaction
- 0x0c1edc5fcb…0a9faa5fe5
11 files
- contracts/bridges/adapters/StargateSwapAdapter.solmain3.96 KB
- contracts/base/Admin.sol1.3 KB
- contracts/base/GuardianAdmin.sol1.76 KB
- contracts/bridges/adapters/BridgeAdapterBase.sol4.49 KB
- contracts/bridges/adapters/StargateAdapterBase.sol11.43 KB
- contracts/bridges/interfaces/IBridgeSwapExecutor.sol1.39 KB
- contracts/bridges/interfaces/ILayerZeroComposer.sol1.14 KB
- contracts/bridges/libraries/OFTComposeMsgCodec.sol1.23 KB
- contracts/dex/SwapTypes.sol1.95 KB
- lib/solmate/src/tokens/ERC20.sol6.81 KB
- lib/solmate/src/utils/SafeTransferLib.sol6.26 KB
contracts/bridges/adapters/StargateSwapAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SwapStep } from "contracts/dex/SwapTypes.sol";
import { StargateAdapterBase } from "./StargateAdapterBase.sol";
import {
IBridgeSwapExecutor
} from "contracts/bridges/interfaces/IBridgeSwapExecutor.sol";
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
/// @title StargateSwapAdapter
/// @notice Receives Stargate V2 compose callbacks and swaps tokens via
/// BridgeSwapReceiver. This path is permissionless-by-design for funds that
/// arrive through authenticated Stargate compose callbacks, subject to the
/// endpoint/pool/source-EID checks. Any whitelisted Stargate sender on a
/// whitelisted source EID may choose `recipient`, `swapSteps`, and
/// `minAmountOut` for its own bridged funds.
/// Stargate delivers assets to this contract before lzCompose() is called, and
/// the adapter requires the local balance of the compose token to be at least
/// `amountLD` before forwarding. Any extra dust is left behind on the adapter
/// instead of being mixed into the current compose delivery. For native ETH
/// pools, the adapter wraps exactly `amountLD` to WETH.
contract StargateSwapAdapter is StargateAdapterBase {
error ReceiverAdapterDisabled();
// Same event ABI as historical receiver fallbacks. New generations emit
// fallback here; successful executions continue to emit on the receiver.
event BridgeSwapFallback(
address indexed recipient, address token, uint256 amount
);
IBridgeSwapExecutor public immutable receiver;
constructor(
address receiver_,
address admin_,
address guardian_,
address weth_
) StargateAdapterBase(admin_, guardian_, weth_) {
receiver = IBridgeSwapExecutor(receiver_);
}
function _processCompose(
address token,
uint256 amountLD,
bytes calldata userPayload,
uint32,
bytes32
) internal override {
token = _prepareInboundToken(token, amountLD);
(
address recipient,
SwapStep[] memory swapSteps,
uint256 minAmountOut,
uint256 nativeGasDrop,
uint256 swapDeadline
) = abi.decode(
userPayload, (address, SwapStep[], uint256, uint256, uint256)
);
// A governance pause must park funds for recovery, not refund them.
// Keep this outside the refund boundary, as on the legacy receiver.
if (!receiver.whitelistedAdapters(address(this))) {
revert ReceiverAdapterDisabled();
}
// Roll forwarding AND execution back together. The outer compose
// dispatcher has already consumed the GUID and catches refund failure.
try this.executeSwapExternal(
token,
amountLD,
recipient,
swapSteps,
minAmountOut,
nativeGasDrop,
swapDeadline
) { }
catch {
SafeTransferLib.safeTransfer(token, recipient, amountLD);
emit BridgeSwapFallback(recipient, token, amountLD);
}
}
/// @dev Only the authenticated processing self-call can reach this leg.
/// Reverting it restores the exact inbound amount to the adapter before
/// refunding; receiver dust and later deliveries are never the refund pot.
function executeSwapExternal(
address token,
uint256 amount,
address recipient,
SwapStep[] calldata swapSteps,
uint256 minAmountOut,
uint256 nativeGasDrop,
uint256 swapDeadline
) external {
if (msg.sender != address(this)) revert OnlySelf();
SafeTransferLib.safeTransfer(token, address(receiver), amount);
receiver.executeSwapStrict(
token,
amount,
recipient,
swapSteps,
minAmountOut,
nativeGasDrop,
swapDeadline
);
}
}
contracts/base/Admin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @title Admin contract
/// @author vfat.tools
/// @notice Provides an administration mechanism allowing restricted functions
abstract contract Admin {
/// ERRORS ///
/// @notice Thrown when the caller is not the admin
error NotAdminError(); //0xb5c42b3b
/// EVENTS ///
/// @notice Emitted when a new admin is set
/// @param oldAdmin Address of the old admin
/// @param newAdmin Address of the new admin
event AdminSet(address oldAdmin, address newAdmin);
/// STORAGE ///
/// @notice Address of the current admin
address public admin;
/// MODIFIERS ///
/// @dev Restricts a function to the admin
modifier onlyAdmin() {
if (msg.sender != admin) revert NotAdminError();
_;
}
/// WRITE FUNCTIONS ///
/// @param admin_ Address of the admin
constructor(
address admin_
) {
emit AdminSet(address(0), admin_);
admin = admin_;
}
/// @notice Sets a new admin
/// @param newAdmin Address of the new admin
/// @custom:access Restricted to protocol admin.
function setAdmin(
address newAdmin
) external onlyAdmin {
emit AdminSet(admin, newAdmin);
admin = newAdmin;
}
}
contracts/base/GuardianAdmin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Admin } from "contracts/base/Admin.sol";
/// @title GuardianAdmin
/// @author vfat.tools
/// @notice Extends Admin with an optional guardian that can perform
/// emergency disable-only actions on inheriting bridge contracts.
abstract contract GuardianAdmin is Admin {
/// ERRORS ///
/// @notice Thrown when the caller is neither guardian nor admin
error NotGuardianOrAdminError();
/// EVENTS ///
/// @notice Emitted when a new guardian is set
/// @param oldGuardian Address of the old guardian
/// @param newGuardian Address of the new guardian
event GuardianSet(address oldGuardian, address newGuardian);
/// STORAGE ///
/// @notice Address of the current emergency guardian
address public guardian;
/// MODIFIERS ///
/// @dev Restricts a function to the guardian or admin
modifier onlyGuardianOrAdmin() {
_onlyGuardianOrAdmin();
_;
}
constructor(
address admin_,
address guardian_
) Admin(admin_) {
if (guardian_ != address(0)) {
emit GuardianSet(address(0), guardian_);
guardian = guardian_;
}
}
/// @notice Sets a new guardian
/// @param newGuardian Address of the new guardian
/// @custom:access Restricted to protocol admin.
function setGuardian(
address newGuardian
) external onlyAdmin {
if (newGuardian == guardian) return;
emit GuardianSet(guardian, newGuardian);
guardian = newGuardian;
}
function _onlyGuardianOrAdmin() internal view {
if (msg.sender != guardian && msg.sender != admin) {
revert NotGuardianOrAdminError();
}
}
}
contracts/bridges/adapters/BridgeAdapterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { GuardianAdmin } from "contracts/base/GuardianAdmin.sol";
/// @title BridgeAdapterBase
/// @notice Shared base for bridge adapters: endpoint whitelist + rescue.
abstract contract BridgeAdapterBase is GuardianAdmin {
error NotWhitelistedBridgeEndpoint();
/// Thrown when admin tries to whitelist a non-contract address as a
/// local callback endpoint.
error EndpointNotAContract();
event WhitelistedBridgeEndpointSet(address endpoint, bool whitelisted);
mapping(address => bool) public whitelistedBridgeEndpoints;
address[] private _bridgeEndpoints;
mapping(address => uint256) private _bridgeEndpointIndexPlusOne;
constructor(
address admin_,
address guardian_
) GuardianAdmin(admin_, guardian_) { }
/// @notice Enumerate the currently-allowed bridge endpoints.
function bridgeEndpoints() external view returns (address[] memory) {
return _bridgeEndpoints;
}
function setWhitelistedBridgeEndpoint(
address endpoint,
bool whitelisted
) external onlyAdmin {
_setWhitelistedBridgeEndpoint(endpoint, whitelisted);
}
/// @notice Emergency-disable a bridge endpoint without waiting on
/// governance. Re-enabling still requires the admin path.
function emergencyDisableBridgeEndpoint(
address endpoint
) external onlyGuardianOrAdmin {
_setWhitelistedBridgeEndpoint(endpoint, false);
}
function _setWhitelistedBridgeEndpoint(
address endpoint,
bool whitelisted
) internal {
// Same-chain callback endpoint must be a contract. Matches
// RouterAllowlist.setBridge / setRouter.
if (whitelisted && endpoint.code.length == 0) {
revert EndpointNotAContract();
}
bool currentlyAllowed = whitelistedBridgeEndpoints[endpoint];
if (currentlyAllowed == whitelisted) return;
whitelistedBridgeEndpoints[endpoint] = whitelisted;
if (whitelisted) {
_bridgeEndpointIndexPlusOne[endpoint] = _bridgeEndpoints.length + 1;
_bridgeEndpoints.push(endpoint);
} else {
uint256 indexPlusOne = _bridgeEndpointIndexPlusOne[endpoint];
// currentlyAllowed == true so the index must be set
uint256 index = indexPlusOne - 1;
uint256 lastIndex = _bridgeEndpoints.length - 1;
if (index != lastIndex) {
address last = _bridgeEndpoints[lastIndex];
_bridgeEndpoints[index] = last;
_bridgeEndpointIndexPlusOne[last] = index + 1;
}
_bridgeEndpoints.pop();
delete _bridgeEndpointIndexPlusOne[endpoint];
}
emit WhitelistedBridgeEndpointSet(endpoint, whitelisted);
}
function rescueTokens(
address token,
address to,
uint256 amount
) external virtual onlyAdmin {
SafeTransferLib.safeTransfer(token, to, amount);
}
function rescueETH(
address to
) external virtual onlyAdmin {
SafeTransferLib.safeTransferETH(to, address(this).balance);
}
function _onlyWhitelistedEndpoint() internal view {
if (!whitelistedBridgeEndpoints[msg.sender]) {
revert NotWhitelistedBridgeEndpoint();
}
}
/// @dev Forward up to `amount` tokens to `to`, capped to the adapter's
/// current balance so a bridge under-delivery does not revert the
/// forwarding leg. The returned `sent` is the nominal amount transferred
/// out by this contract; for fee-on-transfer or tax tokens the recipient
/// may receive less than `sent`, which downstream callers do not measure.
function _forwardAvailable(
address token,
address to,
uint256 amount
) internal returns (uint256 sent) {
uint256 available = _tokenBalance(token);
sent = available < amount ? available : amount;
if (sent > 0) {
SafeTransferLib.safeTransfer(token, to, sent);
}
}
function _tokenBalance(
address token
) internal view returns (uint256) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(0x70a08231, address(this))
);
if (!success || data.length < 32) return 0;
return abi.decode(data, (uint256));
}
}
contracts/bridges/adapters/StargateAdapterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { BridgeAdapterBase } from "./BridgeAdapterBase.sol";
import {
OFTComposeMsgCodec
} from "contracts/bridges/libraries/OFTComposeMsgCodec.sol";
import {
ILayerZeroComposer
} from "contracts/bridges/interfaces/ILayerZeroComposer.sol";
interface IWETHStargate {
function deposit() external payable;
}
/// @title StargateAdapterBase
/// @notice Shared Stargate adapter configuration and compose authentication.
abstract contract StargateAdapterBase is BridgeAdapterBase, ILayerZeroComposer {
error NotWhitelistedPool(address pool);
error NotWhitelistedSourceEid(uint32 srcEid);
error InsufficientNativeBalance(uint256 expectedAmount, uint256 actualBalance);
error InsufficientTokenBalance(
address token, uint256 expectedAmount, uint256 actualBalance
);
/// Thrown when a compose `_guid` has already been consumed. Prevents
/// replaying a failed-then-rescued compose against later same-token
/// balances on the adapter.
error ComposeAlreadyConsumed(bytes32 guid);
/// @dev Used by adapter-side try/catch self-calls so guid consumption
/// persists across downstream reverts.
error OnlySelf();
event WhitelistedPoolSet(address pool, address token, bool whitelisted);
event WhitelistedSourceEidSet(uint32 srcEid, bool whitelisted);
/// @notice Emitted when a compose `_guid` is marked consumed —
/// either by a successful authorize-and-consume or by an admin
/// explicitly invalidating it during a rescue.
event ComposeGuidConsumed(bytes32 indexed guid);
/// @notice Emitted when the outer `lzCompose` authorized a guid but
/// the inner processing reverted.
/// The guid stays consumed (so a LayerZero retry cannot replay against
/// later same-token funds), the inbound tokens stay parked on the
/// adapter, and admins must rescue them via `rescueTokens` /
/// `rescueETH`. `reason` is the raw revert payload from the inner
/// self-call for off-chain triage.
event ComposeProcessingFailed(
bytes32 indexed guid,
address indexed from,
uint32 indexed srcEid,
bytes32 composeFrom,
bytes reason
);
/// @notice Stargate pool / OFT addresses authorized to compose into this
/// adapter.
mapping(address => bool) public whitelistedPools;
/// @notice Token address per whitelisted Stargate sender.
/// @dev address(0) for native ETH pools.
mapping(address => address) public poolTokens;
/// @notice LayerZero source endpoint IDs allowed to reach this adapter.
mapping(uint32 => bool) public whitelistedSourceEids;
address[] private _pools;
mapping(address => uint256) private _poolIndexPlusOne;
uint32[] private _sourceEids;
mapping(uint32 => uint256) private _sourceEidIndexPlusOne;
/// @notice Tracks LayerZero compose `_guid`s already authenticated by
/// this adapter (whether the downstream call succeeded or reverted).
/// A consumed guid can never be replayed against later same-token
/// balances on the adapter. Admins can invalidate additional guids
/// explicitly via `invalidateComposeGuid` before or alongside a
/// `rescueTokens` / `rescueETH` recovery.
mapping(bytes32 guid => bool consumed) public consumedComposeGuid;
/// @notice WETH (or equivalent wrapped-native) used to wrap native ETH
/// pool deliveries before forwarding downstream.
address public immutable weth;
constructor(
address admin_,
address guardian_,
address weth_
) BridgeAdapterBase(admin_, guardian_) {
weth = weth_;
}
/// @notice LayerZero V2 compose callback. Authorizes the guid (consuming
/// it irreversibly via `_authorizeCompose`) then dispatches the downstream
/// processing via an external self-call wrapped in try/catch. If the inner
/// work reverts, the guid stays consumed — LayerZero retries cannot replay
/// against later same-token balances — and the inbound tokens stay parked
/// for admin rescue.
function lzCompose(
address _from,
bytes32 _guid,
bytes calldata _message,
address,
bytes calldata
) external payable override {
(
address token,
uint256 amountLD,
bytes calldata userPayload,
uint32 srcEid,
bytes32 composeFrom
) = _authorizeCompose(_from, _guid, _message);
try this.lzComposeExternal{ value: msg.value }(
token, amountLD, userPayload, srcEid, composeFrom
) {
// success
} catch (bytes memory reason) {
emit ComposeProcessingFailed(
_guid, _from, srcEid, composeFrom, reason
);
}
}
/// @dev Self-callable inner dispatcher. Reverts on validation /
/// downstream failure; the outer try/catch in `lzCompose` keeps the
/// guid consumed regardless.
function lzComposeExternal(
address token,
uint256 amountLD,
bytes calldata userPayload,
uint32 srcEid,
bytes32 composeFrom
) external payable {
if (msg.sender != address(this)) revert OnlySelf();
_processCompose(token, amountLD, userPayload, srcEid, composeFrom);
}
/// @dev Adapter-specific compose handler. Implementations decode the
/// user payload, prepare the inbound token via `_prepareInboundToken`,
/// and forward to the downstream receiver/strategy.
function _processCompose(
address token,
uint256 amountLD,
bytes calldata userPayload,
uint32 srcEid,
bytes32 composeFrom
) internal virtual;
/// @dev Native pool (token == address(0)): wraps exactly `amountLD` of
/// the delivered ETH to WETH. ERC20 pool: validates the local balance
/// is at least `amountLD`. Returns the effective token to forward.
function _prepareInboundToken(
address token,
uint256 amountLD
) internal returns (address) {
if (token == address(0)) {
// `msg.value` is a separate LayerZero native drop (forwarded
// downstream by the route adapter), not part of the bridged
// delivery — exclude it so wrapping `amountLD` cannot dip into it.
uint256 balance = address(this).balance - msg.value;
if (balance < amountLD) {
revert InsufficientNativeBalance(amountLD, balance);
}
IWETHStargate(weth).deposit{ value: amountLD }();
return weth;
}
_requireSufficientTokenBalance(token, amountLD);
return token;
}
receive() external payable { }
function pools() external view returns (address[] memory) {
return _pools;
}
function sourceEids() external view returns (uint32[] memory) {
return _sourceEids;
}
function setWhitelistedPool(
address pool,
address token,
bool whitelisted
) external onlyAdmin {
bool currentlyAllowed = whitelistedPools[pool];
if (currentlyAllowed == whitelisted) {
if (whitelisted && poolTokens[pool] != token) {
poolTokens[pool] = token;
emit WhitelistedPoolSet(pool, token, true);
}
return;
}
whitelistedPools[pool] = whitelisted;
if (whitelisted) {
poolTokens[pool] = token;
_poolIndexPlusOne[pool] = _pools.length + 1;
_pools.push(pool);
emit WhitelistedPoolSet(pool, token, true);
return;
}
uint256 indexPlusOne = _poolIndexPlusOne[pool];
uint256 index = indexPlusOne - 1;
uint256 lastIndex = _pools.length - 1;
if (index != lastIndex) {
address last = _pools[lastIndex];
_pools[index] = last;
_poolIndexPlusOne[last] = index + 1;
}
_pools.pop();
delete _poolIndexPlusOne[pool];
emit WhitelistedPoolSet(pool, poolTokens[pool], false);
}
function setWhitelistedSourceEid(
uint32 srcEid,
bool whitelisted
) external onlyAdmin {
bool currentlyAllowed = whitelistedSourceEids[srcEid];
if (currentlyAllowed == whitelisted) return;
whitelistedSourceEids[srcEid] = whitelisted;
if (whitelisted) {
_sourceEidIndexPlusOne[srcEid] = _sourceEids.length + 1;
_sourceEids.push(srcEid);
} else {
uint256 indexPlusOne = _sourceEidIndexPlusOne[srcEid];
uint256 index = indexPlusOne - 1;
uint256 lastIndex = _sourceEids.length - 1;
if (index != lastIndex) {
uint32 last = _sourceEids[lastIndex];
_sourceEids[index] = last;
_sourceEidIndexPlusOne[last] = index + 1;
}
_sourceEids.pop();
delete _sourceEidIndexPlusOne[srcEid];
}
emit WhitelistedSourceEidSet(srcEid, whitelisted);
}
function _requireSufficientTokenBalance(
address token,
uint256 amountLD
) internal view {
uint256 balance = _tokenBalance(token);
if (balance < amountLD) {
revert InsufficientTokenBalance(token, amountLD, balance);
}
}
function _authorizeCompose(
address _from,
bytes32 _guid,
bytes calldata _message
)
internal
returns (
address token,
uint256 amountLD,
bytes calldata userPayload,
uint32 srcEid,
bytes32 composeFrom
)
{
_onlyWhitelistedEndpoint();
if (!whitelistedPools[_from]) revert NotWhitelistedPool(_from);
srcEid = OFTComposeMsgCodec.srcEid(_message);
if (!whitelistedSourceEids[srcEid]) {
revert NotWhitelistedSourceEid(srcEid);
}
// Mark the compose guid as consumed. The flag only persists across
// a downstream revert when the **caller** (each Stargate adapter's
// `lzCompose`) wraps the downstream processing in a try/catch
// self-call so the outer transaction does not revert. Without that
// pattern, the outer revert would roll back this assignment and the
// LayerZero compose would remain replayable.
if (consumedComposeGuid[_guid]) {
revert ComposeAlreadyConsumed(_guid);
}
consumedComposeGuid[_guid] = true;
emit ComposeGuidConsumed(_guid);
composeFrom = OFTComposeMsgCodec.composeFrom(_message);
token = poolTokens[_from];
amountLD = OFTComposeMsgCodec.amountLD(_message);
userPayload = OFTComposeMsgCodec.composeMsg(_message);
}
/// @notice Admin handle to invalidate a compose `_guid` so it can
/// never trigger an `lzCompose` callback on this adapter. Intended to
/// pair with `rescueTokens` /
/// `rescueETH` after a failed delivery: rescue the parked funds, then
/// (or simultaneously) invalidate the guid so the still-queued
/// LayerZero compose cannot replay against a later balance.
function invalidateComposeGuid(
bytes32 guid
) external onlyAdmin {
if (consumedComposeGuid[guid]) return;
consumedComposeGuid[guid] = true;
emit ComposeGuidConsumed(guid);
}
}
contracts/bridges/interfaces/IBridgeSwapExecutor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SwapStep } from "contracts/dex/SwapTypes.sol";
/// @notice Stable strict execution boundary. The caller owns delivery,
/// authentication, replay and recovery policy; failures propagate unchanged.
interface IBridgeSwapExecutor {
function whitelistedAdapters(
address adapter
) external view returns (bool);
function executeSwapStrict(
address token,
uint256 amount,
address recipient,
SwapStep[] calldata swapSteps,
uint256 minAmountOut,
uint256 nativeGasDrop,
uint256 swapDeadline
) external;
}
/// @notice Compatibility surface for adapters deployed with receiver-side
/// graceful recovery. Retain these wire entrypoints for in-flight deliveries.
interface ILegacyBridgeSwapReceiver {
function executeSwap(
address token,
uint256 amount,
address recipient,
SwapStep[] calldata swapSteps,
uint256 minAmountOut,
uint256 nativeGasDrop,
uint256 swapDeadline
) external;
function executeSwapWithNativeGasDropToken(
address token,
uint256 amount,
address nativeGasDropToken,
uint256 nativeGasDrop,
address recipient,
SwapStep[] calldata swapSteps,
uint256 minAmountOut,
uint256 swapDeadline
) external;
}
contracts/bridges/interfaces/ILayerZeroComposer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @title ILayerZeroComposer
/// @notice Interface for contracts that receive composed messages via
/// LayerZero V2. Used by Stargate V2 to trigger destination-side logic
/// after token delivery.
interface ILayerZeroComposer {
/// @notice Called by the LayerZero Endpoint after a composed message
/// is queued by an OApp (e.g., a Stargate pool).
/// @param _from The OApp that originated the compose (Stargate pool)
/// @param _guid Unique identifier for the LZ transaction
/// @param _message Bridge-specific composed payload. Stargate V2
/// composes through the OFT envelope:
/// nonce (8 bytes) + srcEid (4 bytes) + amountLD (32 bytes)
/// + composeFrom (32 bytes) + user composeMsg (remaining bytes)
/// @param _executor The executor that delivered this compose
/// @param _extraData Arbitrary extra data from the executor
function lzCompose(
address _from,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable;
}
contracts/bridges/libraries/OFTComposeMsgCodec.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @title OFTComposeMsgCodec
/// @notice Decodes LayerZero V2 OFT compose messages.
/// @dev Byte layout:
/// [0:8] nonce (uint64)
/// [8:12] srcEid (uint32)
/// [12:44] amountLD (uint256) — token amount in local decimals
/// [44:76] composeFrom (bytes32) — original sender on source chain
/// [76:] composeMsg (bytes) — user payload from SendParam.composeMsg
/// Short or malformed messages revert on calldata slicing.
library OFTComposeMsgCodec {
function srcEid(bytes calldata _message) internal pure returns (uint32) {
return uint32(bytes4(_message[8:12]));
}
/// @notice Extract the token amount in local decimals
function amountLD(
bytes calldata _message
) internal pure returns (uint256) {
return uint256(bytes32(_message[12:44]));
}
function composeFrom(
bytes calldata _message
) internal pure returns (bytes32) {
return bytes32(_message[44:76]);
}
/// @notice Extract the user compose message payload
function composeMsg(
bytes calldata _message
) internal pure returns (bytes calldata) {
return _message[76:];
}
}
contracts/dex/SwapTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @notice DEX types `SwapRouter` knows how to dispatch. This enum is a
/// set of named constants only — `SwapStep.dexType` is a raw `uint8` (not
/// this enum), so the dispatch table `dexAdapter[uint8]` carries the byte
/// directly with no enum range-check at the ABI boundary. A new *standard*
/// type (allow-listed router + ERC20 `tokenIn`) can therefore be appended
/// and dispatched on an already-deployed `SwapRouter` via `setDexAdapter`
/// alone — no redeploy. NOTE this does NOT cover a type that needs a new
/// `SwapRouter._executeStep` exemption (router-allowlist bypass or
/// native-ETH `tokenIn`); those exemption lists are hardcoded and still
/// require a `SwapRouter` redeploy. Append new entries rather than
/// reordering existing ones.
enum DexType {
UniswapV2,
UniswapV3Router02,
Solidly,
Algebra,
UniswapV4,
VelodromeUniversalRouter,
UniswapV3Router,
AerodromeRouter,
AlgebraPool,
SlipstreamRouter,
BlackholeV2Router,
UniswapV3Pool,
WrapWETH,
UnwrapWETH,
CamelotV2Router,
PancakeInfinity,
AaveSupply,
AaveWithdraw,
BaselineRelay,
FlowStateMarket,
SolidlyPool,
AeroMetarouter,
UniswapV2Fot,
BushAggregatorRouter,
LiquidityBook,
CurveStableNgPool,
MorphoVaultV2Deposit,
MorphoVaultV2Redeem,
AeroTokenMigration
}
/// @notice One hop of a multi-step swap. Stable, ABI-stable struct used
/// by `SwapRouter`, every `IDexAdapter`, every bridge swap receiver, and
/// every off-chain encoder (vfat-api, deploy scripts).
struct SwapStep {
/// @dev Raw `uint8` (not the `DexType` enum) so dispatch is purely
/// `dexAdapter[dexType]` — adding a new DEX type never requires
/// redeploying `SwapRouter`. Compare against `uint8(DexType.X)`.
uint8 dexType;
address router;
address tokenIn;
address tokenOut;
bytes dexData;
}
lib/solmate/src/tokens/ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
lib/solmate/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error ETHTransferFailed();
error TransferFromFailed();
error TransferFailed();
error ApproveFailed();
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
if (!success) revert ETHTransferFailed();
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
address token,
address from,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
if (!success) revert TransferFromFailed();
}
function safeTransfer(
address token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert TransferFailed();
}
function safeApprove(
address token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert ApproveFailed();
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"solmate/=lib/solmate/src/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"@morpho-blue/=lib/morpho-blue/src/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"morpho-blue/=lib/morpho-blue/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.