Verified contractPartialMIT
OptimismBridgeModule
Address0x797a317d1d834b3b663e62acf9d3452aacee8cd4
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.25
- Same code
1 more contract
Details
- Compiler
- solc 0.8.25+commit.b61c2a91
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,491,634
- Creation transaction
- 0xb18708fdac…db7d925eb3
20 files
- src/modules/bridge/OptimismBridgeModule.solmain2.56 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.06 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol799 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol1.94 KB
- lib/openzeppelin-contracts/contracts/utils/ShortStrings.sol4.31 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol9.32 KB
- lib/solady/src/utils/SafeTransferLib.sol26.32 KB
- src/modules/base/BaseModule.sol2.47 KB
- src/modules/bridge/base/BridgeModuleBase.sol4.71 KB
- src/modules/bridge/base/OptimismStackBridgeModule.sol7.29 KB
- src/modules/bridge/interfaces/optimism/IL1StandardBridge.sol4.05 KB
- src/modules/bridge/interfaces/optimism/IOptimismBridgeModule.sol845 B
- src/modules/bridge/interfaces/optimism/IOptimismStackBridgeModule.sol2.88 KB
- src/modules/interfaces/IModule.sol1.16 KB
- src/modules/libraries/BridgeLib.sol13.11 KB
- src/modules/libraries/ERC20UtilsLib.sol13.8 KB
- src/types/Bridge.sol2.57 KB
- src/types/BridgeContext.sol1.8 KB
- src/types/Order.sol2.98 KB
- src/types/ProductiveOrder.sol3.2 KB
src/modules/bridge/OptimismBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Contracts
import { OptimismStackBridgeModule } from "@modules/bridge/base/OptimismStackBridgeModule.sol";
// Interfaces
import { IOptimismBridgeModule } from "@modules/bridge/interfaces/optimism/IOptimismBridgeModule.sol";
import { IModule } from "@modules/interfaces/IModule.sol";
// Libraries
import { BridgeLib } from "@modules/libraries/BridgeLib.sol";
// Types
import { BridgeContext } from "@types/BridgeContext.sol";
/// @title Optimism Bridge Module
/// @notice Bridge module implementation for Optimism's native L1StandardBridge
/// @dev Supports both ETH and ERC20 bridging to Optimism (L2)
contract OptimismBridgeModule is OptimismStackBridgeModule, IOptimismBridgeModule {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Optimism chain ID
uint256 private constant OPTIMISM_CHAIN_ID = 10;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Constructor for OptimismBridgeModule
/// @param _portikusV2 The PortikusV2 contract address
/// @param _l1StandardBridge The L1StandardBridge contract address
constructor(
address _portikusV2,
address _l1StandardBridge
)
OptimismStackBridgeModule("Optimism Bridge Module", "2.3.0", _portikusV2, _l1StandardBridge, OPTIMISM_CHAIN_ID)
{ }
/// @inheritdoc OptimismStackBridgeModule
function _bridgeProtocol() internal pure override returns (string memory) {
return "optimism";
}
/*//////////////////////////////////////////////////////////////
EXTERNAL
//////////////////////////////////////////////////////////////*/
/// @notice Bridges tokens using Optimism's native L1StandardBridge
/// @param ctx The bridge context containing all necessary bridging information
function bridgeWithOptimism(BridgeContext memory ctx) external payable {
// Require bridge access authorization from settlement module
BridgeLib.consumeBridgeAuthorization();
_bridgeInternal(ctx);
}
/// @inheritdoc IModule
function selectors() external pure override returns (bytes4[] memory moduleSelectors) {
moduleSelectors = new bytes4[](1);
moduleSelectors[0] = this.bridgeWithOptimism.selector;
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*/
abstract contract ReentrancyGuardTransient {
using StorageSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/ShortStrings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
/// @solidity memory-safe-assembly
assembly {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.24;
/**
* @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;
* }
* }
* ```
*
* Since version 5.1, this library also support writing and reading value types to and from transient storage.
*
* * Example using transient storage:
* ```solidity
* contract Lock {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library 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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlotType.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlotType) {
return AddressSlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlotType.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlotType) {
return BooleanSlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32SlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32SlotType.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32SlotType) {
return Bytes32SlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256SlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256SlotType.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256SlotType) {
return Uint256SlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256SlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256SlotType.
*/
function asInt256(bytes32 slot) internal pure returns (Int256SlotType) {
return Int256SlotType.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlotType slot) internal view returns (address value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlotType slot, address value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlotType slot) internal view returns (bool value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlotType slot, bool value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32SlotType slot) internal view returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32SlotType slot, bytes32 value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256SlotType slot) internal view returns (uint256 value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256SlotType slot, uint256 value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256SlotType slot) internal view returns (int256 value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256SlotType slot, int256 value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `1` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
}
src/modules/base/BaseModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Contracts
import { ReentrancyGuardTransient as ReentrancyGuard } from "@openzeppelin/utils/ReentrancyGuardTransient.sol";
// Interfaces
import { IModule } from "@modules/interfaces/IModule.sol";
// Libraries
import { ShortStrings, ShortString } from "@openzeppelin/utils/ShortStrings.sol";
/// @title Base Module
/// @notice An abstract base module to be inherited by all modules in the Portikus V2 protocol
abstract contract BaseModule is ReentrancyGuard, IModule {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ShortStrings for string;
using ShortStrings for ShortString;
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice The name and version of the module
ShortString private immutable NAME;
ShortString private immutable VERSION;
/// @notice The address of the Portikus V2 contract
address public immutable PORTIKUS_V2;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @param _name The name of the module
/// @param _version The version of the module
constructor(string memory _name, string memory _version, address _portikusV2) {
NAME = _name.toShortString();
VERSION = _version.toShortString();
PORTIKUS_V2 = _portikusV2;
}
/*//////////////////////////////////////////////////////////////
METADATA
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IModule
function name() external view virtual override returns (string memory) {
return NAME.toString();
}
/// @inheritdoc IModule
function version() external view virtual override returns (string memory) {
return VERSION.toString();
}
/*//////////////////////////////////////////////////////////////
SELECTORS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IModule
function selectors() external pure virtual override returns (bytes4[] memory moduleSelectors);
}
src/modules/bridge/base/BridgeModuleBase.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Contracts
import { BaseModule } from "@modules/base/BaseModule.sol";
// Libraries
import { SafeTransferLib } from "@solady/utils/SafeTransferLib.sol";
import { ERC20UtilsLib } from "@modules/libraries/ERC20UtilsLib.sol";
/// @title Bridge Module Base
/// @notice Abstract base contract for bridge modules containing shared functionality
/// @dev Provides common patterns, validations, and utilities for bridge implementations
abstract contract BridgeModuleBase is BaseModule {
using SafeTransferLib for address;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when protocol data is missing or empty
error MissingProtocolData();
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when tokens are bridged across chains
/// @param orderHash The hash of the order being bridged
/// @param beneficiary The recipient on the destination chain
/// @param destChainId The destination chain ID
/// @param inputAmount The amount of tokens being bridged (expressed in source token decimals)
/// @param outputAmount The expected amount on the destination chain, expressed in destination token decimals
/// after applying `_convertToDestDecimals`
/// @param bridgeProtocol The bridge protocol used (e.g., "optimism", "polygon", "cctp")
event TokensBridged(
bytes32 indexed orderHash,
address indexed beneficiary,
uint256 indexed destChainId,
uint256 inputAmount,
uint256 outputAmount,
string bridgeProtocol
);
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Constructor for BridgeModuleBase
/// @param _name The module name
/// @param _version The module version
/// @param _portikusV2 The PortikusV2 contract address
constructor(
string memory _name,
string memory _version,
address _portikusV2
)
BaseModule(_name, _version, _portikusV2)
{ }
/*//////////////////////////////////////////////////////////////
SHARED UTILITIES
//////////////////////////////////////////////////////////////*/
/// @notice Calculates agent fee with cap protection
/// @param requestedFee The requested agent fee
/// @param maxFee The maximum allowed fee
/// @return The capped agent fee
function _calculateCappedFee(uint256 requestedFee, uint256 maxFee) internal pure returns (uint256) {
return requestedFee > maxFee ? maxFee : requestedFee;
}
/*//////////////////////////////////////////////////////////////
DECIMAL CONVERSION
//////////////////////////////////////////////////////////////*/
/// @notice Converts an amount from source token decimals to destination token decimals
/// @dev scalingFactor = destDecimals - srcDecimals
///
/// Behavior:
/// - scalingFactor > 0 (dest has more decimals than src): multiply by 10^scalingFactor
/// - scalingFactor < 0 (dest has fewer decimals than src): divide by 10^(-scalingFactor)
///
/// Constraints:
/// - |scalingFactor| <= 18 to avoid 10^N overflow and keep gas predictable
///
/// Examples:
/// - USDC (6) -> WETH (18): scalingFactor = +12; 1e6 -> 1e6 * 10^12 = 1e18
/// - WETH (18) -> USDC (6): scalingFactor = -12; 1e18 -> 1e18 / 10^12 = 1e6
///
/// @param amount Amount expressed in source token decimals
/// @param scalingFactor Signed decimal difference (destDecimals - srcDecimals)
/// @return Amount expressed in destination token decimals
function _convertToDestDecimals(uint256 amount, int8 scalingFactor) internal pure returns (uint256) {
if (scalingFactor == 0) return amount;
// Validate scaling factor to prevent overflow
int8 absFactor = scalingFactor >= 0 ? scalingFactor : -scalingFactor;
require(uint8(absFactor) <= 18, "Bridge: scaling factor too large");
uint256 scale = 10 ** uint8(absFactor);
if (scalingFactor > 0) {
// destDecimals > srcDecimals: multiply to convert src -> dest
return amount * scale;
} else {
// srcDecimals > destDecimals: divide to convert src -> dest
return amount / scale;
}
}
}
src/modules/bridge/base/OptimismStackBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Contracts
import { BridgeModuleBase } from "@modules/bridge/base/BridgeModuleBase.sol";
// Interfaces
import { IL1StandardBridge } from "@modules/bridge/interfaces/optimism/IL1StandardBridge.sol";
import { IOptimismStackBridgeModule } from "@modules/bridge/interfaces/optimism/IOptimismStackBridgeModule.sol";
// Libraries
import { SafeTransferLib } from "@solady/utils/SafeTransferLib.sol";
import { ERC20UtilsLib } from "@modules/libraries/ERC20UtilsLib.sol";
// Types
import { BridgeContext } from "@types/BridgeContext.sol";
/// @title Optimism Stack Bridge Module Base
/// @notice Base contract for Optimism Stack bridge modules (Optimism, Base, etc.)
/// @dev Supports both ETH and ERC20 bridging using L1StandardBridge
abstract contract OptimismStackBridgeModule is BridgeModuleBase {
using SafeTransferLib for address;
using ERC20UtilsLib for address;
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Minimum gas limit for L2 transactions (default safety buffer)
uint32 private constant MIN_GAS_LIMIT = 200_000;
/// @notice The L1StandardBridge contract address
address public immutable L1_STANDARD_BRIDGE;
/// @notice The chain ID of the destination chain L1_STANDARD_BRIDGE deposits to
uint256 public immutable DEST_CHAIN_ID;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Constructor for OptimismStackBridgeModule
/// @param _name The module name
/// @param _version The module version
/// @param _portikusV2 The PortikusV2 contract address
/// @param _l1StandardBridge The L1StandardBridge contract address
/// @param _destChainId The chain ID of the destination chain
constructor(
string memory _name,
string memory _version,
address _portikusV2,
address _l1StandardBridge,
uint256 _destChainId
)
BridgeModuleBase(_name, _version, _portikusV2)
{
L1_STANDARD_BRIDGE = _l1StandardBridge;
DEST_CHAIN_ID = _destChainId;
}
/*//////////////////////////////////////////////////////////////
VIRTUAL
//////////////////////////////////////////////////////////////*/
/// @notice The bridge protocol name for event emission (e.g., "optimism", "base")
/// @dev Must return a bytecode literal, not storage: bridge modules run via delegatecall on the
/// adapter, so any storage written in the module constructor is unreadable at runtime.
function _bridgeProtocol() internal pure virtual returns (string memory);
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @notice Internal bridge implementation for Optimism Stack chains
/// @param ctx The bridge context containing all necessary bridging information
function _bridgeInternal(BridgeContext memory ctx) internal {
IOptimismStackBridgeModule.OptimismStackBridgeData memory protocolData = _validateAndDecodeProtocolData(ctx);
// Handle ETH vs ERC20 bridging
if (ctx.token.isEth()) {
_bridgeETH(protocolData, ctx);
} else {
_bridgeERC20(protocolData, ctx);
}
}
/// @notice Bridges ETH to L2
/// @param protocolData The validated bridge configuration
/// @param ctx The bridge context containing all necessary bridging information
function _bridgeETH(
IOptimismStackBridgeModule.OptimismStackBridgeData memory protocolData,
BridgeContext memory ctx
)
internal
{
// Call L1StandardBridge to deposit ETH
IL1StandardBridge(L1_STANDARD_BRIDGE).depositETHTo{ value: ctx.amount }(
ctx.beneficiary, protocolData.minGasLimit, protocolData.extraData
);
// Emit the bridge event with destination-decimal output amount
emit TokensBridged(
ctx.orderHash,
ctx.beneficiary,
ctx.destChainId,
ctx.amount,
_convertToDestDecimals(ctx.amount, ctx.scalingFactor),
_bridgeProtocol()
);
}
/// @notice Bridges ERC20 tokens to L2
/// @param protocolData The validated bridge configuration
/// @param ctx The bridge context containing all necessary bridging information
function _bridgeERC20(
IOptimismStackBridgeModule.OptimismStackBridgeData memory protocolData,
BridgeContext memory ctx
)
internal
{
// Validate protocol data
if (protocolData.l1Token == address(0)) revert IOptimismStackBridgeModule.InvalidL1Token();
if (protocolData.l2Token == address(0)) revert IOptimismStackBridgeModule.InvalidL2Token();
// Ensure the L1 token in protocol data matches the input token being bridged
if (protocolData.l1Token != ctx.token) revert IOptimismStackBridgeModule.InputTokenMismatch();
// Ensure the L2 token in protocol data matches the declared output token
if (protocolData.l2Token != ctx.outputToken) revert IOptimismStackBridgeModule.OutputTokenMismatch();
// Approve the L1StandardBridge to spend tokens
protocolData.l1Token.safeApprove(L1_STANDARD_BRIDGE, ctx.amount);
// Call L1StandardBridge to deposit ERC20 tokens
IL1StandardBridge(L1_STANDARD_BRIDGE)
.depositERC20To(
protocolData.l1Token,
protocolData.l2Token,
ctx.beneficiary,
ctx.amount,
protocolData.minGasLimit,
protocolData.extraData
);
// Emit the bridge event with destination-decimal output amount
emit TokensBridged(
ctx.orderHash,
ctx.beneficiary,
ctx.destChainId,
ctx.amount,
_convertToDestDecimals(ctx.amount, ctx.scalingFactor),
_bridgeProtocol()
);
}
/// @notice Validates and decodes the protocol data from the BridgeContext
/// @param ctx The bridge context containing the protocol data to validate
/// @return protocolData The validated and decoded bridge data
function _validateAndDecodeProtocolData(BridgeContext memory ctx)
internal
view
returns (IOptimismStackBridgeModule.OptimismStackBridgeData memory protocolData)
{
// Reject orders signed for a different L2 than L1_STANDARD_BRIDGE deposits to
if (ctx.destChainId != DEST_CHAIN_ID) revert IOptimismStackBridgeModule.InvalidDestChainId();
// Validate protocol data exists
if (ctx.protocolData.length == 0) revert MissingProtocolData();
// Decode protocol data
protocolData = abi.decode(ctx.protocolData, (IOptimismStackBridgeModule.OptimismStackBridgeData));
// Validate decoded data
if (protocolData.minGasLimit < MIN_GAS_LIMIT) revert IOptimismStackBridgeModule.InsufficientGasLimit();
}
}
src/modules/bridge/interfaces/optimism/IL1StandardBridge.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
/// @title L1 Standard Bridge Interface
/// @notice Interface for Optimism's L1StandardBridge contract
/// @dev Based on Optimism's official L1StandardBridge implementation
interface IL1StandardBridge {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when ETH is deposited from L1 to L2
/// @param from Address that deposited ETH on L1
/// @param to Address that will receive ETH on L2
/// @param amount Amount of ETH deposited
/// @param extraData Extra data attached to the deposit
event ETHDepositInitiated(address indexed from, address indexed to, uint256 amount, bytes extraData);
/// @notice Emitted when ERC20 tokens are deposited from L1 to L2
/// @param l1Token L1 token address
/// @param l2Token L2 token address
/// @param from Address that deposited tokens on L1
/// @param to Address that will receive tokens on L2
/// @param amount Amount of tokens deposited
/// @param extraData Extra data attached to the deposit
event ERC20DepositInitiated(
address indexed l1Token,
address indexed l2Token,
address indexed from,
address to,
uint256 amount,
bytes extraData
);
/*//////////////////////////////////////////////////////////////
ETH BRIDGING
//////////////////////////////////////////////////////////////*/
/// @notice Deposits ETH to the caller's address on L2
/// @param _minGasLimit Minimum gas limit for the L2 transaction
/// @param _extraData Optional data to forward to L2 (usually empty)
function depositETH(uint32 _minGasLimit, bytes calldata _extraData) external payable;
/// @notice Deposits ETH to a specified address on L2
/// @param _to Address to receive ETH on L2
/// @param _minGasLimit Minimum gas limit for the L2 transaction
/// @param _extraData Optional data to forward to L2 (usually empty)
function depositETHTo(address _to, uint32 _minGasLimit, bytes calldata _extraData) external payable;
/*//////////////////////////////////////////////////////////////
ERC20 BRIDGING
//////////////////////////////////////////////////////////////*/
/// @notice Deposits ERC20 tokens to the caller's address on L2
/// @param _l1Token L1 token address
/// @param _l2Token Corresponding L2 token address
/// @param _amount Amount of tokens to deposit
/// @param _minGasLimit Minimum gas limit for the L2 transaction
/// @param _extraData Optional data to forward to L2 (usually empty)
function depositERC20(
address _l1Token,
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
)
external;
/// @notice Deposits ERC20 tokens to a specified address on L2
/// @param _l1Token L1 token address
/// @param _l2Token L2 token address
/// @param _to Address to receive tokens on L2
/// @param _amount Amount of tokens to deposit
/// @param _minGasLimit Minimum gas limit for the L2 transaction
/// @param _extraData Optional data to forward to L2 (usually empty)
function depositERC20To(
address _l1Token,
address _l2Token,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
)
external;
/*//////////////////////////////////////////////////////////////
UTILITIES
//////////////////////////////////////////////////////////////*/
/// @notice Returns the L2 token bridge address
/// @return L2 token bridge address
function l2TokenBridge() external view returns (address);
/// @notice Returns the messenger contract address
/// @return Messenger contract address
function messenger() external view returns (address);
}
src/modules/bridge/interfaces/optimism/IOptimismBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Interfaces
import { IOptimismStackBridgeModule } from "@modules/bridge/interfaces/optimism/IOptimismStackBridgeModule.sol";
// Types
import { BridgeContext } from "@types/BridgeContext.sol";
/// @title Optimism Bridge Module Interface
/// @notice Interface for Optimism's native L1StandardBridge protocol
interface IOptimismBridgeModule is IOptimismStackBridgeModule {
/*//////////////////////////////////////////////////////////////
EXTERNAL
//////////////////////////////////////////////////////////////*/
/// @notice Bridges tokens using Optimism's native L1StandardBridge
/// @param ctx The bridge context containing all necessary bridging information
function bridgeWithOptimism(BridgeContext memory ctx) external payable;
}
src/modules/bridge/interfaces/optimism/IOptimismStackBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Types
import { Order } from "@types/Order.sol";
/// @title Optimism Stack Bridge Module Interface
/// @notice Common interface for all Optimism Stack-based bridge modules (Optimism, Base, etc.)
interface IOptimismStackBridgeModule {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when L1 token address is invalid (zero address)
error InvalidL1Token();
/// @notice Thrown when L2 token address is invalid (zero address)
error InvalidL2Token();
/// @notice Thrown when gas limit is too low for L2 execution
error InsufficientGasLimit();
/// @notice Thrown when l1Token in protocol data doesn't match the input token being bridged
error InputTokenMismatch();
/// @notice Thrown when l2Token in protocol data doesn't match the declared output token
error OutputTokenMismatch();
/// @notice Thrown when the context destination chain ID doesn't match the chain this module bridges to
error InvalidDestChainId();
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/// @notice Protocol-controlled Optimism Stack bridge configuration
/// @dev This struct defines the data encoded in order.bridge.protocolData by the backend
/// These parameters cannot be manipulated by agents during execution
/// @dev Used by all Optimism Stack chains (Optimism, Base, Arbitrum One, Polygon, etc.)
struct OptimismStackBridgeData {
/// @dev The L1 token address (source chain)
address l1Token;
/// @dev The corresponding L2 token address (destination chain)
address l2Token;
/// @dev Minimum gas limit for L2 transaction execution
uint32 minGasLimit;
/// @dev Optional calldata for L2 execution (usually empty)
bytes extraData;
}
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when tokens are successfully bridged to an Optimism Stack L2
/// @param order The order that initiated the bridge
/// @param beneficiary The recipient address on L2
/// @param inputAmount The amount of tokens bridged
/// @param l1Token The L1 token address
/// @param l2Token The L2 token address
/// @param destinationChainId The L2 chain ID
event TokensBridged(
Order indexed order,
address indexed beneficiary,
uint256 inputAmount,
address indexed l1Token,
address l2Token,
uint256 destinationChainId
);
}
src/modules/interfaces/IModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
/// @title IModule
/// @notice Core interfaces that all modules must implement to be compatible with the Portikus protocol
interface IModule {
/*//////////////////////////////////////////////////////////////
METADATA
//////////////////////////////////////////////////////////////*/
/// @notice Returns the name of the module
function name() external view returns (string memory);
/// @notice Returns the version of the module
function version() external view returns (string memory);
/*//////////////////////////////////////////////////////////////
SELECTORS
//////////////////////////////////////////////////////////////*/
/// @notice Used by the executor to determine which functions should be installed
/// @dev The implementation should not include any of the function selectors defined in the IModule interface itself
/// @return moduleSelectors An array of function selectors that the module implements
function selectors() external pure returns (bytes4[] memory moduleSelectors);
}
src/modules/libraries/BridgeLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import { Address } from "@openzeppelin/utils/Address.sol";
// Types
import { Order, OrderWithSig } from "@types/Order.sol";
import { ProductiveOrder, ProductiveOrderWithSig } from "@types/ProductiveOrder.sol";
import { Bridge, BridgeOverride } from "@types/Bridge.sol";
import { BridgeContext } from "@types/BridgeContext.sol";
/// @title Bridge Library
/// @notice Provides universal bridge functionality with support for dynamic protocol selection
/// @dev Handles bridge operations across multiple protocols with automatic override support.
/// Supports dynamic bridge selection via BridgeOverride for cosigned orders where users
/// delegate bridge selection to authorized protocol signers.
library BridgeLib {
using Address for address;
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice Transient-storage slot holding the single-use bridge authorization commitment.
/// @dev keccak256(abi.encode(uint256(keccak256("BridgeLib.initiated")) - 1)) & ~bytes32(uint256(0xff));
/// Holds keccak256 of the dispatch calldata (selector ++ encoded context) for the one bridge
/// call authorized by the current settlement, or 0 when none. Transient (EIP-1153): its
/// lifetime is exactly one transaction, so an authorization can never leak across transactions.
bytes32 internal constant BRIDGE_INITIATED_SLOT =
0x55784d688e8aecdf5908e67d2532e5fa1b0a3f379bbfebaef09e5fc7c0e69100;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when a bridge module is called without a matching, unconsumed authorization
/// @dev Replaces the former ambient "is any bridge in progress" check: authorization is now bound
/// to the exact (selector, context) and is consumed on entry, so a nested/reentrant bridge
/// selector - or the same selector with a different context - can never satisfy it.
error BridgeNotAuthorized();
/// @notice Thrown when no protocol selector is specified (neither by user nor override)
error MissingProtocolSelector();
/*//////////////////////////////////////////////////////////////
BRIDGE AUTHORIZATION
//////////////////////////////////////////////////////////////*/
/// @notice Authorizes exactly one bridge call, bound to the exact dispatch calldata
/// @dev Called by the dispatcher immediately before delegatecalling the selected bridge module,
/// with the SAME `callData` (abi.encodeWithSelector(selector, ctx)) that will be delegatecalled.
/// The commitment is keccak256 of that calldata (selector ++ encoded context), so it binds both
/// the target selector and the full context in a single hash - reusing the buffer already built
/// for dispatch instead of a second abi.encode of the struct. Overwrites any previous value.
/// @param callData The exact calldata about to be delegatecalled to the bridge module.
function authorizeBridge(bytes memory callData) internal {
bytes32 commitment = keccak256(callData);
bytes32 slot = BRIDGE_INITIATED_SLOT;
/// @solidity memory-safe-assembly
assembly {
tstore(slot, commitment)
}
}
/// @notice Clears any outstanding bridge authorization
/// @dev Defensive cleanup after dispatch; a well-behaved module already consumed it on entry.
function clearBridgeAuthorization() internal {
bytes32 slot = BRIDGE_INITIATED_SLOT;
/// @solidity memory-safe-assembly
assembly {
tstore(slot, 0)
}
}
/// @notice Validates and consumes the authorization for the currently executing bridge call
/// @dev MUST be the first action in every bridge module entrypoint, BEFORE any approval or external
/// call. It requires the stored commitment to equal keccak256(msg.data) - the module's calldata
/// is exactly the calldata authorizeBridge committed to (selector ++ encoded context), so this
/// needs no context re-encoding. It then zeroes the slot, making the authorization single-use:
/// by the time the module makes its external call (the reentrancy window) no authorization
/// remains, and any nested bridge selector - or the same selector with a different context - reverts.
function consumeBridgeAuthorization() internal {
bytes32 slot = BRIDGE_INITIATED_SLOT;
bytes32 expected;
bytes32 stored;
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
expected := keccak256(ptr, calldatasize())
stored := tload(slot)
// Consume immediately so the authorization cannot be reused within this transaction.
tstore(slot, 0)
}
if (stored == 0 || stored != expected) {
revert BridgeNotAuthorized();
}
}
/*//////////////////////////////////////////////////////////////
UNIVERSAL BRIDGE
//////////////////////////////////////////////////////////////*/
/// @notice Universal bridge function with automatic bridge override support for Order
/// @dev Main entry point for settlement modules to execute bridge operations.
/// Uses BridgeContext abstraction to decouple bridge operations from order types.
///
/// Bridge Override Logic:
/// - protocolSelector: User's choice takes precedence (if non-zero)
/// - protocolData: Use override's fresh data if cosignature is present, otherwise user's data
///
/// Note: Cosignature validation is done by settlement modules before calling this
///
/// @param orderWithSig The order with signature and optional bridge override
/// @param beneficiary The address to receive bridged tokens on destination chain
/// @param amount The amount of tokens to bridge
/// @param bridgeData Protocol-specific execution data (e.g., relayer fees, slippage)
/// @param orderHash The EIP-712 hash of the order (for event emission and tracking)
/// @return nativeFee The native fee paid to the bridge protocol (0 if not applicable)
function doBridge(
OrderWithSig memory orderWithSig,
address beneficiary,
uint256 amount,
bytes memory bridgeData,
bytes32 orderHash
)
internal
returns (uint256 nativeFee)
{
// Resolve protocol selector and data (with override support)
(bytes4 protocolSelector, bytes memory protocolData) =
_resolveProtocol(orderWithSig.order.bridge, orderWithSig.bridgeOverride, orderWithSig.cosignature);
// Build BridgeContext from Order fields
BridgeContext memory bridgeContext = BridgeContext({
token: orderWithSig.order.destToken,
owner: orderWithSig.order.owner,
beneficiary: beneficiary,
amount: amount,
destChainId: orderWithSig.order.bridge.destinationChainId,
outputToken: orderWithSig.order.bridge.outputToken,
scalingFactor: orderWithSig.order.bridge.scalingFactor,
protocolData: protocolData,
bridgeData: bridgeData,
orderHash: orderHash
});
nativeFee = _executeBridge(protocolSelector, bridgeContext);
}
/// @notice Universal bridge function with automatic bridge override support for ProductiveOrder
/// @dev See doBridge(OrderWithSig, ...) for full documentation
function doBridge(
ProductiveOrderWithSig memory orderWithSig,
address beneficiary,
uint256 amount,
bytes memory bridgeData,
bytes32 orderHash
)
internal
returns (uint256 nativeFee)
{
// Resolve protocol selector and data (with override support)
(bytes4 protocolSelector, bytes memory protocolData) =
_resolveProtocol(orderWithSig.order.bridge, orderWithSig.bridgeOverride, orderWithSig.cosignature);
// Build BridgeContext from ProductiveOrder fields
BridgeContext memory bridgeContext = BridgeContext({
token: orderWithSig.order.destToken,
owner: orderWithSig.order.owner,
beneficiary: beneficiary,
amount: amount,
destChainId: orderWithSig.order.bridge.destinationChainId,
outputToken: orderWithSig.order.bridge.outputToken,
scalingFactor: orderWithSig.order.bridge.scalingFactor,
protocolData: protocolData,
bridgeData: bridgeData,
orderHash: orderHash
});
nativeFee = _executeBridge(protocolSelector, bridgeContext);
}
/*//////////////////////////////////////////////////////////////
INTERNAL HELPERS
//////////////////////////////////////////////////////////////*/
/// @dev Resolves which protocol selector and data to use, applying override if present
/// @param bridge The bridge config from the signed order
/// @param bridgeOverride The optional bridge override (protocolSelector != bytes4(0) means active)
/// @return protocolSelector The resolved protocol selector
/// @return protocolData The resolved protocol-specific data
function _resolveProtocol(
Bridge memory bridge,
BridgeOverride memory bridgeOverride,
bytes memory cosignature
)
private
pure
returns (bytes4 protocolSelector, bytes memory protocolData)
{
// Start with user's specified values as defaults
protocolSelector = bridge.protocolSelector;
protocolData = bridge.protocolData;
bool userDelegated = protocolSelector == bytes4(0);
bool hasCosignature = cosignature.length > 0;
// No cosignature: use order as-is, no overrides allowed
if (!hasCosignature) {
if (userDelegated) revert MissingProtocolSelector();
return (protocolSelector, protocolData);
}
// Has cosignature: apply overrides
if (userDelegated) {
protocolSelector = bridgeOverride.protocolSelector;
}
// Use override's data
protocolData = bridgeOverride.protocolData;
if (protocolSelector == bytes4(0)) revert MissingProtocolSelector();
}
/// @dev Executes the bridge operation via delegatecall to the selected bridge module
/// @param protocolSelector The function selector of the bridge module to call
/// @param bridgeContext The complete bridge context with all required data
/// @return nativeFee The native fee paid to the bridge protocol (0 if not applicable)
function _executeBridge(
bytes4 protocolSelector,
BridgeContext memory bridgeContext
)
private
returns (uint256 nativeFee)
{
// Build the dispatch calldata once and authorize exactly it for a single consume by the module
bytes memory callData = abi.encodeWithSelector(protocolSelector, bridgeContext);
authorizeBridge(callData);
// Execute bridge via delegatecall to the selected bridge module
// The protocolSelector determines which bridge module function is called
// Use OpenZeppelin's Address library for better error handling and revert reason bubbling
bytes memory result = address(this).functionDelegateCall(callData);
// Decode native fee if returned by the bridge module
if (result.length != 0) nativeFee = abi.decode(result, (uint256));
// Defensive: clear any residual authorization (module consumes it on entry)
clearBridgeAuthorization();
}
/*//////////////////////////////////////////////////////////////
BRIDGE UTILITIES
//////////////////////////////////////////////////////////////*/
/// @notice Checks if the given order requires cross-chain bridging
/// @dev An order is a bridge order if:
/// 1. destinationChainId is non-zero (bridging is requested)
/// 2. destinationChainId differs from current chain (cross-chain transfer needed)
/// @param order The order to check
/// @return bool True if cross-chain bridging is required, false for same-chain orders
function isBridge(Order memory order) internal view returns (bool) {
return order.bridge.destinationChainId != 0 && order.bridge.destinationChainId != block.chainid;
}
/// @notice Overload of isBridge for ProductiveOrder
/// @dev See isBridge(Order) for full documentation
function isBridge(ProductiveOrder memory order) internal view returns (bool) {
return order.bridge.destinationChainId != 0 && order.bridge.destinationChainId != block.chainid;
}
}
src/modules/libraries/ERC20UtilsLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Libraries
import { SafeTransferLib } from "@solady/utils/SafeTransferLib.sol";
/// @title ERC20 Utility Library
/// @dev Library with common functions used by different modules within the Portikus V2 protocol
library ERC20UtilsLib {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when the permit execution fails
error PermitFailed();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev An address used to represent the native token
address internal constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev The address of the Permit2 contract
address internal constant PERMIT2_ADDRESS = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using SafeTransferLib for address;
/*//////////////////////////////////////////////////////////////
TRANSFER
//////////////////////////////////////////////////////////////*/
/// @dev Transfer the dest token to the order beneficiary, reducing the amount by 1 wei for gas optimization
/// purposes. If the destToken is ETH, it will transfer native ETH to recipient
/// @param destToken The address of the dest token
/// @param recipient The address to transfer to
/// @param amount The amount to transfer
function transferTo(address destToken, address recipient, uint256 amount) internal {
// If the destToken is ETH, transfer native ETH
if (isEth(destToken)) {
recipient.safeTransferETH(amount);
} else {
// Otherwise, transfer the dest token to the recipient, reducing the amount by 1 wei
// for gas optimization purposes
destToken.safeTransfer(recipient, amount);
}
}
/// @dev Transfer the src token from the user to a recipient, using permit2 allowance or erc20 allowance based on
/// permit length, if the permit length is 192 or 1 it will call transferFrom using permit2
/// allowance, otherwise it will call transferFrom using erc20 allowance unless permit length is 96
/// @param srcToken The address of the src token
/// @param owner The owner of the token
/// @param recipient The recipient of the token
/// @param amount The amount to transfer
/// @param permitLength The length of the permit
function transferFrom(
address srcToken,
address owner,
address recipient,
uint256 amount,
uint256 permitLength
)
internal
{
// Skip transferring if the permit length is 96 (permit2TransferFrom)
if (permitLength == 96) {
return;
}
// If the permit length is 192 or 1 execute permit2TransferFrom to transfer the
// input assets from the owner to the agent, otherwise execute ERC20 transferFrom
if (permitLength == 192 || permitLength == 1) {
// Transfer the input assets from the owner to the recipient using permit2 allowance
srcToken.permit2TransferFrom(owner, recipient, amount);
} else {
// Transfer the input assets from the owner to the recipient using the ERC20 transferFrom function
srcToken.safeTransferFrom(owner, recipient, amount);
}
}
/*//////////////////////////////////////////////////////////////
PERMIT
//////////////////////////////////////////////////////////////*/
/// @dev Executes the permit function on the provided token, depending on the permit length,
/// it will call the EIP2612 permit (224), DAI-Style permit (256), Permit2 AllowanceTransfer (192)
/// or Permit2 Signature (96)
/// @param token The address of the token
/// @param data The permit data
/// @param owner The owner of the token (used for Permit2)
/// @param deadline The deadline for the permit (used for Permit2)
/// @param amount The amount to permit (used for Permit2)
function permit(
address token,
bytes calldata data,
address owner,
uint256 deadline,
uint256 amount,
address recipient
)
internal
{
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// check the permit length
switch data.length
// 0x00 = no permit
case 0x00 {
// do nothing
}
case 0x01 {
// 0x01 is used to signify already existing permit2 allowance
}
// 32(permit2nonce) + 64(signature) = 96 Permit2 Transfer format
case 0x60 {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0x30f28b7a00000000000000000000000000000000000000000000000000000000) // store the selector
mstore(add(x, 0x04), token) // store the srcToken
mstore(add(x, 0x24), amount) // store the amount
calldatacopy(add(x, 0x44), data.offset, 0x20) // copy the nonce
mstore(add(x, 0x64), deadline) // store the deadline
mstore(add(x, 0x84), recipient) // store the recipient address (executor)
mstore(add(x, 0xa4), amount) // store the amount
mstore(add(x, 0xc4), owner) // store the owner
mstore(add(x, 0xe4), 0x100) // store the offset
mstore(add(x, 0x104), 0x40) // store the length
calldatacopy(add(x, 0x124), add(data.offset, 0x20), 0x40) // copy the signature
// Call Permit2 contract and revert on failure
if iszero(call(gas(), PERMIT2_ADDRESS, 0x00, x, 0x164, 0x00, 0x00)) {
mstore(0x00, 0xb78cb0dd00000000000000000000000000000000000000000000000000000000) // store the
// selector
revert(0x00, 0x04) // Revert with PermitFailed error
}
}
// 32(amount) + 32(nonce) + 32(expiration) + 32(sigDeadline) + 64(signature) = 192 Permit2 allowance format
case 0xc0 {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0x2b67b57000000000000000000000000000000000000000000000000000000000) // store the selector
mstore(add(x, 0x04), owner) // store the owner address
mstore(add(x, 0x24), token) // store the token address
calldatacopy(add(x, 0x44), data.offset, 0x60) // copy amount, expiration, nonce
mstore(add(x, 0xa4), address()) // store this contract's address as the spender
calldatacopy(add(x, 0xc4), add(data.offset, 0x60), 0x20) // copy sigDeadline
mstore(add(x, 0xe4), 0x100) // store the offset for signature
mstore(add(x, 0x104), 0x40) // store the length of signature
calldatacopy(add(x, 0x124), add(data.offset, 0x80), 0x40) // copy the signature
// Call Permit2 contract and revert on failure
if iszero(call(gas(), PERMIT2_ADDRESS, 0x00, x, 0x164, 0x00, 0x00)) {
mstore(0x00, 0xb78cb0dd00000000000000000000000000000000000000000000000000000000) // store the
// selector
revert(0x00, 0x04) // Revert with PermitFailed error
}
}
// 32 * 7 = 224 EIP2612 Permit
case 0xe0 {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0xd505accf00000000000000000000000000000000000000000000000000000000) // store the selector
calldatacopy(add(x, 0x04), data.offset, 0xe0) // store the args
pop(call(gas(), token, 0x00, x, 0xe4, 0x00, 0x20)) // call ERC20 permit, skip checking return data
}
// 32 * 8 = 256 DAI-Style Permit
case 0x100 {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0x8fcbaf0c00000000000000000000000000000000000000000000000000000000) // store the selector
calldatacopy(add(x, 0x04), data.offset, 0x100) // store the args
pop(call(gas(), token, 0x00, x, 0x104, 0x00, 0x20)) // call ERC20 permit, skip checking return data
}
// Otherwise revert
default {
mstore(0x00, 0xb78cb0dd00000000000000000000000000000000000000000000000000000000) // store the selector
revert(0x00, 0x04) // Revert with PermitFailed error
}
}
}
/// @dev A fillable version of the permit function from this lib, that doesn't support Permit2 SignatureTransfer
/// @param token The address of the token
/// @param data The permit data
/// @param owner The owner of the token (used for Permit2)
function permit(address token, bytes calldata data, address owner) internal {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// check the permit length
switch data.length
// 0x00 = no permit
case 0x00 {
// do nothing
}
case 0x01 {
// 0x01 is used to signify already existing permit2 allowance
}
// 32(amount) + 32(nonce) + 32(expiration) + 32(sigDeadline) + 64(signature) = 192 Permit2 allowance format
case 0xc0 {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0x2b67b57000000000000000000000000000000000000000000000000000000000) // store the selector
mstore(add(x, 0x04), owner) // store the owner address
mstore(add(x, 0x24), token) // store the token address
calldatacopy(add(x, 0x44), data.offset, 0x60) // copy amount, expiration, nonce
mstore(add(x, 0xa4), address()) // store this contract's address as the spender
calldatacopy(add(x, 0xc4), add(data.offset, 0x60), 0x20) // copy sigDeadline
mstore(add(x, 0xe4), 0x100) // store the offset for signature
mstore(add(x, 0x104), 0x40) // store the length of signature
calldatacopy(add(x, 0x124), add(data.offset, 0x80), 0x40) // copy the signature
// Call Permit2 contract and revert on failure
if iszero(call(gas(), PERMIT2_ADDRESS, 0x00, x, 0x164, 0x00, 0x00)) {
mstore(0x00, 0xb78cb0dd00000000000000000000000000000000000000000000000000000000) // store the
// selector
revert(0x00, 0x04) // Revert with PermitFailed error
}
}
// 32 * 7 = 224 EIP2612 Permit
case 0xe0 {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0xd505accf00000000000000000000000000000000000000000000000000000000) // store the selector
calldatacopy(add(x, 0x04), data.offset, 0xe0) // store the args
pop(call(gas(), token, 0x00, x, 0xe4, 0x00, 0x20)) // call ERC20 permit, skip checking return data
}
// 32 * 8 = 256 DAI-Style Permit
case 0x100 {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0x8fcbaf0c00000000000000000000000000000000000000000000000000000000) // store the selector
calldatacopy(add(x, 0x04), data.offset, 0x100) // store the args
pop(call(gas(), token, 0x00, x, 0x104, 0x00, 0x20)) // call ERC20 permit, skip checking return data
}
// Otherwise revert
default {
mstore(0x00, 0xb78cb0dd00000000000000000000000000000000000000000000000000000000) // store the selector
revert(0x00, 0x04) // Revert with PermitFailed error
}
}
}
/*//////////////////////////////////////////////////////////////
UTILITIES
//////////////////////////////////////////////////////////////*/
/// @notice Checks if a token is ETH
/// @param token The token address to check
/// @return True if the token represents ETH
function isEth(address token) internal pure returns (bool) {
return token == ETH_ADDRESS;
}
/*//////////////////////////////////////////////////////////////
BALANCE
//////////////////////////////////////////////////////////////*/
/// @dev Returns the balance of address(this), works for both ETH and ERC20 tokens
function getBalance(address token) internal view returns (uint256 balanceOf) {
// solhint-disable-next-line no-inline-assembly
assembly {
switch eq(token, ETH_ADDRESS)
// ETH
case 0x01 { balanceOf := selfbalance() }
// ERC20
default {
let x := mload(0x40) // get the free memory pointer
mstore(x, 0x70a0823100000000000000000000000000000000000000000000000000000000) // store the selector
mstore(add(x, 0x04), address()) // store the account
let success := staticcall(gas(), token, x, 0x24, x, 0x20) // call balanceOf
if success { balanceOf := mload(x)} // load the balance
}
}
}
}
src/types/Bridge.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
/// @title Bridge Configuration Types
/// @notice User-facing bridge configuration types that are part of signed orders
/// @dev These structs are signed by users/protocols and stored in order data structures.
/// For internal execution types, see BridgeContext.sol
/// @dev Represents bridge configuration for cross-chain operations
/// This struct is part of the Order and is signed by the user
struct Bridge {
/// @dev The bridge protocol selector
/// This determines which bridge module will be used for execution
/// For co-signed orders, this should be bytes4(0) and the protocol will provide an override
bytes4 protocolSelector;
/// @dev The destination chain ID where tokens should be bridged
uint256 destinationChainId;
/// @dev The token address on the destination chain
address outputToken;
/// @dev Represents destDecimals - srcDecimals to convert between token decimal formats
/// Positive: dest has more decimals, divide amounts before bridge
/// Negative: src has more decimals, multiply amounts before bridge
/// Zero: same decimals, no conversion needed
int8 scalingFactor;
/// @dev Protocol-specific configuration data
/// Contains immutable parameters like destEid for Stargate or multiCallHandler for Across
/// For co-signed orders, this should be empty and the protocol will provide an override
bytes protocolData;
}
/// @notice Bridge protocol override for co-signed orders
/// @dev Allows users to delegate bridge selection to an authorized protocol signer while retaining control
/// over critical parameters (destinationChainId, outputToken).
///
/// When cosignature is present:
/// - protocolSelector must be non-zero and overrides order.bridge.protocolSelector
/// - protocolData overrides order.bridge.protocolData (bridge-specific configuration)
/// - The protocol signer must be authorized in SignersRegistry
///
/// When cosignature is not present:
/// - BridgeOverride is ignored (protocolSelector should be bytes4(0))
/// - order.bridge is used as-is
///
/// See BridgeCosignatureLib for signature verification logic.
struct BridgeOverride {
/// @notice The bridge protocol selector
/// @dev Overrides order.bridge.protocolSelector if non-zero
bytes4 protocolSelector;
/// @notice Protocol-specific bridge configuration data
/// @dev Overrides order.bridge.protocolData
bytes protocolData;
}
src/types/BridgeContext.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
/// @title BridgeContext
/// @notice Internal execution context for bridge modules
/// @dev This is a runtime struct created by BridgeLib during bridge execution.
/// It is never part of signed orders and exists only during the execution lifecycle.
/// Bridge modules receive this context and use it to perform cross-chain operations.
/// @notice Universal bridge context for all order types
/// @dev Contains all fields required for bridge execution, making bridge operations order-type agnostic.
/// This struct combines Order configuration with execution-specific data into a complete bridge context
/// that bridge modules can use regardless of the original order type.
struct BridgeContext {
/// @notice Token to bridge (the post-swap token on current chain)
address token;
/// @notice Order owner (used for depositor address and refunds/failures)
address owner;
/// @notice Final recipient address on destination chain (never address(0) - settlement modules ensure this)
address beneficiary;
/// @notice Amount of tokens to bridge (determined after swap and fees)
uint256 amount;
/// @notice Order hash for event emission and tracking
bytes32 orderHash;
/// @notice Target chain ID where tokens should be bridged
uint256 destChainId;
/// @notice Token address on the destination chain
address outputToken;
/// @notice Decimal conversion factor (destDecimals - srcDecimals)
int8 scalingFactor;
/// @notice Protocol-specific configuration data (e.g., destEid for Stargate, multiCallHandler for Across)
bytes protocolData;
/// @notice Protocol-specific execution data (e.g., agent fees, slippage, relayer preferences)
bytes bridgeData;
}
src/types/Order.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import { Bridge, BridgeOverride } from "./Bridge.sol";
/// @dev OrderKind enum to differentiate between sell and buy orders
enum OrderKind {
SELL,
BUY
}
/// @dev Order data structure containing the order details to be settled,
/// the order is signed by the owner to be executed by an agent
/// on behalf of the owner, executing the swap and transferring the
/// dest token to the beneficiary
struct Order {
/// @dev The address of the order owner
address owner;
/// @dev The address of the order beneficiary
address beneficiary;
/// @dev The address of the src token
address srcToken;
/// @dev The address of the dest token
address destToken;
/// @dev The amount of src token to swap
uint256 srcAmount;
/// @dev The minimum amount of dest token to receive
uint256 destAmount;
/// @dev The expected amount of tokens (for sell orders this is expected amount of dest token to receive, for buy
/// orders this is the expected amount of src token to spend)
uint256 expectedAmount;
/// @dev The deadline for the order (timestamp)
uint256 deadline;
/// @dev The type of order (SELL or BUY)
OrderKind kind;
/// @dev The nonce of the order
uint256 nonce;
/// @dev Encoded partner address, fee bps, and flags for the order
/// partnerAndFee = (partner << 96) | (partnerTakesSurplus << 8) | (capSurplus << 9) |
/// fee in bps (max fee is 2%)
uint256 partnerAndFee;
/// @dev Optional permit signature for the src token
bytes permit;
/// @dev Optional metadata for the order
bytes metadata;
/// @dev The bridge configuration, should contain all empty fields if cross-chain is not required
Bridge bridge;
}
/// @notice Order with user signature and optional protocol co-signature for bridge delegation
/// @dev Encapsulates the complete order execution data including optional bridge override mechanism
struct OrderWithSig {
/// @notice The order data struct
Order order;
/// @notice The user's EIP-712 signature on the order hash
bytes signature;
/// @notice Optional bridge override for delegated bridge selection
/// @dev When cosignature is present, these values override order.bridge.protocolSelector and
/// order.bridge.protocolData
/// When cosignature is absent, this field is ignored
/// Allows users to delegate optimal bridge selection to protocol while retaining control over
/// destination chain and output token
BridgeOverride bridgeOverride;
/// @notice Optional protocol co-signature authorizing the bridge override
/// @dev When present: bridgeOverride must be valid and will be applied (protocolSelector must be non-zero)
/// When absent: bridgeOverride is ignored, order.bridge is used as-is
/// Must be from an authorized signer in SignersRegistry
bytes cosignature;
}
src/types/ProductiveOrder.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import { Bridge, BridgeOverride } from "./Bridge.sol";
/// @dev Order data structure containing the order details to be settled,
/// the order is signed by the owner to be executed by an agent
/// on behalf of the owner, executing the swap and transferring the
/// dest token to the beneficiary.
/// ProductiveOrders are always SELL orders - the user sells srcToken (with accumulated yield)
/// for destToken. BUY semantics don't apply since source amount is fixed by strategy position.
struct ProductiveOrder {
/// @dev The address of the order owner
address owner;
/// @dev The address of the order beneficiary
address beneficiary;
/// @dev The address of the src token
address srcToken;
/// @dev The address of the dest token
address destToken;
/// @dev The amount of src token to swap
uint256 srcAmount;
/// @dev The minimum amount of dest token to receive
uint256 destAmount;
/// @dev The expected amount of dest token to receive (used for surplus/fee calculation)
uint256 expectedAmount;
/// @dev The deadline for the order (timestamp)
uint256 deadline;
/// @dev The nonce of the order
uint256 nonce;
/// @dev Encoded partner address, fee bps, and flags for the order
/// partnerAndFee = (partner << 96) | (partnerTakesSurplus << 8) | (capSurplus << 9) |
/// fee in bps (max fee is 2%)
uint256 partnerAndFee;
/// @dev Optional permit signature for the src token
bytes permit;
/// @dev Optional metadata for the order
bytes metadata;
/// @dev Strategy used for yield
address strategy;
/// @dev Amount of shares on order's creation
uint256 shares;
/// @dev Whether to use principal + yield or only initial principal for order's settlement
bool useShares;
/// @dev The bridge configuration, should contain all empty fields if cross-chain is not required
Bridge bridge;
}
/// @notice Order with user signature and optional protocol co-signature for bridge delegation
/// @dev Encapsulates the complete order execution data including optional bridge override mechanism
struct ProductiveOrderWithSig {
/// @notice The order data struct
ProductiveOrder order;
/// @notice The user's EIP-712 signature on the order hash
bytes signature;
/// @notice Optional bridge override for delegated bridge selection
/// @dev When cosignature is present, these values override order.bridge.protocolSelector and
/// order.bridge.protocolData
/// When cosignature is absent, this field is ignored
/// Allows users to delegate optimal bridge selection to protocol while retaining control over
/// destination chain and output token
BridgeOverride bridgeOverride;
/// @notice Optional protocol co-signature authorizing the bridge override
/// @dev When present: bridgeOverride must be valid and will be applied (protocolSelector must be non-zero)
/// When absent: bridgeOverride is ignored, order.bridge is used as-is
/// Must be from an authorized signer in SignersRegistry
bytes cosignature;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@forge-std/=lib/forge-std/src/",
"@interfaces/=src/interfaces/",
"@types/=src/types/",
"@libraries/=src/libraries/",
"@solady/=lib/solady/src/",
"@prb-test/=lib/prb-test/src/",
"@openzeppelin/=lib/openzeppelin-contracts/contracts/",
"@admin/=src/admin/",
"@executors/=src/executors/",
"@mocks/=test/mocks/",
"@factory/=src/factory/",
"@registry/=src/registry/",
"@modules/=src/modules/",
"@adapter/=src/adapter/",
"@tokens/=src/tokens/",
"@test/=test/",
"@aave-v3-core/=lib/aave-v3-core/contracts/",
"@create3/=lib/create3-factory/src/",
"@morpho/=lib/morpho-blue/src/",
"@uniswap-v4-core/=lib/v4-core/src/",
"lib/create3-factory/lib/create3-factory/lib/forge-std/:ds-test/=lib/create3-factory/lib/create3-factory/lib/forge-std/lib/ds-test/src/",
"lib/create3-factory/lib/create3-factory/lib/forge-std/:ds-test/=lib/create3-factory/lib/create3-factory/lib/forge-std/lib/ds-test/src/",
"lib/create3-factory/lib/create3-factory/lib/solmate/:ds-test/=lib/create3-factory/lib/create3-factory/lib/solmate/lib/ds-test/src/",
"lib/create3-factory/lib/create3-factory/lib/solmate/:ds-test/=lib/create3-factory/lib/create3-factory/lib/solmate/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/create3-factory/lib/create3-factory/:forge-std/=lib/create3-factory/lib/create3-factory/lib/forge-std/src/",
"lib/create3-factory/lib/create3-factory/:forge-std/=lib/create3-factory/lib/create3-factory/lib/forge-std/src/",
"lib/create3-factory/lib/create3-factory/:solmate/=lib/create3-factory/lib/create3-factory/lib/solmate/src/",
"lib/create3-factory/lib/create3-factory/:solmate/=lib/create3-factory/lib/create3-factory/lib/solmate/src/",
"lib/create3-factory/lib/forge-std/:ds-test/=lib/create3-factory/lib/forge-std/lib/ds-test/src/",
"lib/create3-factory/lib/forge-std/:ds-test/=lib/create3-factory/lib/forge-std/lib/ds-test/src/",
"lib/create3-factory/lib/solmate/:ds-test/=lib/create3-factory/lib/solmate/lib/ds-test/src/",
"lib/create3-factory/lib/solmate/:ds-test/=lib/create3-factory/lib/solmate/lib/ds-test/src/",
"lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/:forge-std/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/src/",
"lib/v4-core/lib/openzeppelin-contracts/:forge-std/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/src/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/create3-factory/:create3-factory/=lib/create3-factory/lib/create3-factory/",
"lib/create3-factory/:create3-factory/=lib/create3-factory/lib/create3-factory/",
"lib/create3-factory/:forge-std/=lib/create3-factory/lib/forge-std/src/",
"lib/create3-factory/:forge-std/=lib/create3-factory/lib/forge-std/src/",
"lib/create3-factory/:solmate/=lib/create3-factory/lib/solmate/src/",
"lib/create3-factory/:solmate/=lib/create3-factory/lib/solmate/src/",
"lib/morpho-blue/:forge-std/=lib/morpho-blue/lib/forge-std/src/",
"lib/morpho-blue/:forge-std/=lib/morpho-blue/lib/forge-std/src/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
"lib/openzeppelin-contracts/:forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:forge-std/=lib/v4-core/lib/forge-std/src/",
"lib/v4-core/:forge-std/=lib/v4-core/lib/forge-std/src/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"aave-v3-core/=lib/aave-v3-core/",
"create3-factory/=lib/create3-factory/",
"ds-test/=lib/create3-factory/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"morpho-blue/=lib/morpho-blue/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"prb-test/=lib/prb-test/src/",
"solady/=lib/solady/src/",
"solmate/=lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-core/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.