Verified contractPartialMIT
RobinhoodBridgeModule
Address0x07e71f5fd8ff1703ccdb55b72b6a444691012add
- 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,639
- Creation transaction
- 0x49d48f58ba…b229dd02f7
21 files
- src/modules/bridge/RobinhoodBridgeModule.solmain2.88 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/ArbitrumStackBridgeModule.sol9.29 KB
- src/modules/bridge/base/BridgeModuleBase.sol4.71 KB
- src/modules/bridge/interfaces/arbitrum/IArbitrumStackBridgeModule.sol1.92 KB
- src/modules/bridge/interfaces/arbitrum/IInbox.sol2.42 KB
- src/modules/bridge/interfaces/arbitrum/IL1GatewayRouter.sol2.33 KB
- src/modules/bridge/interfaces/robinhood/IRobinhoodBridgeModule.sol1.27 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/RobinhoodBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Contracts
import { ArbitrumStackBridgeModule } from "@modules/bridge/base/ArbitrumStackBridgeModule.sol";
// Interfaces
import { IRobinhoodBridgeModule } from "@modules/bridge/interfaces/robinhood/IRobinhoodBridgeModule.sol";
import { IModule } from "@modules/interfaces/IModule.sol";
// Libraries
import { BridgeLib } from "@modules/libraries/BridgeLib.sol";
// Types
import { BridgeContext } from "@types/BridgeContext.sol";
/// @title RobinhoodBridgeModule
/// @notice Module for bridging tokens from Ethereum to Robinhood Chain via the canonical bridge (Arbitrum Nitro
/// stack)
/// @dev Supports both ERC20 tokens (via L1GatewayRouter) and ETH (via Inbox)
contract RobinhoodBridgeModule is ArbitrumStackBridgeModule, IRobinhoodBridgeModule {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Robinhood Chain chain ID
uint256 private constant ROBINHOOD_CHAIN_ID = 4663;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Constructs the RobinhoodBridgeModule
/// @param _portikusV2 The PortikusV2 contract address
/// @param l1GatewayRouter The L1 Gateway Router address for ERC20 bridging
/// @param inbox The Delayed Inbox address for ETH bridging
constructor(
address _portikusV2,
address l1GatewayRouter,
address inbox
)
ArbitrumStackBridgeModule(
"Robinhood Bridge Module", "2.3.0", _portikusV2, l1GatewayRouter, inbox, ROBINHOOD_CHAIN_ID
)
{ }
/// @inheritdoc ArbitrumStackBridgeModule
function _bridgeProtocol() internal pure override returns (string memory) {
return "robinhood";
}
/*//////////////////////////////////////////////////////////////
EXTERNAL
//////////////////////////////////////////////////////////////*/
/// @notice Bridges tokens using Robinhood Chain's native bridge
/// @param ctx The bridge context containing all necessary bridging information
/// @return nativeFee Returns the actual native fee paid to the bridge protocol
function bridgeWithRobinhood(BridgeContext memory ctx) external payable returns (uint256 nativeFee) {
// Require bridge access authorization from settlement module
BridgeLib.consumeBridgeAuthorization();
return _bridgeInternal(ctx);
}
/// @inheritdoc IModule
function selectors() external pure override returns (bytes4[] memory moduleSelectors) {
moduleSelectors = new bytes4[](1);
moduleSelectors[0] = this.bridgeWithRobinhood.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/ArbitrumStackBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Contracts
import { BridgeModuleBase } from "@modules/bridge/base/BridgeModuleBase.sol";
// Interfaces
import { IArbitrumStackBridgeModule } from "@modules/bridge/interfaces/arbitrum/IArbitrumStackBridgeModule.sol";
import { IL1GatewayRouter } from "@modules/bridge/interfaces/arbitrum/IL1GatewayRouter.sol";
import { IInbox } from "@modules/bridge/interfaces/arbitrum/IInbox.sol";
// Libraries
import { SafeTransferLib } from "@solady/utils/SafeTransferLib.sol";
import { ERC20UtilsLib } from "@modules/libraries/ERC20UtilsLib.sol";
// Types
import { BridgeContext } from "@types/BridgeContext.sol";
/// @title Arbitrum Stack Bridge Module Base
/// @notice Base contract for Arbitrum Nitro stack bridge modules (Arbitrum One, Robinhood, etc.)
/// @dev Supports both ERC20 tokens (via L1GatewayRouter) and ETH (via Inbox retryable tickets).
/// Only supports ETH-gas Nitro chains; custom-gas-token chains (ERC20Inbox) are not supported.
abstract contract ArbitrumStackBridgeModule is BridgeModuleBase, IArbitrumStackBridgeModule {
using SafeTransferLib for address;
using ERC20UtilsLib for address;
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The L1 Gateway Router address for ERC20 bridging
IL1GatewayRouter public immutable L1_GATEWAY_ROUTER;
/// @notice The Delayed Inbox address for ETH bridging
IInbox public immutable INBOX;
/// @notice The chain ID of the destination chain the immutables point at
uint256 public immutable DEST_CHAIN_ID;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Constructor for ArbitrumStackBridgeModule
/// @param _name The module name
/// @param _version The module version
/// @param _portikusV2 The PortikusV2 contract address
/// @param _l1GatewayRouter The L1 Gateway Router address for ERC20 bridging
/// @param _inbox The Delayed Inbox address for ETH bridging
/// @param _destChainId The chain ID of the destination chain
constructor(
string memory _name,
string memory _version,
address _portikusV2,
address _l1GatewayRouter,
address _inbox,
uint256 _destChainId
)
BridgeModuleBase(_name, _version, _portikusV2)
{
L1_GATEWAY_ROUTER = IL1GatewayRouter(_l1GatewayRouter);
INBOX = IInbox(_inbox);
DEST_CHAIN_ID = _destChainId;
}
/*//////////////////////////////////////////////////////////////
VIRTUAL
//////////////////////////////////////////////////////////////*/
/// @notice The bridge protocol name for event emission (e.g., "arbitrum", "robinhood")
/// @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 FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Internal bridge implementation for Arbitrum stack chains
/// @param ctx The bridge context containing all necessary bridging information
/// @return nativeFee Returns the actual native fee paid to the bridge protocol
function _bridgeInternal(BridgeContext memory ctx) internal returns (uint256 nativeFee) {
ArbitrumBridgeData memory protocolData = _validateAndDecodeProtocolData(ctx);
// Decode bridge data and calculate capped agent fee
uint256 agentFee = _calculateCappedFee(abi.decode(ctx.bridgeData, (uint256)), protocolData.maxAgentFee);
uint256 bridgeAmount = ctx.amount - agentFee;
// Compensate agent in dest tokens for paying ETH gas fees
if (agentFee > 0) ctx.token.transferTo(msg.sender, agentFee);
// Calculate ETH value needed for gas fees
nativeFee = _calculateGasFees(protocolData);
// Handle ETH vs ERC20 bridging based on source token (what we're bridging)
if (ctx.token.isEth()) {
_bridgeETH(ctx.beneficiary, bridgeAmount, protocolData, nativeFee);
} else {
_bridgeERC20(ctx.token, ctx.beneficiary, bridgeAmount, protocolData, nativeFee);
}
// Emit the bridge event with destination-decimal output amount
emit TokensBridged(
ctx.orderHash,
ctx.beneficiary,
ctx.destChainId,
ctx.amount,
_convertToDestDecimals(bridgeAmount, ctx.scalingFactor),
_bridgeProtocol()
);
}
/// @notice Bridge ERC20 tokens via the L1 Gateway Router
/// @dev Gas fees are paid from msg.value provided by the agent
/// @param l1Token The L1 token address to bridge
/// @param beneficiary The recipient address on the destination chain
/// @param amount The amount to bridge (after agent fee)
/// @param protocolData The Arbitrum bridge data
/// @param gasFees The gas fees required for the bridge operation
function _bridgeERC20(
address l1Token,
address beneficiary,
uint256 amount,
ArbitrumBridgeData memory protocolData,
uint256 gasFees
)
internal
{
// Get the gateway for this token
address gateway = L1_GATEWAY_ROUTER.getGateway(l1Token);
if (gateway == address(0)) revert NoGatewayFound();
// Approve the gateway to spend the tokens
l1Token.safeApprove(gateway, amount);
// Encode submission cost and empty data for the user
bytes memory userEncodedData = abi.encode(protocolData.maxSubmissionCost, protocolData.extraData);
L1_GATEWAY_ROUTER.outboundTransferCustomRefund{ value: gasFees }(
l1Token, beneficiary, beneficiary, amount, protocolData.maxGas, protocolData.gasPriceBid, userEncodedData
);
}
/// @notice Bridge ETH to the destination chain via Inbox using retryable tickets
/// @dev Uses the Inbox.createRetryableTicket() for ETH bridging with custom recipient
/// @dev Agent provides ETH for both bridge amount and gas fees via msg.value
/// @param beneficiary The recipient address on the destination chain
/// @param amount The amount of ETH to bridge to the beneficiary
/// @param protocolData The Arbitrum bridge data containing gas parameters
/// @param gasFees The gas fees required for the bridge operation
function _bridgeETH(
address beneficiary,
uint256 amount,
ArbitrumBridgeData memory protocolData,
uint256 gasFees
)
internal
{
// Only forward the exact value required by the Inbox (amount + gasFees)
INBOX.createRetryableTicket{ value: amount + gasFees }(
beneficiary, // to: destination address on L2
amount, // l2CallValue: ETH amount to send to beneficiary
protocolData.maxSubmissionCost, // maxSubmissionCost: base fee for submission
beneficiary, // excessFeeRefundAddress: beneficiary gets gas refunds
beneficiary, // callValueRefundAddress: beneficiary gets ETH if ticket times out
protocolData.maxGas, // gasLimit: max gas for L2 execution
protocolData.gasPriceBid, // maxFeePerGas: gas price bid
"" // data: empty for simple ETH transfer
);
}
/// @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 Arbitrum bridge data
function _validateAndDecodeProtocolData(BridgeContext memory ctx)
internal
view
returns (ArbitrumBridgeData memory protocolData)
{
// Validate the order targets the chain this module's immutables point at
if (ctx.destChainId != DEST_CHAIN_ID) revert InvalidDestChainId();
// Validate protocol data exists
if (ctx.protocolData.length == 0) revert MissingProtocolData();
// Decode protocol data
protocolData = abi.decode(ctx.protocolData, (ArbitrumBridgeData));
// Validate gas parameters based on token type
uint256 gasLimit = ctx.token.isEth() ? 21_000 : 200_000; // 21k for ETH, 200k for ERC20
if (protocolData.maxGas < gasLimit) revert InsufficientMaxGas();
if (protocolData.gasPriceBid < 1e7) revert InvalidGasPriceBid(); // Min 0.01 gwei
}
/// @notice Calculates total gas fees required for Arbitrum retryable tickets
/// @param protocolData The Arbitrum bridge data containing gas parameters
/// @return gasFees The total gas fees (submission cost + execution gas cost)
function _calculateGasFees(ArbitrumBridgeData memory protocolData) internal pure returns (uint256 gasFees) {
return protocolData.maxSubmissionCost + (protocolData.maxGas * protocolData.gasPriceBid);
}
}
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/interfaces/arbitrum/IArbitrumStackBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
/// @title Arbitrum Stack Bridge Module Interface
/// @notice Common interface for all Arbitrum Nitro stack bridge modules (Arbitrum One, Robinhood, etc.)
/// @dev Supports both ERC20 tokens (via L1GatewayRouter) and ETH (via Inbox)
interface IArbitrumStackBridgeModule {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when max gas is too low for L2 execution (21k for ETH, 200k for ERC20)
error InsufficientMaxGas();
/// @notice Thrown when gas price bid is too low (minimum 0.01 gwei)
error InvalidGasPriceBid();
/// @notice Thrown when no gateway is found for a token
error NoGatewayFound();
/// @notice Thrown when the context destination chain ID doesn't match the chain this module bridges to
error InvalidDestChainId();
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/// @notice Protocol-controlled Arbitrum 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
struct ArbitrumBridgeData {
/// @dev Max gas deducted from user's L2 balance to cover execution
uint256 maxGas;
/// @dev Gas price for L2 execution
uint256 gasPriceBid;
/// @dev Max gas deducted for base submission fee
uint256 maxSubmissionCost;
/// @dev Optional extra data for L2 execution
bytes extraData;
/// @dev The maximum fee in order dest token that agent can set as compensation for paying for the bridge
uint256 maxAgentFee;
}
}
src/modules/bridge/interfaces/arbitrum/IInbox.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
/// @title Interface for Arbitrum's Inbox contract
/// @notice Used for depositing ETH from L1 to L2 Arbitrum
interface IInbox {
/// @notice Deposit eth from L1 to L2 to address of the sender if sender is an EOA, and to its aliased address if
/// the sender is a contract
/// @dev This does not trigger the fallback function when receiving in the L2 side.
/// Look into retryable tickets if you are interested in this functionality.
/// @dev This function should not be called inside contract constructors
/// @return The unique message number of the deposit
function depositEth() external payable returns (uint256);
/// @notice Put a message in the L2 inbox that can be reexecuted for some fixed amount of time if it reverts
/// @dev all msg.value will deposited to callValueRefundAddress on L2
/// @dev Gas limit and maxFeePerGas should not be set to 1 as that is used to trigger the RetryableData error
/// @param to destination L2 contract address
/// @param l2CallValue call value for retryable L2 message
/// @param maxSubmissionCost Max gas deducted from user's L2 balance to cover base submission fee
/// @param excessFeeRefundAddress gasLimit x maxFeePerGas - execution cost gets credited here on L2 balance. In case
/// this address is a contract, funds will be received in its alias on L2.
/// @param callValueRefundAddress l2Callvalue gets credited here on L2 if retryable txn times out or gets cancelled.
/// In case this address is a contract, funds will be received in its alias on L2.
/// @param gasLimit Max gas deducted from user's L2 balance to cover L2 execution. Should not be set to 1 (magic
/// value used to trigger the RetryableData error)
/// @param maxFeePerGas price bid for L2 execution. Should not be set to 1 (magic value used to trigger the
/// RetryableData error)
/// @param data ABI encoded data of L2 message
/// @return unique message number of the retryable transaction
function createRetryableTicket(
address to,
uint256 l2CallValue,
uint256 maxSubmissionCost,
address excessFeeRefundAddress,
address callValueRefundAddress,
uint256 gasLimit,
uint256 maxFeePerGas,
bytes calldata data
)
external
payable
returns (uint256);
}
src/modules/bridge/interfaces/arbitrum/IL1GatewayRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
/// @title Interface for Arbitrum's L1GatewayRouter
/// @notice Defines the API for routing token deposits to appropriate gateways
interface IL1GatewayRouter {
/// @notice Deposit ERC20 token from Ethereum into Arbitrum using the registered or otherwise default gateway
/// @dev Some legacy gateway might not have the outboundTransferCustomRefund method and will revert, in such case
/// use outboundTransfer instead
/// L2 address alias will not be applied to the following types of addresses on L1:
/// - an externally-owned account
/// - a contract in construction
/// - an address where a contract will be created
/// - an address where a contract lived, but was destroyed
/// @param _token L1 address of ERC20
/// @param _refundTo Account, or its L2 alias if it have code in L1, to be credited with excess gas refund in L2
/// @param _to Account to be credited with the tokens in the L2 (can be the user's L2 account or a contract), not
/// subject to L2 aliasing
/// This account, or its L2 alias if it have code in L1, will also be able to cancel the retryable
/// ticket and receive callvalue refund
/// @param _amount Token Amount
/// @param _maxGas Max gas deducted from user's L2 balance to cover L2 execution
/// @param _gasPriceBid Gas price for L2 execution
/// @param _data encoded data from router and user
/// @return res abi encoded inbox sequence number
function outboundTransferCustomRefund(
address _token,
address _refundTo,
address _to,
uint256 _amount,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes calldata _data
)
external
payable
returns (bytes memory res);
/// @notice Gets the gateway contract for a given token
/// @dev Returns the token-specific gateway if registered, otherwise returns the default gateway.
/// Returns address(0) if the gateway is disabled or not a valid contract.
/// @param _token L1 address of the token
/// @return gateway Address of the gateway contract for this token, or address(0) if no valid gateway exists
function getGateway(address _token) external view returns (address gateway);
}
src/modules/bridge/interfaces/robinhood/IRobinhoodBridgeModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
// Interfaces
import { IArbitrumStackBridgeModule } from "@modules/bridge/interfaces/arbitrum/IArbitrumStackBridgeModule.sol";
// Types
import { BridgeContext } from "@types/BridgeContext.sol";
/// @title Robinhood Bridge Module Interface
/// @notice Interface for Robinhood Chain's native bridge protocol (Arbitrum Nitro stack)
/// @dev Supports both ERC20 tokens (via L1GatewayRouter) and ETH (via Inbox)
interface IRobinhoodBridgeModule is IArbitrumStackBridgeModule {
/*//////////////////////////////////////////////////////////////
EXTERNAL
//////////////////////////////////////////////////////////////*/
/// @notice Bridges tokens using Robinhood Chain's native bridge infrastructure
/// @dev For ERC20: Uses L1GatewayRouter, agent provides ETH for gas via msg.value
/// @dev For ETH: Uses Inbox.createRetryableTicket, agent provides ETH for bridge amount + gas via msg.value
/// @param ctx The bridge context containing all necessary bridging information
/// @return nativeFee Returns the actual native fee paid to the bridge protocol
function bridgeWithRobinhood(BridgeContext memory ctx) external payable returns (uint256 nativeFee);
}
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.