Verified contractExactMIT
IntentForwarder
Address0x0852e805dda4fa6eb89da4dcff5c9d748cc95735
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- No
- EVM version
- prague
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,434,320
- Creation transaction
- 0x0d3650264f…f7ec3ed7b1
21 files
- src/intents-v2/IntentForwarder.solmain9.84 KB
- dependencies/openzeppelin-contracts-5.5.0/contracts/interfaces/IERC1967.sol637 B
- dependencies/openzeppelin-contracts-5.5.0/contracts/interfaces/draft-IERC1822.sol882 B
- dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/beacon/IBeacon.sol473 B
- dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/utils/Initializable.sol9.28 KB
- dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/utils/UUPSUpgradeable.sol6.32 KB
- dependencies/openzeppelin-contracts-5.5.0/contracts/utils/Address.sol6.8 KB
- dependencies/openzeppelin-contracts-5.5.0/contracts/utils/Errors.sol896 B
- dependencies/openzeppelin-contracts-5.5.0/contracts/utils/LowLevelCall.sol5.51 KB
- dependencies/openzeppelin-contracts-5.5.0/contracts/utils/StorageSlot.sol4.18 KB
- dependencies/wormhole-solidity-sdk-0.1.0/src/interfaces/IWormhole.sol4.24 KB
- dependencies/wormhole-solidity-sdk-0.1.0/src/libraries/BytesParsing.sol36.24 KB
- src/intents-v2/IntentCodec.sol10.93 KB
- src/intents-v2/interfaces/IIntentDispatcher.sol9.5 KB
- src/intents-v2/interfaces/IIntentForwarder.sol5.06 KB
- src/intents-v2/interfaces/IIntentResolutionReceiver.sol1.61 KB
- src/ntt/NttPayload.sol5.99 KB
- src/ntt/interfaces/INttManager.sol2.54 KB
- src/ntt/interfaces/IWormholeTransceiver.sol1.08 KB
- src/utils/hydration/HydrationConsts.sol1.16 KB
src/intents-v2/IntentForwarder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {IWormhole} from "wormhole-solidity-sdk/interfaces/IWormhole.sol";
import {INttManager} from "../ntt/interfaces/INttManager.sol";
import {IWormholeTransceiver} from "../ntt/interfaces/IWormholeTransceiver.sol";
import {NttPayload} from "../ntt/NttPayload.sol";
import {HydrationConsts} from "../utils/hydration/HydrationConsts.sol";
import {IntentCodec} from "./IntentCodec.sol";
import {IIntentForwarder} from "./interfaces/IIntentForwarder.sol";
/// @title IntentForwarder — Ethereum end of intents v2
/// @notice One call carries an order the last hop it takes on our side:
///
/// 1. READ — the settlement must be the dispatcher's transfer to this contract, and its
/// payload the forwarding instruction.
/// 2. DELIVER — submit the NTT VAA, releasing native ETH here.
/// 3. FORWARD — pay the caller its fee, send the rest to the payload's depositAddress.
///
/// Atomic, so whoever calls it did all of it and is the one paid. NTT's delivery is
/// permissionless, so a settlement may already be here; that skips step 2 rather than failing.
///
/// @dev Nothing is caller-supplied. The destination and the fee ceiling ride in the transfer's
/// payload, which NTT attests with the transfer itself; only a transfer the pinned dispatcher
/// sent is an order, and the amount comes from the settlement. The manager executing the
/// message is what proves it — it only executes its registered Hydration peer's messages.
contract IntentForwarder is Initializable, UUPSUpgradeable, IIntentForwarder {
using NttPayload for bytes;
/// @notice The longest head start the owner can give authorized relayers — past it, anyone can
/// process, so liveness never waits on them for longer.
uint256 internal constant MAX_EXCLUSIVE_WINDOW = 1 days;
/// @notice What NTT trims WETH to — `min(8, srcDp, dstDp)` with 18 decimals on both sides.
uint8 internal constant NTT_DECIMALS = 8;
/// @notice Scales a trimmed amount back to the 18-decimal native ETH the rail delivers.
uint256 internal constant TRIM_UNIT = 1e10;
address public owner;
IWormhole public wormhole;
IWormholeTransceiver public transceiver;
/// @notice The Hydration IntentDispatcher, as a Wormhole universal address — the only sender
/// whose transfers are orders.
bytes32 public dispatcher;
/// @notice Settlements already forwarded, by NTT message digest.
mapping(bytes32 => bool) public processed;
/// @notice Relayers that may process inside `exclusiveWindow`. Empty means permissionless always.
mapping(address => bool) public authorizedRelayer;
uint256 public authorizedRelayerCount;
/// @notice Head start for authorized relayers, in seconds from the settlement VAA's timestamp.
/// Long enough to outlast a gas spike: past it, anyone can process and claim the whole
/// ceiling, where an authorized relayer claims the measured cost.
uint256 public exclusiveWindow;
modifier onlyOwner() {
_onlyOwner();
_;
}
function _onlyOwner() internal view {
if (msg.sender != owner) revert NotOwner();
}
constructor() {
_disableInitializers();
}
function initialize(address _wormhole, address _transceiver) public initializer {
owner = msg.sender;
wormhole = IWormhole(_wormhole);
transceiver = IWormholeTransceiver(_transceiver);
exclusiveWindow = 1 hours;
}
/// @notice Accept settlements.
receive() external payable {}
// ─── Core ────────────────────────────────────────────────────
/// @inheritdoc IIntentForwarder
function processOrder(bytes calldata nttVaa, uint256 feeRequested) external {
if (dispatcher == bytes32(0)) revert NotConfigured();
IWormhole.VM memory settlement = wormhole.parseVM(nttVaa);
NttPayload.Transfer memory transfer = _requireOrder(settlement);
(address depositAddress, uint256 maxRelayFee) = IntentCodec.decodeForward(transfer.additionalPayload);
if (feeRequested > maxRelayFee) revert FeeExceedsCeiling();
bytes32 digest = keccak256(abi.encodePacked(settlement.emitterChainId, transfer.message));
if (processed[digest]) revert AlreadyRedeemed();
processed[digest] = true;
// Skipped when a generic NTT relayer already delivered.
if (!transceiver.isVAAConsumed(settlement.hash)) {
transceiver.receiveMessage(nttVaa);
}
// Delivered is not released.
_requireReleased(digest, transfer.sequence);
// Below the proof, not above it: only now is the settlement's timestamp trustworthy.
_requireCallerMayProcess(settlement.timestamp);
uint256 forwardAmount = uint256(transfer.amount) * TRIM_UNIT - feeRequested;
_pay(depositAddress, forwardAmount);
emit OrderForwarded(transfer.sequence, depositAddress, forwardAmount);
if (feeRequested > 0) {
_pay(msg.sender, feeRequested);
emit RelayFeePaid(transfer.sequence, msg.sender, feeRequested);
}
}
// ─── Helpers ─────────────────────────────────────────────────
/// @dev Read the settlement and reject it before anything is delivered: from Hydration, sent by
/// the dispatcher, to this contract, at the rail's precision.
/// @param settlement The NTT VAA — parsed, not verified; delivery proves it.
function _requireOrder(IWormhole.VM memory settlement)
private
view
returns (NttPayload.Transfer memory transfer)
{
if (settlement.emitterChainId != HydrationConsts.WORMHOLE_CHAIN_ID) {
revert UnexpectedSourceChain(settlement.emitterChainId);
}
transfer = settlement.payload.transferOf();
if (transfer.sender != dispatcher) revert UnauthorizedSender(transfer.sender);
if (transfer.to != bytes32(uint256(uint160(address(this))))) revert WrongRecipient(transfer.to);
if (transfer.decimals != NTT_DECIMALS) revert UnexpectedTrim(transfer.decimals);
}
/// @dev The VAA is public once signed and this pays msg.sender, so anyone can rebuild the call —
/// or copy a pending one out of the mempool. The window makes that unprofitable without
/// making delivery depend on us: it expires, and an empty allowlist disables it entirely.
/// @param timestamp The settlement's, trustworthy only after the settlement is proven — it is
/// parsed unverified.
function _requireCallerMayProcess(uint32 timestamp) private view {
if (authorizedRelayerCount == 0 || authorizedRelayer[msg.sender]) return;
if (block.timestamp < uint256(timestamp) + exclusiveWindow) revert Unauthorized();
}
/// @dev Assert the settlement's funds landed here, rather than inferring it from delivery: the
/// manager marks a message executed before the inbound rate limiter runs, and a queued
/// transfer releases nothing until someone completes it.
function _requireReleased(bytes32 digest, uint64 sequence) private view {
INttManager manager = INttManager(transceiver.nttManager());
if (!manager.isMessageExecuted(digest) || manager.getInboundQueuedTransfer(digest).txTimestamp != 0) {
revert SettlementNotReleased(sequence);
}
}
/// @dev Everything this contract moves is native ETH.
function _pay(address to, uint256 amount) private {
(bool ok,) = to.call{value: amount}("");
if (!ok) revert NativeTransferFailed();
}
// ─── Upgrade ─────────────────────────────────────────────────
function _authorizeUpgrade(address) internal view override onlyOwner {}
// ─── Admin ───────────────────────────────────────────────────
function setOwner(address newOwner) external onlyOwner {
owner = newOwner;
}
/// @notice Pin the dispatcher whose transfers are orders.
function setDispatcher(bytes32 _dispatcher) external onlyOwner {
dispatcher = _dispatcher;
emit DispatcherUpdated(_dispatcher);
}
/// @notice Grant or revoke exclusive-window access. The first grant turns the window on for
/// everyone else; revoking the last turns it off again.
function setAuthorizedRelayer(address relayer, bool enabled) external onlyOwner {
if (authorizedRelayer[relayer] == enabled) return;
authorizedRelayer[relayer] = enabled;
enabled ? authorizedRelayerCount++ : authorizedRelayerCount--;
emit RelayerAuthorized(relayer, enabled);
}
/// @notice Set the authorized relayers' head start, at most MAX_EXCLUSIVE_WINDOW.
function setExclusiveWindow(uint256 window) external onlyOwner {
if (window > MAX_EXCLUSIVE_WINDOW) revert InvalidExclusiveWindow(window);
exclusiveWindow = window;
emit ExclusiveWindowSet(window);
}
/// @notice Emergency withdrawal.
function sweep(address to, uint256 amount) external onlyOwner {
_pay(to, amount);
emit Swept(to, amount);
}
}
dependencies/openzeppelin-contracts-5.5.0/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
dependencies/openzeppelin-contracts-5.5.0/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
dependencies/openzeppelin-contracts-5.5.0/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* @custom:stateless
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
dependencies/openzeppelin-contracts-5.5.0/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.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);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
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 = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @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 = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @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 = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @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.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
// 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 (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @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) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
dependencies/openzeppelin-contracts-5.5.0/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
dependencies/openzeppelin-contracts-5.5.0/contracts/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
dependencies/openzeppelin-contracts-5.5.0/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
dependencies/wormhole-solidity-sdk-0.1.0/src/interfaces/IWormhole.sol
// contracts/Messages.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
interface IWormhole {
struct GuardianSet {
address[] keys;
uint32 expirationTime;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
uint8 guardianIndex;
}
struct VM {
uint8 version;
uint32 timestamp;
uint32 nonce;
uint16 emitterChainId;
bytes32 emitterAddress;
uint64 sequence;
uint8 consistencyLevel;
bytes payload;
uint32 guardianSetIndex;
Signature[] signatures;
bytes32 hash;
}
struct ContractUpgrade {
bytes32 module;
uint8 action;
uint16 chain;
address newContract;
}
struct GuardianSetUpgrade {
bytes32 module;
uint8 action;
uint16 chain;
GuardianSet newGuardianSet;
uint32 newGuardianSetIndex;
}
struct SetMessageFee {
bytes32 module;
uint8 action;
uint16 chain;
uint256 messageFee;
}
struct TransferFees {
bytes32 module;
uint8 action;
uint16 chain;
uint256 amount;
bytes32 recipient;
}
struct RecoverChainId {
bytes32 module;
uint8 action;
uint256 evmChainId;
uint16 newChainId;
}
event LogMessagePublished(
address indexed sender, uint64 sequence, uint32 nonce, bytes payload, uint8 consistencyLevel
);
event ContractUpgraded(address indexed oldContract, address indexed newContract);
event GuardianSetAdded(uint32 indexed index);
function publishMessage(uint32 nonce, bytes memory payload, uint8 consistencyLevel)
external
payable
returns (uint64 sequence);
function initialize() external;
function parseAndVerifyVM(bytes calldata encodedVM)
external
view
returns (VM memory vm, bool valid, string memory reason);
function verifyVM(VM memory vm) external view returns (bool valid, string memory reason);
function verifySignatures(bytes32 hash, Signature[] memory signatures, GuardianSet memory guardianSet)
external
pure
returns (bool valid, string memory reason);
function parseVM(bytes memory encodedVM) external pure returns (VM memory vm);
function quorum(uint256 numGuardians) external pure returns (uint256 numSignaturesRequiredForQuorum);
function getGuardianSet(uint32 index) external view returns (GuardianSet memory);
function getCurrentGuardianSetIndex() external view returns (uint32);
function getGuardianSetExpiry() external view returns (uint32);
function governanceActionIsConsumed(bytes32 hash) external view returns (bool);
function isInitialized(address impl) external view returns (bool);
function chainId() external view returns (uint16);
function isFork() external view returns (bool);
function governanceChainId() external view returns (uint16);
function governanceContract() external view returns (bytes32);
function messageFee() external view returns (uint256);
function evmChainId() external view returns (uint256);
function nextSequence(address emitter) external view returns (uint64);
function parseContractUpgrade(bytes memory encodedUpgrade) external pure returns (ContractUpgrade memory cu);
function parseGuardianSetUpgrade(bytes memory encodedUpgrade)
external
pure
returns (GuardianSetUpgrade memory gsu);
function parseSetMessageFee(bytes memory encodedSetMessageFee) external pure returns (SetMessageFee memory smf);
function parseTransferFees(bytes memory encodedTransferFees) external pure returns (TransferFees memory tf);
function parseRecoverChainId(bytes memory encodedRecoverChainId)
external
pure
returns (RecoverChainId memory rci);
function submitContractUpgrade(bytes memory _vm) external;
function submitSetMessageFee(bytes memory _vm) external;
function submitNewGuardianSet(bytes memory _vm) external;
function submitTransferFees(bytes memory _vm) external;
function submitRecoverChainId(bytes memory _vm) external;
}
dependencies/wormhole-solidity-sdk-0.1.0/src/libraries/BytesParsing.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.13;
library BytesParsing {
uint256 private constant freeMemoryPtr = 0x40;
uint256 private constant wordSize = 32;
error OutOfBounds(uint256 offset, uint256 length);
error LengthMismatch(uint256 encodedLength, uint256 expectedLength);
error InvalidBoolVal(uint8 val);
function checkBound(uint offset, uint length) internal pure {
if (offset > length)
revert OutOfBounds(offset, length);
}
function checkLength(bytes memory encoded, uint256 expected) internal pure {
if (encoded.length != expected)
revert LengthMismatch(encoded.length, expected);
}
function sliceUnchecked(
bytes memory encoded,
uint offset,
uint length
) internal pure returns (bytes memory ret, uint nextOffset) {
//bail early for degenerate case
if (length == 0)
return (new bytes(0), offset);
assembly ("memory-safe") {
nextOffset := add(offset, length)
ret := mload(freeMemoryPtr)
//Explanation on how we copy data here:
// The bytes type has the following layout in memory:
// [length: 32 bytes, data: length bytes]
// So if we allocate `bytes memory foo = new bytes(1);` then `foo` will be a pointer to 33
// bytes where the first 32 bytes contain the length and the last byte is the actual data.
// Since mload always loads 32 bytes of memory at once, we use our shift variable to align
// our reads so that our last read lines up exactly with the last 32 bytes of `encoded`.
// However this also means that if the length of `encoded` is not a multiple of 32 bytes, our
// first read will necessarily partly contain bytes from `encoded`'s 32 length bytes that
// will be written into the length part of our `ret` slice.
// We remedy this issue by writing the length of our `ret` slice at the end, thus
// overwritting those garbage bytes.
let shift := and(length, 31) //equivalent to `mod(length, 32)` but 2 gas cheaper
if iszero(shift) {
shift := wordSize
}
let dest := add(ret, shift)
let end := add(dest, length)
for {
let src := add(add(encoded, shift), offset)
} lt(dest, end) {
src := add(src, wordSize)
dest := add(dest, wordSize)
} {
mstore(dest, mload(src))
}
mstore(ret, length)
//When compiling with --via-ir then normally allocated memory (i.e. via new) will have 32 byte
// memory alignment and so we enforce the same memory alignment here.
mstore(freeMemoryPtr, and(add(dest, 31), not(31)))
}
}
function slice(
bytes memory encoded,
uint offset,
uint length
) internal pure returns (bytes memory ret, uint nextOffset) {
(ret, nextOffset) = sliceUnchecked(encoded, offset, length);
checkBound(nextOffset, encoded.length);
}
function asAddressUnchecked(
bytes memory encoded,
uint offset
) internal pure returns (address, uint) {
(uint160 ret, uint nextOffset) = asUint160Unchecked(encoded, offset);
return (address(ret), nextOffset);
}
function asAddress(
bytes memory encoded,
uint offset
) internal pure returns (address ret, uint nextOffset) {
(ret, nextOffset) = asAddressUnchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBoolUnchecked(
bytes memory encoded,
uint offset
) internal pure returns (bool, uint) {
(uint8 val, uint nextOffset) = asUint8Unchecked(encoded, offset);
if (val & 0xfe != 0)
revert InvalidBoolVal(val);
uint cleanedVal = uint(val);
bool ret;
//skip 2x iszero opcode
assembly ("memory-safe") {
ret := cleanedVal
}
return (ret, nextOffset);
}
function asBool(
bytes memory encoded,
uint offset
) internal pure returns (bool ret, uint nextOffset) {
(ret, nextOffset) = asBoolUnchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
/* -------------------------------------------------------------------------------------------------
Remaining library code below was auto-generated by via the following js/node code:
for (let bytes = 1; bytes <= 32; ++bytes) {
const bits = bytes*8;
console.log(
`function asUint${bits}Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint${bits} ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, ${bytes})
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint${bits}(
bytes memory encoded,
uint offset
) internal pure returns (uint${bits} ret, uint nextOffset) {
(ret, nextOffset) = asUint${bits}Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes${bytes}Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes${bytes}, uint) {
(uint${bits} ret, uint nextOffset) = asUint${bits}Unchecked(encoded, offset);
return (bytes${bytes}(ret), nextOffset);
}
function asBytes${bytes}(
bytes memory encoded,
uint offset
) internal pure returns (bytes${bytes}, uint) {
(uint${bits} ret, uint nextOffset) = asUint${bits}(encoded, offset);
return (bytes${bytes}(ret), nextOffset);
}
`
);
}
------------------------------------------------------------------------------------------------- */
function asUint8Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint8 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 1)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint8(
bytes memory encoded,
uint offset
) internal pure returns (uint8 ret, uint nextOffset) {
(ret, nextOffset) = asUint8Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes1Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes1, uint) {
(uint8 ret, uint nextOffset) = asUint8Unchecked(encoded, offset);
return (bytes1(ret), nextOffset);
}
function asBytes1(
bytes memory encoded,
uint offset
) internal pure returns (bytes1, uint) {
(uint8 ret, uint nextOffset) = asUint8(encoded, offset);
return (bytes1(ret), nextOffset);
}
function asUint16Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint16 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 2)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint16(
bytes memory encoded,
uint offset
) internal pure returns (uint16 ret, uint nextOffset) {
(ret, nextOffset) = asUint16Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes2Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes2, uint) {
(uint16 ret, uint nextOffset) = asUint16Unchecked(encoded, offset);
return (bytes2(ret), nextOffset);
}
function asBytes2(
bytes memory encoded,
uint offset
) internal pure returns (bytes2, uint) {
(uint16 ret, uint nextOffset) = asUint16(encoded, offset);
return (bytes2(ret), nextOffset);
}
function asUint24Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint24 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 3)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint24(
bytes memory encoded,
uint offset
) internal pure returns (uint24 ret, uint nextOffset) {
(ret, nextOffset) = asUint24Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes3Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes3, uint) {
(uint24 ret, uint nextOffset) = asUint24Unchecked(encoded, offset);
return (bytes3(ret), nextOffset);
}
function asBytes3(
bytes memory encoded,
uint offset
) internal pure returns (bytes3, uint) {
(uint24 ret, uint nextOffset) = asUint24(encoded, offset);
return (bytes3(ret), nextOffset);
}
function asUint32Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint32 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 4)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint32(
bytes memory encoded,
uint offset
) internal pure returns (uint32 ret, uint nextOffset) {
(ret, nextOffset) = asUint32Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes4Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes4, uint) {
(uint32 ret, uint nextOffset) = asUint32Unchecked(encoded, offset);
return (bytes4(ret), nextOffset);
}
function asBytes4(
bytes memory encoded,
uint offset
) internal pure returns (bytes4, uint) {
(uint32 ret, uint nextOffset) = asUint32(encoded, offset);
return (bytes4(ret), nextOffset);
}
function asUint40Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint40 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 5)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint40(
bytes memory encoded,
uint offset
) internal pure returns (uint40 ret, uint nextOffset) {
(ret, nextOffset) = asUint40Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes5Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes5, uint) {
(uint40 ret, uint nextOffset) = asUint40Unchecked(encoded, offset);
return (bytes5(ret), nextOffset);
}
function asBytes5(
bytes memory encoded,
uint offset
) internal pure returns (bytes5, uint) {
(uint40 ret, uint nextOffset) = asUint40(encoded, offset);
return (bytes5(ret), nextOffset);
}
function asUint48Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint48 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 6)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint48(
bytes memory encoded,
uint offset
) internal pure returns (uint48 ret, uint nextOffset) {
(ret, nextOffset) = asUint48Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes6Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes6, uint) {
(uint48 ret, uint nextOffset) = asUint48Unchecked(encoded, offset);
return (bytes6(ret), nextOffset);
}
function asBytes6(
bytes memory encoded,
uint offset
) internal pure returns (bytes6, uint) {
(uint48 ret, uint nextOffset) = asUint48(encoded, offset);
return (bytes6(ret), nextOffset);
}
function asUint56Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint56 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 7)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint56(
bytes memory encoded,
uint offset
) internal pure returns (uint56 ret, uint nextOffset) {
(ret, nextOffset) = asUint56Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes7Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes7, uint) {
(uint56 ret, uint nextOffset) = asUint56Unchecked(encoded, offset);
return (bytes7(ret), nextOffset);
}
function asBytes7(
bytes memory encoded,
uint offset
) internal pure returns (bytes7, uint) {
(uint56 ret, uint nextOffset) = asUint56(encoded, offset);
return (bytes7(ret), nextOffset);
}
function asUint64Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint64 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 8)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint64(
bytes memory encoded,
uint offset
) internal pure returns (uint64 ret, uint nextOffset) {
(ret, nextOffset) = asUint64Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes8Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes8, uint) {
(uint64 ret, uint nextOffset) = asUint64Unchecked(encoded, offset);
return (bytes8(ret), nextOffset);
}
function asBytes8(
bytes memory encoded,
uint offset
) internal pure returns (bytes8, uint) {
(uint64 ret, uint nextOffset) = asUint64(encoded, offset);
return (bytes8(ret), nextOffset);
}
function asUint72Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint72 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 9)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint72(
bytes memory encoded,
uint offset
) internal pure returns (uint72 ret, uint nextOffset) {
(ret, nextOffset) = asUint72Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes9Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes9, uint) {
(uint72 ret, uint nextOffset) = asUint72Unchecked(encoded, offset);
return (bytes9(ret), nextOffset);
}
function asBytes9(
bytes memory encoded,
uint offset
) internal pure returns (bytes9, uint) {
(uint72 ret, uint nextOffset) = asUint72(encoded, offset);
return (bytes9(ret), nextOffset);
}
function asUint80Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint80 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 10)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint80(
bytes memory encoded,
uint offset
) internal pure returns (uint80 ret, uint nextOffset) {
(ret, nextOffset) = asUint80Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes10Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes10, uint) {
(uint80 ret, uint nextOffset) = asUint80Unchecked(encoded, offset);
return (bytes10(ret), nextOffset);
}
function asBytes10(
bytes memory encoded,
uint offset
) internal pure returns (bytes10, uint) {
(uint80 ret, uint nextOffset) = asUint80(encoded, offset);
return (bytes10(ret), nextOffset);
}
function asUint88Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint88 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 11)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint88(
bytes memory encoded,
uint offset
) internal pure returns (uint88 ret, uint nextOffset) {
(ret, nextOffset) = asUint88Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes11Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes11, uint) {
(uint88 ret, uint nextOffset) = asUint88Unchecked(encoded, offset);
return (bytes11(ret), nextOffset);
}
function asBytes11(
bytes memory encoded,
uint offset
) internal pure returns (bytes11, uint) {
(uint88 ret, uint nextOffset) = asUint88(encoded, offset);
return (bytes11(ret), nextOffset);
}
function asUint96Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint96 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 12)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint96(
bytes memory encoded,
uint offset
) internal pure returns (uint96 ret, uint nextOffset) {
(ret, nextOffset) = asUint96Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes12Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes12, uint) {
(uint96 ret, uint nextOffset) = asUint96Unchecked(encoded, offset);
return (bytes12(ret), nextOffset);
}
function asBytes12(
bytes memory encoded,
uint offset
) internal pure returns (bytes12, uint) {
(uint96 ret, uint nextOffset) = asUint96(encoded, offset);
return (bytes12(ret), nextOffset);
}
function asUint104Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint104 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 13)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint104(
bytes memory encoded,
uint offset
) internal pure returns (uint104 ret, uint nextOffset) {
(ret, nextOffset) = asUint104Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes13Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes13, uint) {
(uint104 ret, uint nextOffset) = asUint104Unchecked(encoded, offset);
return (bytes13(ret), nextOffset);
}
function asBytes13(
bytes memory encoded,
uint offset
) internal pure returns (bytes13, uint) {
(uint104 ret, uint nextOffset) = asUint104(encoded, offset);
return (bytes13(ret), nextOffset);
}
function asUint112Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint112 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 14)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint112(
bytes memory encoded,
uint offset
) internal pure returns (uint112 ret, uint nextOffset) {
(ret, nextOffset) = asUint112Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes14Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes14, uint) {
(uint112 ret, uint nextOffset) = asUint112Unchecked(encoded, offset);
return (bytes14(ret), nextOffset);
}
function asBytes14(
bytes memory encoded,
uint offset
) internal pure returns (bytes14, uint) {
(uint112 ret, uint nextOffset) = asUint112(encoded, offset);
return (bytes14(ret), nextOffset);
}
function asUint120Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint120 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 15)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint120(
bytes memory encoded,
uint offset
) internal pure returns (uint120 ret, uint nextOffset) {
(ret, nextOffset) = asUint120Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes15Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes15, uint) {
(uint120 ret, uint nextOffset) = asUint120Unchecked(encoded, offset);
return (bytes15(ret), nextOffset);
}
function asBytes15(
bytes memory encoded,
uint offset
) internal pure returns (bytes15, uint) {
(uint120 ret, uint nextOffset) = asUint120(encoded, offset);
return (bytes15(ret), nextOffset);
}
function asUint128Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint128 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 16)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint128(
bytes memory encoded,
uint offset
) internal pure returns (uint128 ret, uint nextOffset) {
(ret, nextOffset) = asUint128Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes16Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes16, uint) {
(uint128 ret, uint nextOffset) = asUint128Unchecked(encoded, offset);
return (bytes16(ret), nextOffset);
}
function asBytes16(
bytes memory encoded,
uint offset
) internal pure returns (bytes16, uint) {
(uint128 ret, uint nextOffset) = asUint128(encoded, offset);
return (bytes16(ret), nextOffset);
}
function asUint136Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint136 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 17)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint136(
bytes memory encoded,
uint offset
) internal pure returns (uint136 ret, uint nextOffset) {
(ret, nextOffset) = asUint136Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes17Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes17, uint) {
(uint136 ret, uint nextOffset) = asUint136Unchecked(encoded, offset);
return (bytes17(ret), nextOffset);
}
function asBytes17(
bytes memory encoded,
uint offset
) internal pure returns (bytes17, uint) {
(uint136 ret, uint nextOffset) = asUint136(encoded, offset);
return (bytes17(ret), nextOffset);
}
function asUint144Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint144 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 18)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint144(
bytes memory encoded,
uint offset
) internal pure returns (uint144 ret, uint nextOffset) {
(ret, nextOffset) = asUint144Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes18Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes18, uint) {
(uint144 ret, uint nextOffset) = asUint144Unchecked(encoded, offset);
return (bytes18(ret), nextOffset);
}
function asBytes18(
bytes memory encoded,
uint offset
) internal pure returns (bytes18, uint) {
(uint144 ret, uint nextOffset) = asUint144(encoded, offset);
return (bytes18(ret), nextOffset);
}
function asUint152Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint152 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 19)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint152(
bytes memory encoded,
uint offset
) internal pure returns (uint152 ret, uint nextOffset) {
(ret, nextOffset) = asUint152Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes19Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes19, uint) {
(uint152 ret, uint nextOffset) = asUint152Unchecked(encoded, offset);
return (bytes19(ret), nextOffset);
}
function asBytes19(
bytes memory encoded,
uint offset
) internal pure returns (bytes19, uint) {
(uint152 ret, uint nextOffset) = asUint152(encoded, offset);
return (bytes19(ret), nextOffset);
}
function asUint160Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint160 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 20)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint160(
bytes memory encoded,
uint offset
) internal pure returns (uint160 ret, uint nextOffset) {
(ret, nextOffset) = asUint160Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes20Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes20, uint) {
(uint160 ret, uint nextOffset) = asUint160Unchecked(encoded, offset);
return (bytes20(ret), nextOffset);
}
function asBytes20(
bytes memory encoded,
uint offset
) internal pure returns (bytes20, uint) {
(uint160 ret, uint nextOffset) = asUint160(encoded, offset);
return (bytes20(ret), nextOffset);
}
function asUint168Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint168 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 21)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint168(
bytes memory encoded,
uint offset
) internal pure returns (uint168 ret, uint nextOffset) {
(ret, nextOffset) = asUint168Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes21Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes21, uint) {
(uint168 ret, uint nextOffset) = asUint168Unchecked(encoded, offset);
return (bytes21(ret), nextOffset);
}
function asBytes21(
bytes memory encoded,
uint offset
) internal pure returns (bytes21, uint) {
(uint168 ret, uint nextOffset) = asUint168(encoded, offset);
return (bytes21(ret), nextOffset);
}
function asUint176Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint176 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 22)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint176(
bytes memory encoded,
uint offset
) internal pure returns (uint176 ret, uint nextOffset) {
(ret, nextOffset) = asUint176Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes22Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes22, uint) {
(uint176 ret, uint nextOffset) = asUint176Unchecked(encoded, offset);
return (bytes22(ret), nextOffset);
}
function asBytes22(
bytes memory encoded,
uint offset
) internal pure returns (bytes22, uint) {
(uint176 ret, uint nextOffset) = asUint176(encoded, offset);
return (bytes22(ret), nextOffset);
}
function asUint184Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint184 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 23)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint184(
bytes memory encoded,
uint offset
) internal pure returns (uint184 ret, uint nextOffset) {
(ret, nextOffset) = asUint184Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes23Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes23, uint) {
(uint184 ret, uint nextOffset) = asUint184Unchecked(encoded, offset);
return (bytes23(ret), nextOffset);
}
function asBytes23(
bytes memory encoded,
uint offset
) internal pure returns (bytes23, uint) {
(uint184 ret, uint nextOffset) = asUint184(encoded, offset);
return (bytes23(ret), nextOffset);
}
function asUint192Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint192 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 24)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint192(
bytes memory encoded,
uint offset
) internal pure returns (uint192 ret, uint nextOffset) {
(ret, nextOffset) = asUint192Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes24Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes24, uint) {
(uint192 ret, uint nextOffset) = asUint192Unchecked(encoded, offset);
return (bytes24(ret), nextOffset);
}
function asBytes24(
bytes memory encoded,
uint offset
) internal pure returns (bytes24, uint) {
(uint192 ret, uint nextOffset) = asUint192(encoded, offset);
return (bytes24(ret), nextOffset);
}
function asUint200Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint200 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 25)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint200(
bytes memory encoded,
uint offset
) internal pure returns (uint200 ret, uint nextOffset) {
(ret, nextOffset) = asUint200Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes25Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes25, uint) {
(uint200 ret, uint nextOffset) = asUint200Unchecked(encoded, offset);
return (bytes25(ret), nextOffset);
}
function asBytes25(
bytes memory encoded,
uint offset
) internal pure returns (bytes25, uint) {
(uint200 ret, uint nextOffset) = asUint200(encoded, offset);
return (bytes25(ret), nextOffset);
}
function asUint208Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint208 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 26)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint208(
bytes memory encoded,
uint offset
) internal pure returns (uint208 ret, uint nextOffset) {
(ret, nextOffset) = asUint208Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes26Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes26, uint) {
(uint208 ret, uint nextOffset) = asUint208Unchecked(encoded, offset);
return (bytes26(ret), nextOffset);
}
function asBytes26(
bytes memory encoded,
uint offset
) internal pure returns (bytes26, uint) {
(uint208 ret, uint nextOffset) = asUint208(encoded, offset);
return (bytes26(ret), nextOffset);
}
function asUint216Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint216 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 27)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint216(
bytes memory encoded,
uint offset
) internal pure returns (uint216 ret, uint nextOffset) {
(ret, nextOffset) = asUint216Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes27Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes27, uint) {
(uint216 ret, uint nextOffset) = asUint216Unchecked(encoded, offset);
return (bytes27(ret), nextOffset);
}
function asBytes27(
bytes memory encoded,
uint offset
) internal pure returns (bytes27, uint) {
(uint216 ret, uint nextOffset) = asUint216(encoded, offset);
return (bytes27(ret), nextOffset);
}
function asUint224Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint224 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 28)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint224(
bytes memory encoded,
uint offset
) internal pure returns (uint224 ret, uint nextOffset) {
(ret, nextOffset) = asUint224Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes28Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes28, uint) {
(uint224 ret, uint nextOffset) = asUint224Unchecked(encoded, offset);
return (bytes28(ret), nextOffset);
}
function asBytes28(
bytes memory encoded,
uint offset
) internal pure returns (bytes28, uint) {
(uint224 ret, uint nextOffset) = asUint224(encoded, offset);
return (bytes28(ret), nextOffset);
}
function asUint232Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint232 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 29)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint232(
bytes memory encoded,
uint offset
) internal pure returns (uint232 ret, uint nextOffset) {
(ret, nextOffset) = asUint232Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes29Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes29, uint) {
(uint232 ret, uint nextOffset) = asUint232Unchecked(encoded, offset);
return (bytes29(ret), nextOffset);
}
function asBytes29(
bytes memory encoded,
uint offset
) internal pure returns (bytes29, uint) {
(uint232 ret, uint nextOffset) = asUint232(encoded, offset);
return (bytes29(ret), nextOffset);
}
function asUint240Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint240 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 30)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint240(
bytes memory encoded,
uint offset
) internal pure returns (uint240 ret, uint nextOffset) {
(ret, nextOffset) = asUint240Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes30Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes30, uint) {
(uint240 ret, uint nextOffset) = asUint240Unchecked(encoded, offset);
return (bytes30(ret), nextOffset);
}
function asBytes30(
bytes memory encoded,
uint offset
) internal pure returns (bytes30, uint) {
(uint240 ret, uint nextOffset) = asUint240(encoded, offset);
return (bytes30(ret), nextOffset);
}
function asUint248Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint248 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 31)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint248(
bytes memory encoded,
uint offset
) internal pure returns (uint248 ret, uint nextOffset) {
(ret, nextOffset) = asUint248Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes31Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes31, uint) {
(uint248 ret, uint nextOffset) = asUint248Unchecked(encoded, offset);
return (bytes31(ret), nextOffset);
}
function asBytes31(
bytes memory encoded,
uint offset
) internal pure returns (bytes31, uint) {
(uint248 ret, uint nextOffset) = asUint248(encoded, offset);
return (bytes31(ret), nextOffset);
}
function asUint256Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (uint256 ret, uint nextOffset) {
assembly ("memory-safe") {
nextOffset := add(offset, 32)
ret := mload(add(encoded, nextOffset))
}
return (ret, nextOffset);
}
function asUint256(
bytes memory encoded,
uint offset
) internal pure returns (uint256 ret, uint nextOffset) {
(ret, nextOffset) = asUint256Unchecked(encoded, offset);
checkBound(nextOffset, encoded.length);
}
function asBytes32Unchecked(
bytes memory encoded,
uint offset
) internal pure returns (bytes32, uint) {
(uint256 ret, uint nextOffset) = asUint256Unchecked(encoded, offset);
return (bytes32(ret), nextOffset);
}
function asBytes32(
bytes memory encoded,
uint offset
) internal pure returns (bytes32, uint) {
(uint256 ret, uint nextOffset) = asUint256(encoded, offset);
return (bytes32(ret), nextOffset);
}
}
src/intents-v2/IntentCodec.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import {IIntentDispatcher} from "./interfaces/IIntentDispatcher.sol";
/// @title IntentCodec — the terms, order and forward wire formats
/// @notice Packed big-endian, because the decoder is Rust (crates/near/contracts/intent-router,
/// `terms.rs` and `order.rs`). Checks mirror the router's parser exactly: terms this encoder
/// accepts must parse there, or their account could not even refund. Layouts and rationale:
/// docs/intents-v2/schema.md §2–3.
///
/// Terms:
/// offset size field offset size field
/// 0 1 version 88 8 deadline
/// 1 20 owner 96 1 recipientKind
/// 21 32 quoteId 97 20 refundTo
/// 53 2 maxSlippageBps 117 1 destAssetLen (D)
/// 55 1 maxFillMultiplier 118 D destinationAsset
/// 56 16 minOutPerIn 118+D 1 recipientLen (R)
/// 72 16 minDelivery 119+D R recipient total 119 + D + R
///
/// Order message: msgType 1 | authPath 32 | seq 8 | amount 16 | outPerIn 16 — 73 bytes.
///
/// Forward payload, in the NTT transfer's `additionalPayload`:
/// version 1 | depositAddress 20 | maxRelayFee 16 — 37 bytes.
library IntentCodec {
/// @notice The limit swap — the only strategy. Inside the hash, so a future layout derives
/// disjoint accounts.
uint8 internal constant VERSION = 1;
/// @notice `recipient` is an address on the destination chain; the router withdraws through POA.
uint8 internal constant KIND_WITHDRAW = 0;
/// @notice `recipient` is a NEAR intents account; the funds stay on NEAR.
uint8 internal constant KIND_INTENTS_ACCOUNT = 1;
/// @notice Basis points in 1.
uint16 internal constant BPS = 10_000;
/// @notice The fill-multiplier bounds — the router's `MIN_FILL_MULTIPLIER` / `MAX_FILL_MULTIPLIER`. At
/// least 2: an order's own ETH reaches up to twice its amount, which is net of a relay
/// ceiling of at most half.
uint8 internal constant MIN_FILL_MULTIPLIER = 2;
uint8 internal constant MAX_FILL_MULTIPLIER = 100;
/// @notice The order message's type byte.
uint8 internal constant MSG_ORDER = 1;
/// @dev Fixed prefix through `destAssetLen`, i.e. everything before the first string.
uint256 internal constant TERMS_HEADER_SIZE = 118;
uint256 internal constant ORDER_SIZE = 73;
/// @notice The forward payload's version.
uint8 internal constant FORWARD_VERSION = 1;
uint256 internal constant FORWARD_SIZE = 37;
error InvalidOwner();
error InvalidQuoteId();
error InvalidSlippage(uint16 bps);
error InvalidFillMultiplier(uint8 multiplier);
error InvalidDeadline();
error InvalidRecipientKind(uint8 kind);
error InvalidRefundTo();
error InvalidDestinationAsset(uint256 length);
error InvalidRecipient(uint256 length);
error InvalidVersion(uint8 version);
/// @dev Declared lengths do not account for the buffer exactly.
error MalformedTerms(uint256 length);
/// @dev Not a 37-byte payload of the forward version.
error MalformedForward(uint256 length);
/// @dev A relay ceiling wider than the payload's 16 bytes.
error InvalidRelayFee(uint256 maxRelayFee);
// ─── Terms ───────────────────────────────────────────────────
/// @notice The MPC derivation path a set of terms hashes to.
function authPath(IIntentDispatcher.Quote memory t) internal pure returns (bytes32) {
return keccak256(encodeQuote(t));
}
/// @notice Encode a set of terms — the exact bytes published, and the preimage of their path.
/// @dev Every check the router's parser makes, made here first. Length bounds belong to the
/// encoder, so no caller can obtain an ambiguous hash: over 255 wraps to zero through the
/// `uint8` cast.
function encodeQuote(IIntentDispatcher.Quote memory t) internal pure returns (bytes memory) {
bytes memory asset = bytes(t.destinationAsset);
bytes memory recipient = bytes(t.recipient);
if (t.owner == address(0)) revert InvalidOwner();
if (t.quoteId == bytes32(0)) revert InvalidQuoteId();
if (t.maxSlippageBps >= BPS) revert InvalidSlippage(t.maxSlippageBps);
if (t.maxFillMultiplier < MIN_FILL_MULTIPLIER || t.maxFillMultiplier > MAX_FILL_MULTIPLIER) {
revert InvalidFillMultiplier(t.maxFillMultiplier);
}
if (t.deadline == 0) revert InvalidDeadline();
if (t.recipientKind > KIND_INTENTS_ACCOUNT) revert InvalidRecipientKind(t.recipientKind);
if (t.refundTo == address(0)) revert InvalidRefundTo();
if (!_printable(asset)) revert InvalidDestinationAsset(asset.length);
if (!_printable(recipient)) revert InvalidRecipient(recipient.length);
// Two halves, or the packing runs out of stack: the fixed fields, then the two strings.
return bytes.concat(
abi.encodePacked(
VERSION,
t.owner,
t.quoteId,
t.maxSlippageBps,
t.maxFillMultiplier,
t.minOutPerIn,
t.minDelivery,
t.deadline,
t.recipientKind,
t.refundTo
),
abi.encodePacked(uint8(asset.length), asset, uint8(recipient.length), recipient)
);
}
/// @notice Parse encoded terms back — the mirror of the router's decoder, for tests and tools.
/// @dev Rejects rather than truncates: a buffer two different sets of terms could hash from is
/// not one to read the first of.
function decodeQuote(bytes memory terms) internal pure returns (IIntentDispatcher.Quote memory t) {
if (terms.length < TERMS_HEADER_SIZE) revert MalformedTerms(terms.length);
if (uint8(terms[0]) != VERSION) revert InvalidVersion(uint8(terms[0]));
uint256 assetLen = uint8(terms[117]);
uint256 recipientLenOffset = TERMS_HEADER_SIZE + assetLen;
if (terms.length <= recipientLenOffset) revert MalformedTerms(terms.length);
uint256 recipientLen = uint8(terms[recipientLenOffset]);
// Read the second length only after the first string, and hold the total to both.
if (terms.length != recipientLenOffset + 1 + recipientLen) revert MalformedTerms(terms.length);
t = IIntentDispatcher.Quote({
owner: address(uint160(_uint(terms, 1, 20))),
quoteId: bytes32(_uint(terms, 21, 32)),
maxSlippageBps: uint16(_uint(terms, 53, 2)),
maxFillMultiplier: uint8(terms[55]),
minOutPerIn: uint128(_uint(terms, 56, 16)),
minDelivery: uint128(_uint(terms, 72, 16)),
deadline: uint64(_uint(terms, 88, 8)),
recipientKind: uint8(terms[96]),
refundTo: address(uint160(_uint(terms, 97, 20))),
destinationAsset: string(_slice(terms, TERMS_HEADER_SIZE, assetLen)),
recipient: string(_slice(terms, recipientLenOffset + 1, recipientLen))
});
if (t.owner == address(0)) revert InvalidOwner();
if (t.quoteId == bytes32(0)) revert InvalidQuoteId();
if (t.maxSlippageBps >= BPS) revert InvalidSlippage(t.maxSlippageBps);
if (t.maxFillMultiplier < MIN_FILL_MULTIPLIER || t.maxFillMultiplier > MAX_FILL_MULTIPLIER) {
revert InvalidFillMultiplier(t.maxFillMultiplier);
}
if (t.deadline == 0) revert InvalidDeadline();
if (t.recipientKind > KIND_INTENTS_ACCOUNT) revert InvalidRecipientKind(t.recipientKind);
if (t.refundTo == address(0)) revert InvalidRefundTo();
if (!_printable(bytes(t.destinationAsset))) revert InvalidDestinationAsset(assetLen);
if (!_printable(bytes(t.recipient))) revert InvalidRecipient(recipientLen);
}
// ─── Order ───────────────────────────────────────────────────
/// @notice The order message: what the router reads to price one fill of the path's account.
function encodeOrder(bytes32 path, IIntentDispatcher.Order memory o) internal pure returns (bytes memory) {
return abi.encodePacked(MSG_ORDER, path, o.seq, o.amount, o.outPerIn);
}
// ─── Forward ─────────────────────────────────────────────────
/// @notice The forwarding instruction the Ethereum forwarder reads from the NTT transfer.
function encodeForward(address depositAddress, uint256 maxRelayFee) internal pure returns (bytes memory) {
if (maxRelayFee > type(uint128).max) revert InvalidRelayFee(maxRelayFee);
return abi.encodePacked(FORWARD_VERSION, depositAddress, uint128(maxRelayFee));
}
/// @notice Parse a forward payload — exactly 37 bytes of the forward version, or nothing.
function decodeForward(bytes memory payload) internal pure returns (address depositAddress, uint256 maxRelayFee) {
if (payload.length != FORWARD_SIZE || uint8(payload[0]) != FORWARD_VERSION) {
revert MalformedForward(payload.length);
}
depositAddress = address(uint160(_uint(payload, 1, 20)));
maxRelayFee = _uint(payload, 21, 16);
}
// ─── Helpers ─────────────────────────────────────────────────
/// @dev 1..255 bytes, every one visible ASCII — no spaces, no control characters. Both strings
/// end up in a withdrawal memo or an intents id.
function _printable(bytes memory s) private pure returns (bool) {
if (s.length == 0 || s.length > 255) return false;
for (uint256 i = 0; i < s.length; i++) {
uint8 c = uint8(s[i]);
if (c < 0x21 || c > 0x7e) return false;
}
return true;
}
/// @dev `size` big-endian bytes at `offset`, as an integer.
function _uint(bytes memory data, uint256 offset, uint256 size) private pure returns (uint256 v) {
for (uint256 i = 0; i < size; i++) {
v = (v << 8) | uint8(data[offset + i]);
}
}
/// @dev Solidity has no slice for `bytes memory`.
function _slice(bytes memory data, uint256 offset, uint256 length) private pure returns (bytes memory out) {
out = new bytes(length);
for (uint256 i = 0; i < length; i++) {
out[i] = data[offset + i];
}
}
}
src/intents-v2/interfaces/IIntentDispatcher.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import {IIntentResolutionReceiver} from "./IIntentResolutionReceiver.sol";
/// @title IIntentDispatcher — intents v2 on Hydration: one order, priced, bridged and published
/// @notice Takes WETH, prices the terms' destination from Hydration feeds, bridges it to the
/// Ethereum forwarder over NTT with the forwarding instruction in the transfer's payload,
/// and publishes the order message NEAR's router swaps against. Two entries into one path:
/// ICE's `execute` callback, which arrives holding WETH, and `dispatch` for a direct caller,
/// which batches `router.sell` before it if it holds anything else.
///
/// @dev The router pins this contract as the order emitter, and the forwarder pins it as the NTT
/// sender — both by its proxy address, which ICE intents also store. A stale or missing feed
/// reverts before value leaves Hydration. Layouts: docs/intents-v2/schema.md.
interface IIntentDispatcher is IIntentResolutionReceiver {
// ─── Types ───────────────────────────────────────────────────
/// @notice One action's terms — a swap, or a whole DCA schedule. Hashed into the MPC derivation
/// path, so they fix the account `A` and every rule it can be spent under.
/// @param owner The Hydration account whose orders these are — its EVM address, which ICE calls
/// `execute` as. The only caller an order of these terms is taken from.
/// @param quoteId Random per action. Keeps one user's actions on disjoint accounts; reuse merges.
/// @param maxSlippageBps How far below the order's oracle rate a fill may land.
/// @param maxFillMultiplier One fill sells at most this many times its order's amount, 2..100 —
/// what catches up missed orders, and what one order's price may move at once.
/// @param minOutPerIn The user's hard floor, destination units per 1e18 wei; 0 = none.
/// @param minDelivery Before the deadline, deliver only once `A` holds this much of the
/// destination — at least the bridge's minimum withdrawal.
/// @param deadline Unix seconds. Swaps end by it; refunds start after it.
/// @param recipientKind 0 = withdraw off NEAR through POA to `recipient`; 1 = `recipient` is a
/// NEAR intents account.
/// @param refundTo Ethereum address refunds go to, as native ETH.
/// @param destinationAsset Intents ledger id to buy, e.g. `nep141:zec.omft.near`.
/// @param recipient Where the destination asset goes. The value the whole design protects.
struct Quote {
address owner;
bytes32 quoteId;
uint16 maxSlippageBps;
uint8 maxFillMultiplier;
uint128 minOutPerIn;
uint128 minDelivery;
uint64 deadline;
uint8 recipientKind;
address refundTo;
string destinationAsset;
string recipient;
}
/// @notice One execution, priced.
/// @param seq The NTT message id of its transfer — the order's id.
/// @param amount The least ETH `A` receives, wei: the WETH taken less the rail's costs, trimmed,
/// less the relay ceiling.
/// @param outPerIn Destination smallest units per 1e18 wei, from the oracle, before slippage.
struct Order {
uint64 seq;
uint128 amount;
uint128 outPerIn;
}
/// @notice How a destination asset is priced: two USD feeds, and the asset's decimals on NEAR.
/// @param ethFeed ETH/USD, `AggregatorV3`
/// @param destFeed Destination/USD, `AggregatorV3`
/// @param destDecimals The destination's decimals in its intents ledger (ZEC 8, wNEAR 24)
struct PriceRoute {
address ethFeed;
address destFeed;
uint8 destDecimals;
}
// ─── Events ──────────────────────────────────────────────────
/// @notice An order was bridged and published — what the bot acts on.
/// @param authPath Hash of the terms — the MPC derivation path
/// @param seq The order's NTT message id
/// @param caller Who placed it: a direct caller, or the ICE intent's owner (the runtime calls
/// `execute` as the user)
/// @param depositAddress POA's deposit address the ETH is forwarded to
/// @param amount The least ETH `A` receives — bridged less the relay ceiling
/// @param outPerIn The rate it was priced at
/// @param messageSequence Wormhole core sequence of the order message
/// @param terms The encoded terms, in full — what the bot passes to the router
event OrderPublished(
bytes32 indexed authPath,
uint64 indexed seq,
address indexed caller,
address depositAddress,
uint128 amount,
uint128 outPerIn,
uint64 messageSequence,
bytes terms
);
event PriceRouteSet(string destinationAsset, address ethFeed, address destFeed, uint8 destDecimals);
event MaxFeedAgeSet(uint256 maxFeedAge);
event MinOrderAmountSet(uint256 minOrderAmount);
event NttManagerSet(address nttManager);
event ForwarderSet(bytes32 forwarder);
event Swept(address indexed asset, address indexed to, uint256 amount);
// ─── Errors ──────────────────────────────────────────────────
error NotOwner();
error NotConfigured();
error ZeroAmount();
error InvalidDepositAddress();
error SettlementRouteMismatch(address expected, address actual);
/// @dev ICE pushed something other than WETH — only a trade into WETH can become an order.
error NotWeth(address assetOut);
/// @dev Only the terms' owner places their orders — anyone else could spend `A`'s ETH at a
/// moment of their choosing.
error NotTermsOwner(address caller, address owner);
/// @dev `execute` was called for more WETH than arrived since the last order — the rest is
/// dust earlier orders left, not this caller's.
error UnbackedAmount(uint256 amountOut);
/// @dev The WETH does not cover the rail's delivery price and the order message's fee.
error AmountBelowCost(uint256 weth, uint256 cost);
/// @dev What would bridge is below the floor: POA's minimum deposit plus the relay ceiling.
error AmountBelowMinimum(uint256 amount, uint256 minimum);
/// @dev The relay ceiling is over half of what bridges — `A` could receive under half the
/// order, more than one router fill.
error RelayFeeTooHigh(uint256 maxRelayFee, uint256 amount);
error UnpricedAsset(string destinationAsset);
error InvalidFeedAnswer(address feed, int256 answer);
error StaleFeed(address feed, uint256 updatedAt);
/// @dev The feed reports an update after the current block — its age could never expire.
error FutureFeedAnswer(address feed, uint256 updatedAt);
error InvalidRate(uint256 outPerIn);
// ─── Dispatch ────────────────────────────────────────────────
/// @notice Send `amount` of the caller's WETH as one order of the action `terms` describe.
/// @param depositAddress POA's deposit address for the account the terms derive — the SDK
/// computes it once per action; nothing on-chain binds the two.
/// @param maxRelayFee Ceiling a redeemer may claim on Ethereum.
/// @dev Not payable: the rail's costs come out of `amount`, as they do out of an ICE trade. What
/// bridges must be at least POA's minimum deposit plus `maxRelayFee`, and `maxRelayFee` at
/// most half of it, so the order credits and swaps in one fill.
/// @return seq The order's NTT message id
function dispatch(
uint256 amount,
address depositAddress,
uint256 maxRelayFee,
Quote calldata terms
) external returns (uint64 seq);
/// @notice The rate the next order for `destinationAsset` would carry: destination smallest
/// units per 1e18 wei. Reverts on a missing route or a stale feed, as a dispatch would.
function outPerIn(string calldata destinationAsset) external view returns (uint128);
/// @notice The MPC derivation path a set of terms hashes to. Turn this into the NEAR account and
/// its POA deposit address off-chain.
function computeAuthPath(Quote calldata terms) external pure returns (bytes32);
/// @notice The exact bytes the terms encode to — the preimage of their path.
function computeTerms(Quote calldata terms) external pure returns (bytes memory);
// ─── Admin ───────────────────────────────────────────────────
function setPriceRoute(string calldata destinationAsset, PriceRoute calldata route) external;
function setMaxFeedAge(uint256 maxFeedAge) external;
function setMinOrderAmount(uint256 minOrderAmount) external;
function setNttManager(address nttManager) external;
function setForwarder(bytes32 forwarder) external;
function setOwner(address newOwner) external;
function owner() external view returns (address);
}
src/intents-v2/interfaces/IIntentForwarder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title IIntentForwarder — Ethereum end of intents v2
/// @notice A relayer calls `processOrder(nttVaa, feeRequested)`: the NTT VAA is delivered, releasing
/// native ETH here, and the forwarding instruction the dispatcher put in the transfer's
/// payload says where it goes. The relayer takes `feeRequested`, bounded by the ceiling the
/// payload carries, and the rest goes to `depositAddress` — POA's deposit address for the
/// NEAR account the order funds.
///
/// One VAA: the instruction travels inside the transfer, so there is nothing to pair.
interface IIntentForwarder {
// ─── Events ──────────────────────────────────────────────────
/// @param transferSequence NTT manager's sequence — the order's id
/// @param depositAddress where the settlement was forwarded
/// @param amount forwarded, net of the relay fee
event OrderForwarded(uint64 indexed transferSequence, address indexed depositAddress, uint256 amount);
/// @param transferSequence NTT manager's sequence
/// @param relayer the caller (msg.sender) reimbursed for the relay
/// @param fee relay fee paid, in native ETH
event RelayFeePaid(uint64 indexed transferSequence, address indexed relayer, uint256 fee);
event Swept(address indexed to, uint256 amount);
event DispatcherUpdated(bytes32 indexed dispatcher);
event RelayerAuthorized(address indexed relayer, bool enabled);
event ExclusiveWindowSet(uint256 window);
// ─── Errors ──────────────────────────────────────────────────
error NotOwner();
error NotConfigured();
error NativeTransferFailed();
/// @dev Not a settlement from Hydration — the only chain the dispatcher bridges from.
error UnexpectedSourceChain(uint16 chainId);
/// @dev The transfer was not sent by the dispatcher, so its payload is not an order.
error UnauthorizedSender(bytes32 sender);
/// @dev The transfer released its funds to another address — forwarding would spend this
/// contract's balance on someone else's settlement.
error WrongRecipient(bytes32 to);
/// @dev The settlement was delivered but its funds have not been released — NTT's inbound rate
/// limiter holds it queued. Reverting leaves the order executable for retry.
error SettlementNotReleased(uint64 sequence);
/// @dev The settlement's amount is not trimmed to the precision the rail has always used, so
/// scaling it to wei would be a guess. Reverting beats forwarding a mis-scaled amount.
error UnexpectedTrim(uint8 decimals);
error FeeExceedsCeiling();
error AlreadyRedeemed();
/// @dev Caller is not authorized and the order is still inside its exclusive window. Expires, so
/// liveness never depends on any one relayer.
error Unauthorized();
/// @dev Over MAX_EXCLUSIVE_WINDOW — a longer head start would hold orders hostage to one relayer.
error InvalidExclusiveWindow(uint256 window);
// ─── Core ────────────────────────────────────────────────────
/// @notice Deliver a settlement and forward it where its payload says.
/// @dev The destination and the fee ceiling come from the transfer's payload, attested with the
/// transfer and accepted only from the pinned dispatcher; the amount from the settlement
/// itself. Any caller may process, except inside the exclusive window while an allowlist is
/// set. Reverts if the forward fails, leaving the order executable.
/// @param nttVaa the NTT transfer VAA. Delivered here unless someone already did.
/// @param feeRequested relay fee the caller claims, ≤ the payload's `maxRelayFee`
function processOrder(bytes calldata nttVaa, uint256 feeRequested) external;
// ─── Views / Admin ───────────────────────────────────────────
function owner() external view returns (address);
function dispatcher() external view returns (bytes32);
function processed(bytes32 digest) external view returns (bool);
function authorizedRelayer(address relayer) external view returns (bool);
function authorizedRelayerCount() external view returns (uint256);
function exclusiveWindow() external view returns (uint256);
function setOwner(address newOwner) external;
function setDispatcher(bytes32 dispatcher) external;
function setAuthorizedRelayer(address relayer, bool enabled) external;
function setExclusiveWindow(uint256 window) external;
function sweep(address to, uint256 amount) external;
}
src/intents-v2/interfaces/IIntentResolutionReceiver.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
// Vendored from galacticcouncil/hydration-node, pallets/intent/contracts/IIntentResolutionReceiver.sol
// (master a35840f0b). The runtime's lazy executor calls it — keep it byte-identical in its ABI.
/// @title ICE intent-resolution receiver
/// @notice Implemented by a contract named in an intent's `OnResolved::Forward` action. On (per-trade)
/// resolution the runtime pushes `amountOut` of `assetOut` to this contract and then calls `execute`.
/// The call runs inside one storage transaction: returning anything other than `this.execute.selector`
/// — or reverting — rolls the push back and leaves the funds with the intent owner.
interface IIntentResolutionReceiver {
/// @param user Intent owner's EVM address. `msg.sender == user` (identity only).
/// @param intentId The resolved intent's id.
/// @param assetIn ERC20-mapped address of the intent's input asset.
/// @param amountIn Input amount for this trade.
/// @param assetOut ERC20-mapped address of the output asset (pushed to this contract).
/// @param amountOut Output amount pushed to this contract before the call (this trade's fill).
/// @param data Opaque, contract-defined payload supplied at intent submission.
/// @return The `bytes4` ack: must equal `this.execute.selector`.
function execute(
address user,
uint256 intentId,
address assetIn,
uint256 amountIn,
address assetOut,
uint256 amountOut,
bytes calldata data
) external returns (bytes4);
}
src/ntt/NttPayload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import {BytesParsing} from "wormhole-solidity-sdk/libraries/BytesParsing.sol";
/// @title NttPayload — the fields an intent settlement is matched and sized on
/// @dev Mirrors `TransceiverStructs.parseTransceiverMessage` + `parseNttManagerMessage` +
/// `parseNativeTokenTransfer` from hydration-ntt at NTT_COMMIT
/// 0f19d43f7ae88adf36e62364d4157db8da7a68ee, reading as far as the transfer's amount. Field by
/// field, using the same `BytesParsing` primitives NTT does, and in ONE pass — the sequence,
/// the digest preimage and the amount all come off the same walk.
library NttPayload {
using BytesParsing for bytes;
/// @notice The Wormhole transceiver's payload prefix.
bytes4 internal constant WH_TRANSCEIVER_PAYLOAD_PREFIX = 0x9945FF10;
/// @notice The `NativeTokenTransfer` prefix, inside the manager's message.
bytes4 internal constant NTT_PREFIX = 0x994E5454;
error InvalidPrefix(bytes4 prefix);
error InvalidTransferPrefix(bytes4 prefix);
/// @notice Everything a settlement is matched and sized on.
/// @param payload A Wormhole transceiver VAA's payload.
/// @return sequence The manager's sequence for this settlement — `NttManager.transfer`'s return
/// value, which the manager writes as `bytes32(uint256(sequence))`
/// @return message The manager message, the preimage NTT digests delivery on
/// @return decimals The precision `amount` carries. NTT trims to `min(8, srcDp, dstDp)`, so this
/// is not the token's own and the caller must scale by it
/// @return amount What the transfer releases, trimmed to `decimals`
function settlementOf(bytes memory payload)
internal
pure
returns (uint64 sequence, bytes memory message, uint8 decimals, uint64 amount)
{
uint256 offset = 0;
bytes4 prefix;
(prefix, offset) = payload.asBytes4Unchecked(offset);
if (prefix != WH_TRANSCEIVER_PAYLOAD_PREFIX) revert InvalidPrefix(prefix);
(, offset) = payload.asBytes32Unchecked(offset); // sourceNttManagerAddress
(, offset) = payload.asBytes32Unchecked(offset); // recipientNttManagerAddress
uint16 length;
(length, offset) = payload.asUint16Unchecked(offset);
// Checked: the length prefix comes from bytes `parseVM` has not verified.
(message,) = payload.slice(offset, length);
bytes32 id;
(id, offset) = payload.asBytes32Unchecked(offset);
sequence = uint64(uint256(id));
(, offset) = payload.asBytes32Unchecked(offset); // sender
(, offset) = payload.asUint16Unchecked(offset); // transfer payload length
bytes4 transferPrefix;
(transferPrefix, offset) = payload.asBytes4Unchecked(offset);
if (transferPrefix != NTT_PREFIX) revert InvalidTransferPrefix(transferPrefix);
// Amount and decimals are encoded in reverse order to how `TrimmedAmount` declares them,
// matching the Rust implementation — decimals first.
(decimals, offset) = payload.asUint8Unchecked(offset);
(amount, offset) = payload.asUint64Unchecked(offset);
}
/// @notice A settlement's transfer in full — who sent it, where it goes, and its payload.
/// @param sequence The manager's sequence, as `settlementOf` reads it
/// @param message The manager message, the preimage NTT digests delivery on
/// @param sender Who called `transfer` on the source manager
/// @param decimals The precision `amount` carries
/// @param amount What the transfer releases, trimmed to `decimals`
/// @param to The recipient on the destination chain
/// @param toChain The destination chain
/// @param additionalPayload The transfer's payload; empty when it carries none
struct Transfer {
uint64 sequence;
bytes message;
bytes32 sender;
uint8 decimals;
uint64 amount;
bytes32 to;
uint16 toChain;
bytes additionalPayload;
}
/// @notice Read a settlement's transfer through its optional payload, as
/// `TransceiverStructs.parseNativeTokenTransfer` does: the payload is encoded only when
/// non-empty, and the manager message must end where the transfer does.
/// @dev Every read is checked: the bytes come from a VAA `parseVM` has not verified.
/// @param payload A Wormhole transceiver VAA's payload.
function transferOf(bytes memory payload) internal pure returns (Transfer memory t) {
uint256 offset = 0;
bytes4 prefix;
(prefix, offset) = payload.asBytes4(offset);
if (prefix != WH_TRANSCEIVER_PAYLOAD_PREFIX) revert InvalidPrefix(prefix);
(, offset) = payload.asBytes32(offset); // sourceNttManagerAddress
(, offset) = payload.asBytes32(offset); // recipientNttManagerAddress
uint16 length;
(length, offset) = payload.asUint16(offset);
(t.message,) = payload.slice(offset, length);
bytes memory m = t.message;
uint256 at = 0;
bytes32 id;
(id, at) = m.asBytes32(at);
t.sequence = uint64(uint256(id));
(t.sender, at) = m.asBytes32(at);
uint16 transferLength;
(transferLength, at) = m.asUint16(at);
m.checkLength(at + transferLength);
bytes4 transferPrefix;
(transferPrefix, at) = m.asBytes4(at);
if (transferPrefix != NTT_PREFIX) revert InvalidTransferPrefix(transferPrefix);
(t.decimals, at) = m.asUint8(at);
(t.amount, at) = m.asUint64(at);
(, at) = m.asBytes32(at); // sourceToken
(t.to, at) = m.asBytes32(at);
(t.toChain, at) = m.asUint16(at);
if (at < m.length) {
uint16 payloadLength;
(payloadLength, at) = m.asUint16(at);
(t.additionalPayload, at) = m.slice(at, payloadLength);
}
m.checkLength(at);
}
}
src/ntt/interfaces/INttManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title INttManager — minimal NTT manager surface used by Basejump
/// @dev Hand-written: the pinned Solidity SDK ships no NTT interface. Signatures match
/// hydration-ntt evm/src/interfaces/{INttManager,IManagerBase}.sol at NTT_COMMIT
/// 0f19d43f7ae88adf36e62364d4157db8da7a68ee (deployment version 2.0.0).
interface INttManager {
/// @notice Locks (hub) or burns (spoke) `amount` and emits a transfer message.
/// @dev This 3-arg overload hardcodes `shouldQueue = false`, so an outbound
/// rate-limit breach REVERTS rather than queuing. Basejump depends on that:
/// it is what keeps a fast-path payout from ever outrunning its settlement.
function transfer(
uint256 amount,
uint16 recipientChain,
bytes32 recipient
) external payable returns (uint64 msgId);
/// @return perTransceiver Price for each enabled transceiver
/// @return total Total delivery price — the value `transfer` must be sent with
/// @dev `transceiverInstructions` must be `hex"00"` (zero-count prefix). Passing
/// empty bytes reverts LengthMismatch(0,1) = 0xab8b67c6.
function quoteDeliveryPrice(
uint16 recipientChain,
bytes memory transceiverInstructions
) external view returns (uint256[] memory perTransceiver, uint256 total);
function token() external view returns (address);
function tokenDecimals() external view returns (uint8);
function isPaused() external view returns (bool);
function getCurrentOutboundCapacity() external view returns (uint256);
/// @notice A transfer held by the inbound rate limiter.
/// @dev `amount` is NTT's `TrimmedAmount`; declared as its underlying `uint72` so the ABI decode
/// matches without importing NTT's value type.
struct InboundQueuedTransfer {
uint72 amount;
uint64 txTimestamp;
address recipient;
}
/// @notice Whether the manager executed a message. Set before the rate limiter runs, so it is
/// true for a queued transfer as well as a released one.
function isMessageExecuted(bytes32 digest) external view returns (bool);
/// @notice The inbound queue entry for a message. `txTimestamp` is zero when none is held —
/// `completeInboundQueuedTransfer` deletes the entry before it releases.
function getInboundQueuedTransfer(bytes32 digest)
external
view
returns (InboundQueuedTransfer memory);
}
src/ntt/interfaces/IWormholeTransceiver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title IWormholeTransceiver — NTT's Wormhole transceiver, destination side
/// @dev Hand-written: the pinned Solidity SDK ships no NTT interfaces. Signatures match
/// hydration-ntt evm/src/interfaces/{IWormholeTransceiver,IWormholeTransceiverState}.sol at
/// NTT_COMMIT 0f19d43f7ae88adf36e62364d4157db8da7a68ee (deployment version 2.0.0).
interface IWormholeTransceiver {
/// @notice Verify a transfer VAA and hand it to the manager, which releases to the recipient the
/// message names.
/// @dev Permissionless and the expensive half of a delivery — it verifies every guardian
/// signature. Reverts if the VAA was already consumed.
function receiveMessage(bytes memory encodedMessage) external;
/// @notice Whether a VAA has already been consumed by this transceiver.
function isVAAConsumed(bytes32 hash) external view returns (bool);
/// @notice The manager this transceiver delivers to.
function nttManager() external view returns (address);
}
src/utils/hydration/HydrationConsts.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
library HydrationConsts {
uint32 internal constant PARA_ID = 2034;
/// @notice Wormhole chain id — the id used in VAAs and NTT routes. Hydration has three distinct
/// identifiers: this one (73), the EVM chain id (222222), and the para id (2034).
uint16 internal constant WORMHOLE_CHAIN_ID = 73;
/// @notice Dispatch precompile (0x0401) — executes a SCALE-encoded runtime call as the caller.
address internal constant DISPATCH_PRECOMPILE = 0x0000000000000000000000000000000000000401;
// --- Native asset ids ---
uint32 internal constant WETH_ID = 20;
/// @notice Asset id → ERC20-precompile address: 0x0100000000 | assetId.
function toErc20(uint32 assetId) internal pure returns (address) {
return address((uint160(1) << 32) | uint160(assetId));
}
/// @notice ERC20-precompile address → Asset id: low 4 bytes.
/// @dev Assumes a valid asset-precompile address; the 0x0100000000 prefix is not checked.
function toAssetId(address erc20) internal pure returns (uint32) {
return uint32(uint160(erc20));
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": false
},
"evmVersion": "prague",
"remappings": [
"forge-std/=dependencies/forge-std-1.14.0/src/",
"wormhole-solidity-sdk/=dependencies/wormhole-solidity-sdk-0.1.0/src/",
"@openzeppelin/contracts-upgradeable/=dependencies/openzeppelin-contracts-upgradeable-5.5.0/contracts/",
"@openzeppelin/contracts/=dependencies/openzeppelin-contracts-5.5.0/contracts/",
"ds-test/=dependencies/wormhole-solidity-sdk-0.1.0/lib/forge-std/lib/ds-test/src/",
"forge-std-1.14.0/=dependencies/forge-std-1.14.0/src/",
"openzeppelin-contracts-5.5.0/=dependencies/openzeppelin-contracts-5.5.0/",
"openzeppelin-contracts-upgradeable-5.5.0/=dependencies/openzeppelin-contracts-upgradeable-5.5.0/",
"wormhole-solidity-sdk-0.1.0/=dependencies/wormhole-solidity-sdk-0.1.0/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.