# What We Do

Redefining Interoperability with iLayer.

iLayer provides an intuitive, one-stop solution enabling developers and decentralized protocols to effortlessly execute arbitrarily complex cross-chain Web3 actions through a flexible, intent-based protocol. At its core, iLayer simplifies cross-chain interoperability, allowing developers to specify their desired outcomes without needing deep technical expertise in bridge technology or chain-specific protocols.

This significantly reduces the typical complexity associated with cross-chain integrations, cutting implementation times from days or weeks to less than one hour.

With iLayer, protocols instantly gain access to interoperability across major EVM-compatible and non-EVM blockchains, unlocking new liquidity channels, accelerating time-to-market, and enhancing user experiences. By abstracting away the technical overhead, iLayer enables Web3 builders to focus on innovation, product growth, and delivering exceptional cross-chain functionality to users.


# The DeFi Problem

DeFi faces critical challenges hindering mainstream adoption and optimal functionality.

***

<table data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>💢 Asset Fragmentation</td><td>Liquidity is trapped across multiple chains, leading to inefficient capital usage and increased slippage.</td></tr><tr><td>❌ Bridge Complexity</td><td>Complex bridging protocols require extensive documentation and technical expertise, hindering rapid deployment.</td></tr><tr><td>🐢 Slow GTM</td><td>Extensive audits, detailed architecture design, and prolonged development cycles delay innovation and market entry.</td></tr></tbody></table>

{% stepper %}
{% step %}

### Asset Fragmentation

Asset fragmentation occurs when liquidity pools and assets are scattered across multiple isolated blockchain ecosystems. This fragmentation leads to higher costs, increased slippage, diminished capital efficiency, and poorer user experiences.

* Existing solutions (e.g., cross-chain DEX aggregators like Li.Fi, 1inch Fusion) partially address fragmentation but typically:
  * Require significant development resources to integrate and maintain.
  * Depend on inefficient routing, increasing transaction fees and delays.
    {% endstep %}

{% step %}

### Bridge Complexity

Cross-chain bridging technology (Wormhole, Li.Fi Axelar, etc.) requires deep technical knowledge, extensive documentation, and complex implementation processes. These complexities significantly delay deployment and deter developers from pursuing cross-chain capabilities.

* Li.Fi, Axelar, Wormhole, and similar bridges:
  * Often necessitate custom integrations for each blockchain supported.
  * Lead to additional auditing costs due to custom implementations.
    {% endstep %}

{% step %}

### Slow GTM

Launching cross-chain functionalities traditionally involves extensive planning, careful architecture, complex audits, and prolonged development cycles. This significantly delays innovation and deployment speed, reducing competitive advantage.

* Custom-built cross-chain solutions typically:
  * Require extensive security audits, often exceeding months in duration.
  * Increase initial implementation and ongoing maintenance costs.
  * Delay product iterations, reducing flexibility in adapting to market demands.
    {% endstep %}
    {% endstepper %}


# How iLayer solves it

iLayer offers a one-stop solution to execute arbitrarily-complex cross-chain web3 actions using an adaptable intent-based protocol.

***

<table data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>💧<strong>Asset fragmentation</strong></td><td>Unify liquidity across multiple chains and protocols leveraging a vast network of individual and professional solvers.</td></tr><tr><td>🧩 <strong>Bridge Complexity</strong></td><td>iLayer removes the need to dive into any bridge docs and provides a simple signature-based interface to encode any type of cross-chain actions.</td></tr><tr><td>🚀<strong>Quick GTM</strong></td><td>iLayer strips out complexity by offering a 1-hour integration timeline and all majour EVM and non-EVM chains at your fingertips.</td></tr></tbody></table>

###

{% stepper %}
{% step %}

### Asset Fragmentation

* **Unified Liquidity Access:** iLayer aggregates liquidity seamlessly across diverse networks.
* **Comprehensive Solver Network:** Access to extensive liquidity sources ensures optimal routing, minimal slippage, and superior user experience.
* **Cost-Effective Execution:** Transparent, lower fees (0.03%) provide significant cost savings compared to existing solutions.
  {% endstep %}

{% step %}

### Bridge Complexity

* **Intuitive, Signature-Based Interface:** Developers easily define intent without diving deep into bridge documentation.
* **Zero Integration Overhead:** Eliminates the need for extensive bridge documentation and specialized technical expertise.
* **Rapid Development:** Simplifies development, reducing  complexity from weeks or months down to less than an hour.
* **Multi-bridge Support:** iLayer offers developers a wide choice of bridging providers, so far LayerZero and Axelar, soon adding support for Chainlink CCIP and Across. Dapps can choose their favourite cross-chain provider or let the user pick it without any code changes.
  {% endstep %}

{% step %}

### Quick GTM

* **Plug-and-Play Integration:** Ready-to-use integration framework ensures deployment in under one hour.
* **Pre-Audited and Secure:** Offers a secure, audited solution out-of-the-box, drastically reducing audit timelines and costs.
* **Rapid Innovation Cycles:** Enables developers to quickly test, iterate, and deploy new cross-chain features, accelerating innovation and enhancing competitive positioning.
  {% endstep %}
  {% endstepper %}

### ⚡️ Why iLayer?

Compared to current market solutions, iLayer significantly reduces complexity, cost, and time-to-market—enabling developers and decentralized applications to rapidly scale and innovate across multiple blockchain ecosystems.

| Features                  | Existing Solutions     | iLayer                          |
| ------------------------- | ---------------------- | ------------------------------- |
| Integration Time          | Weeks or Months        | ✅ **< 1 hour**                  |
| Technical Complexity      | High (Bridge-specific) | ✅ **Minimal (Signature-based)** |
| Liquidity Access          | Limited, fragmented    | ✅ **Unified, comprehensive**    |
| Costs & Fees              | High (up to 0.15%+)    | ✅ **Low (0.03%)**               |
| Audit & Security Overhead | High (custom-built)    | ✅ **Reduced (pre-audited)**     |


# Copy of Copy of About Us

### What we do

We offer a one-stop solution to execute arbitrarily-complex cross-chain web3 actions using an adaptable intent-based protocol.

### What we solve

1. **Asset fragmentation**

   Unify liquidity across multiple chains and protocols leveraging a vast network of individual and professional solvers.
2. **Complexity of bridges**

   we remove the need to dive into LayerZero or any other bridge docs and provide a simple signature-based interface to encode any type of cross-chain actions.
3. **Quick GTM**

   Often times developing or upgrading a protocol to be cross-chain requires extensive auditing and thoughtful architecture; iLayer strips out complexity by offering a 1-hour integration timeline and all majour EVM and non-EVM chains at your fingertips.

### Where we are going

The future roadmap for iLayer mainly revolves around hardening security, improving chain support and making our docs simpler in order to provide dapps and devs the tools to ship faster.


# Use Cases

### **For users**

<table data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>🌾 <strong>Yield farming</strong></td><td>Tap into a new protocol or chain without the need to have gas or funds locally</td></tr><tr><td>🔄 <strong>Swaps</strong></td><td>Rebalance or consolidate funds from chain to chain</td></tr><tr><td>🎛️ <strong>DeFi frontends</strong></td><td>Encode complex actions into a simple intent</td></tr><tr><td>..and more</td><td></td></tr></tbody></table>

### For developers

\- **new chains** (Monad, Bera, megaETH): easy bridging and interaction with local dapps without the need to go through multiple steps, one click defi, gasless UX

\- **chain-specific protocols** (Morpho, GMX): interact with the protocol without having to get exposure to the underlying chain

\- **cross-chain rebalancers** (yearn, nashpoint, beefy): allocate assets cross-chain without multi-bridging (by creating multiple intents)

\- **single-chain dapps looking to go cross-chain**: easier to integrate iLayer than LayerZero/Axelar/Across, with more functionalities out of the box

\- **AI**: encode LLM outputs into a unique intent able to support ideally "any" action the user may want to execute


# RFQ

When a new intent is generated, it needs to be broadcasted to our network of solver bots. We don't rely on a centralised server but instead we use [Waku](https://waku.org/),   a censorship-resistant communication protocol that anyone can access. By doing so, we allow participation to the iLayer network to anyone without the need to KYC or register anywhere.

### Waku

The [**Waku protocol**](https://waku.org) is a decentralized messaging solution designed to facilitate secure, scalable, and privacy-focused communication for distributed applications. Originally derived from the Whisper protocol, Waku has been enhanced to overcome issues of scalability and performance. It operates on a publish/subscribe model, making it an ideal choice for applications requiring real-time, decentralized message exchange without the need for a central server. Key benefits include:

* **Decentralization:** Eliminates single points of failure by distributing message relaying across a network of nodes.
* **Scalability:** Supports high volumes of messages, making it suitable for systems with many simultaneous users and solvers.
* **Enhanced Privacy:** Provides mechanisms to direct responses to specific users, reducing unnecessary network noise and preserving user privacy.

### Overview of the RFQ

In the RFQ (Request For Quote) process, the system allows users to:

* **Configure Tokens:** Define the input tokens on chain A and the output tokens on chain B via the user interface.
* **Request Quotations:** Submit an RFQ that is broadcast to the network of solvers. Each solver processes the request and returns its own quote.
* **Select a Solver:** Review the received quotations, choose the most favorable offer, and then proceed to place an order on the [hub contract](https://docs.ilayer.io/hub-and-spoke/orderhub).

<figure><img src="https://1143396534-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ftk5FFpsTxFBW3oQIy5TY%2Fuploads%2FRINyrFam2Xx9rrSPwF8g%2Frfq.png?alt=media&amp;token=ef8ec51e-0df5-4718-ba5e-bcc32f3ab5cf" alt=""><figcaption><p>Highlighted in red is the complete flow of an individual request.</p></figcaption></figure>

### Order Request Submission

#### **Message Composition**

The user interface constructs an RFQ message that includes:

* **request deadline**
* **nonce**
* The **user** public address encoded as a bytes32 field
* The **recipient** public address encoded as a bytes32 field
* an eventual filler, left blank if any solver can respond to the RFQ
* **inputs** tokens and their amounts
* **outputs** tokens and their relative weight (if > 1)
* **source chain ID**
* **destination chain ID**
* whether the order is **sponsored**/gasless or not (gas cost will be subtracted from the final quote)
* a **primary deadline** for the responder that will have them as the main solver, after this deadline any bot on the iLayer network can fill the order ***preserving the original input and output quotes***
* a **secondary deadlin**e, after which the order is marked as expired and cannot be filled anymore
* any eventual **calldata-related** settings (target, data and value)

> *Chain IDs can be obtained by visiting the* [*chainlist website*](https://chainlist.org/)*.*

**Example**

<pre class="language-json"><code class="lang-json">{
  "deadline": 1750000, // timestamp
  "nonce": 3, // an incremental nonce to avoid replay attacks
  "user": "0x00123", // in bytes32 notation to support non-EVM chains
<strong>  "recipient": "0x00123", // same as above
</strong><strong>  "filler": "", // empty unless we are sending the order to a specific solver
</strong><strong>  "inputs": [
</strong>    { "tokenAddress": "USDC address", "amount": 10000000, "type": "FUNGIBLE_TOKEN", "tokenId": 0 },
<strong>  ],
</strong><strong>  "outputs": [
</strong>    { "tokenAddress": "DAI address", "amount": 9900000000000000000, "type": "FUNGIBLE_TOKEN", "tokenId": 0 },
<strong>  ]
</strong><strong>  "sourceChainId": 1, // Ethereum mainnet
</strong><strong>  "destinationChainId": 137, // Polygon
</strong><strong>  "sponsored": false, //
</strong><strong>  "primaryFillerDeadline": 123..., // timestamp
</strong><strong>  "deadline": 123..., // timestamp
</strong><strong>  "callRecipient": "",
</strong><strong>  "callData": "",
</strong><strong>  "callValue": 0,
</strong><strong>}
</strong></code></pre>

**Multitoken output**

To expand on the multi-token, let's imagine that we have WBTC, WETH and DAI as output, the array would look like this. 20% of the final value will be BTC, 20% will be WETH and 50% will be DAI. The order request `output` tokens part is as follows:

```json
{
...
 "outputs": [
  { "tokenAddress": "WBTC address", "amount": 20, "type": "FUNGIBLE_TOKEN", "tokenId": 0 },
  { "tokenAddress": "WETH address", "amount": 30, "type": "FUNGIBLE_TOKEN", "tokenId": 0 },
  { "tokenAddress": "DAI address", "amount": 50, "type": "FUNGIBLE_TOKEN", "tokenId": 0 },
 ]
}
```

**| Note:** *if the total weights sum is different than 100, the order will be rejected.*

#### **Publishing on the** `rfq` **topic**

This order request message is then published to a dedicated `rfq` topic via the Waku protocol. All network solvers are subscribed to this topic, ensuring that every solver receives the request.&#x20;

#### Solver Response Mechanism

* **Listening to the** `rfq` **topic:**\
  All solvers in the network continuously monitor the `rfq` topic for incoming RFQ messages. Upon receiving a message, each solver evaluates the request based on its own logic and market parameters.
* **Replying via User-specific topics:**\
  In the RFQ message, the user’s public address is included to allow solvers to target their responses. Each solver publishes its quotation to a unique topic associated with the user’s public address (e.g., `<user_public_address>`). This ensures that:
  * Only the intended recipient receives the response.
  * Network traffic is efficiently segregated, minimizing exposure of solver responses to unintended parties.

### Order Execution

* **Quote Selection:**\
  The user interface aggregates the responses from various solvers. The user reviews the quotes and selects one based on factors such as pricing and execution terms.
* **Finalizing the Order:**\
  Once a solver is selected, the user proceeds to:
  * submit an order on the hub contract, thereby initiating the trade based on the chosen quotation.
  * submit the signed order directly to the bot for gasless execution.
  * (not implemented yet) use iLayer gas sponsoring function directly.

### Advantages of using Waku in RFQ

* **Decentralized:**\
  The pub/sub model ensures robust, decentralized messaging without reliance on a central server, thereby enhancing system resilience.
* **Scalable:**\
  The protocol's design allows it to handle a high volume of messages, making it suitable for environments where multiple RFQs and solver responses are processed concurrently.
* **Private:**\
  By directing solver responses to user-specific topics, the protocol limits message exposure to only the intended recipient, thus enhancing confidentiality and reducing risks of data leakage.
* **Trusted:**\
  iLayer contributes to the security and decentralization of the protocol by offering its own Waku nodes. These dedicated nodes enhance the robustness of the messaging infrastructure, reducing dependency on third-party networks and ensuring reliable message propagation throughout the system.
* **Interoperable:**\
  As an open and blockchain agnostic protocol, Waku easily integrates with decentralized applications, ensuring seamless communication across heterogeneous environments.


# Hub & Spoke

iLayer smart contracts form the backbone of the iLayer network, enabling secure and trustless interactions between users and solver bots. They allow value exchange without counterparty risk through a locking mechanism similar to an atomic swap, mediated by the Router cross-chain messaging adapter.&#x20;

At the core, the system is split into two main parts deployed on every supported chain:

* **OrderHub:** Responsible for order creation and withdrawal, input token custody and order settlement.
* **OrderSpoke:** Handles order filling and output token disbursement.

Each chain supported by iLayer features both a Hub contract and a Spoke contract, deployed under deterministic and consistent addresses using Create3 (on EVM-compatible chains).

### The intent flow

#### 1. **Creating an Order on the `OrderHub`**:

* A user creates an order specifying:
  * Input tokens (ERC20, ERC721, ERC1155) they're willing to trade.
  * Desired output tokens on the destination chain.
  * Deadlines, destination chain ID, optional sponsored fees, and an optional execution hook (`callRecipient`and `callData`).
* The user signs the order off-chain.
* The `OrderHub` contract verifies the user's signature and nonce to prevent replay attacks.
* Input tokens are transferred from the user to the `OrderHub` for secure custody.
* Order state is marked as `ACTIVE`.
* A cross-chain call is sent using the designated Router adapter (users can choose LayerZero or Axelar, support for other bridges is coming) to the OrderSpoke contract to register the order ID as pending.

**Key function**: `createOrder()`

{% @mermaid/diagram content="sequenceDiagram
participant User
participant OrderHub
participant Router
participant OrderSpoke

```
User ->> OrderHub: createOrder(signed order + tokens)
OrderHub -->> OrderHub: Verify signature & custody tokens
OrderHub -->> Router: send cross-chain message
Router -->> OrderSpoke: Register order ID" %}
```

***

#### 2. **Filling an Order on the `OrderSpoke`**:

* When a solver (executor bot or other service) fills an order, they trigger the `fillOrder()` function in the `OrderSpoke` contract on the destination chain.
* The `OrderSpoke` verifies that:
  * The order was previously registered, is valid and hasn't expired.
  * The order hasn’t already been filled already.
  * The solver is allowed to fill it by checking if the `msg.sender` is the designated primary filler or the primary deadline has expired and anyone can fill it.
* The solver provides output tokens to the `OrderSpoke`, ensuring the balance matches the amounts defined in the Order. Any positive slippage / excess is kept by the Spoke contract.
* If specified in the Order intent, the Spoke also executes an external hook via an `Executor` contract safely isolated to prevent malicious behavior or reentrancy.
* The `OrderSpoke` sends a message back to the originating chain endpoint (`OrderHub`) using the Router, signaling successful execution and settlement details.
* Upon receiving a cross-chain fill message:
  * `OrderHub` marks the order status as `FILLED`.
  * Input tokens held in custody are released to the solver’s funding wallet.

This completes the settlement: the user gets desired assets on the destination chain, and the solver receives input tokens on the source chain.

**Key function**: `fillOrder()`

{% @mermaid/diagram content="sequenceDiagram
participant Solver
participant OrderSpoke
participant User
participant Router
participant OrderHub

```
Solver ->> OrderSpoke: fillOrder(order + tokens)
OrderSpoke -->> OrderSpoke: Verify order & token amounts
OrderSpoke -->> User: Send output tokens
OrderSpoke -->> Router: send cross-chain message
Router -->> OrderHub: mark order as filled
OrderHub -->> Solver: send input tokens" %}
```


# OrderHub

The `OrderHub` contract manages user orders and custody of tokens until orders are filled, withdrawn, or expired. It acts as a gateway for off-chain orders, allowing users (or their solver bot delegates for gasless execution) to submit orders by providing a signed order request. Each order request comes with a nonce to prevent order creation replay, orders themselves are signed by the user using the EIP712 standard or the EIP165 for smart contract signatures.

Data coming from the RFQ stream is fed into the order intent and signed by the user, then broadcasted to the designated solver for execution or the order directly created by the user on-chain.

**TL;DR**\
The OrderHub contract is a cross-chain “order book” that lets users create off-chain orders with ERC-20/ERC-721/ERC-1155/NATIVE tokens, lock their assets in this contract and send a message via a router to a counterparty settlement contract (the `OrderSpoke`) sitting on another chain. Once the counter-party funds and the router relays back, the contract releases the assets to the designated recipient. Users can also withdraw unfilled orders after a buffer period. Order checks enforce nonce unicity, deadlines, token approvals/permits and reentrancy protection.

***

### Events

| Event                       | Parameters                                                  | Description                                                                                 |
| --------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| **SpokeUpdated**            | `chainId`, `oldSpokeAddr`, `newSpokeAddr`                   | Emitted when the owner changes the destination “spoke” address for a given chain.           |
| **TimeBufferUpdated**       | `oldTimeBufferVal`, `newTimeBufferVal` (indexed)            | Emitted when the owner adjusts the extra time users have to withdraw expired orders.        |
| **MaxOrderDeadlineUpdated** | `oldDeadline`, `newDeadline` (indexed)                      | Emitted when the owner sets a new maximum span users may set for an order’s deadline.       |
| **OrderCreated**            | `orderId` (indexed), `nonce`, `Order order`, `caller` (idx) | Emitted when a user successfully creates (locks) an order and it’s sent through the router. |
| **OrderWithdrawn**          | `orderId` (indexed), `caller` (indexed)                     | Emitted when a user withdraws their active order and assets are returned.                   |
| **OrderSettled**            | `orderId` (indexed), `Order order`                          | Emitted when the router calls back to settle (fill) the order and assets are forwarded.     |
| **ERC721Received**          | `operator`, `from`, `tokenId`, `data`                       | Emitted when this contract receives an ERC-721 token via `safeTransferFrom`.                |
| **ERC1155Received**         | `operator`, `from`, `id`, `value`, `data`                   | Emitted when this contract receives a single ERC-1155 token via `safeTransferFrom`.         |
| **ERC1155BatchReceived**    | `operator`, `from`, `ids`, `values`, `data`                 | Emitted when this contract receives multiple ERC-1155 tokens via `safeBatchTransferFrom`.   |

***

### Errors

| Error                          | Description                                                                                     |
| ------------------------------ | ----------------------------------------------------------------------------------------------- |
| **RequestNonceReused**         | The user’s off-chain order request nonce has already been used.                                 |
| **RequestExpired**             | The off-chain order request deadline (for signature validity) has passed.                       |
| **UndefinedSpoke**             | No spoke address is set for the order’s destination chain.                                      |
| **InvalidOrderInputApprovals** | The number of input tokens doesn’t match the number of provided permit blobs.                   |
| **InvalidOrderSignature**      | The order’s EIP-712 signature failed to validate against the user’s address.                    |
| **InvalidDeadline**            | The order’s deadline exceeds the configured maximum span.                                       |
| **InvalidSourceChain**         | The on-chain `block.chainid` doesn’t match the order’s declared source chain.                   |
| **InvalidDestinationChain**    | The callback from the router came from an unexpected chain (shouldn’t happen in normal flow).   |
| **OrderDeadlinesMismatch**     | The primary-filler deadline is after the overall order deadline.                                |
| **OrderPrimaryFillerExpired**  | The time window for the primary filler has elapsed before the order expires.                    |
| **OrderCannotBeWithdrawn**     | Conditions to withdraw (wrong caller, still within buffer window, or non-active status) failed. |
| **OrderCannotBeFilled**        | Conditions to settle (wrong status) failed when router callback arrives.                        |
| **OrderExpired**               | The order’s deadline has passed before creation or settlement.                                  |
| **InsufficientGasValue**       | The user didn’t send enough native (ETH) value to cover the declared input amount.              |


# OrderSpoke

The `OrderSpoke` smart contract acts as a decentralized mechanism to securely manage order fills and handle token transfers from solver entities directly to users.

Upon creation, it instantiates an `Executor` contract responsible to execute the hooks in a safe way.

The main tasks of the order spoke are:

* **Order Validation:** Ensures orders meet conditions such as expiration deadlines, duplication prevention and primary filler restrictions.
* **Funds Transfer:** Handles secure transfers of output tokens from the solver to the user.
* **Hooks Execution:** Executes additional external calls if specified in the order.
* **Cross-chain Settlement:** Sends confirmation messages to the originating chain OrderSpoke upon successful order fill.

**TL;DR**\
The `OrderSpoke` contract is part of a cross-chain order fulfillment system. It receives “pending” order notifications from a central hub (via `onMessageReceived`), allows an off-chain solver to fill those orders with exactly the right funds and call data (`fillOrder`), manages fee deductions, executes an optional callback on fulfillment, and then relays a response back to the source chain’s hub. It also lets the owner sweep stranded tokens and update configuration settings (hub addresses and fee rate).

***

### Events

| Event                  | Parameters                                                                                                                                          | Description                                                                                                      |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `HubUpdated`           | <p><code>chainId</code><br><code>oldHubAddr</code><br><code>newHubAddr</code></p>                                                                   | Emitted when the owner changes the hub address for a given chain.                                                |
| `FeeUpdated`           | <p><code>oldFee</code> (indexed)<br><code>newFee</code> (indexed)</p>                                                                               | Emitted when the owner updates the per-order fee rate (in basis-points out of 10 000).                           |
| `PendingOrderReceived` | <p><code>orderId</code> (indexed)<br><code>spokeChainId</code> (indexed)</p>                                                                        | Emitted when a new order arrives from a hub on another chain and is marked PENDING.                              |
| `OrderFilled`          | <p><code>orderId</code> (indexed)<br><code>order</code><br><code>caller</code> (indexed)</p>                                                        | Emitted after successfully filling an order: funds transferred, callback called (if any), and message sent back. |
| `TokenSweep`           | <p><code>tokenType</code> (indexed)<br><code>tokenId</code><br><code>token</code> (indexed)<br><code>to</code> (indexed)<br><code>amount</code></p> | Emitted when the owner sweeps tokens/ETH out of the contract for arbitrary token types.                          |

***

### Errors

| Error                                                                     | Description                                                                                                      |
| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `UndefinedHub()`                                                          | Thrown if there is no configured hub address for the chain where the order originated or is destined.            |
| `InvalidFeeValue()`                                                       | Thrown if the owner tries to set a fee greater than the maximum resolution (10 000 basis-points).                |
| `InvalidOrder()`                                                          | Thrown if an order ID is unrecognized (never registered as PENDING).                                             |
| `OrderAlreadyFilled()`                                                    | Thrown if attempting to fill an order that’s already marked FILLED.                                              |
| `OrderExpired()`                                                          | Thrown if the block timestamp has passed the order’s `deadline` field.                                           |
| `InvalidDestinationChain()`                                               | Thrown if the order’s `destinationChainId` doesn’t match the current chain.                                      |
| `RestrictedToPrimaryFiller()`                                             | Thrown if a specific primary filler is designated and only that address can fill before its own deadline.        |
| `ExternalCallFailed()`                                                    | Thrown if the optional callback (hook) execution fails inside the `Executor`.                                    |
| <p><strong>Inherited</strong>:<br><code>InsufficientGasValue()</code></p> | Thrown if the sender didn’t supply enough native ETH to cover the order’s declared `callValue` or output amount. |


# Router

To enable cross-chain communications among a vast number of chains, iLayer employs both Axelar and LayerZero.

On each chain, a specific Router supporting either one or both of these bridging solutions will be deployed, with the plan to add support for more (Chainlink's CCIP, Across, Everclear) in the near future.

Contracts that can call the router must be whitelisted, this is to block eventual attackers from accessing the priviledged message routing infrastructure as well as to prevent polluting the event log for the Router contracts.

When invoking the Hub or the Spoke smart contracts, the user can decide which bridge to use via a specific `Bridge` enum argument. Currently available options are:

* `NULL` same-chain execution without any bridging, **sourceChainID** must match **destinationChainID**&#x20;
* `LAYERZERO` [only for Lz-supported chains](https://docs.layerzero.network/v2/deployments/deployed-contracts)
* `AXELAR` [only for Ax-supported chains](https://www.axelar.network/ecosystem#chains)

The `BaseRouter` is essentially an interface that defines a generic “cross-chain message router” that lets callers send arbitrary payloads to other chains via various bridge protocols. OrderHubs and Spokes pass in a `Message` struct (which encodes which bridge to use, the target chain ID and receiver address, the payload bytes, any extra data and the sender) and the router emits an event when it’s broadcast or reverts if the route is not supported.

**Key functionality**

* **Bridges supported**: an enum of possible cross-chain bridges (`LAYERZERO`, `AXELAR`, `CCIP`, etc.)
* **send(...)**: payable function to dispatch `Message` via the chosen bridge
* **Message struct**: bundles all routing info plus arbitrary payload

***

#### Events

| Event                | Parameters                                                    | Description                                                                                                                             |
| -------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `MessageBroadcasted` | `Message message`                                             | Emitted after a message is successfully enqueued for bridging, contains the full `Message` struct so off-chain relayers can pick it up. |
| `WhitelistUpdated`   | `address indexed target, bool previousStatus, bool newStatus` | Registers an update to the whitelist of contracts that can access the router.                                                           |

***

#### Errors

| Error                        | When It’s Thrown                                                                                                      |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `UnsupportedBridgingRoute()` | Caller specified a `Bridge` enum value that this router hasn’t implemented (e.g. `Bridge.WORMHOLE` if unimplemented). |
| `NotWhitelisted`             | The contract trying to interact with the router is not whitelisted.                                                   |

***

**Structs & Enums (for reference)**

```solidity
enum Bridge {
    NULL,        // same chain
    LAYERZERO,   // LayerZero bridge
    AXELAR,      // Axelar bridge
    CCIP,        // Chainlink CCIP
    ACROSS,      // Across Protocol
    EVERCLEAR,   // Everclear
    WORMHOLE     // Wormhole bridge
}

struct Message {
    Bridge bridge;        // which bridge to use
    uint32 chainId;       // destination chain ID
    bytes32 destination;  // recipient’s address on the dest chain
    bytes payload;        // arbitrary data to deliver
    bytes extra;          // bridge-specific extra data
    bytes32 sender;       // sender encoded addr
}
```

In a nutshell: you call `send(...)` with a `Message`, pay any required fee and if the chosen bridge is supported the router emits `MessageBroadcasted`; otherwise it reverts with `UnsupportedBridgingRoute()`.


# LayerZero Router

This `LzRouter` contract is a LayerZero-powered implementation of the `Router` contract that lets users send and receive arbitrary payloads across supported chains. It extends LayerZero’s `OApp` base to:

1. Map between standardised chain IDs and LayerZero EIDs
2. Send messages via LayerZero (using the option `Bridge.LAYERZERO`)
3. Estimate the native fee required for a given cross-chain call
4. Receive incoming LayerZero messages and dispatch them to a target contract Implementing a `onMessageReceived` hook

{% @mermaid/diagram content="sequenceDiagram
participant SourceContract
participant LzRouter(A)
participant LzRouter(B)
participant DestContract

```
SourceContract->>LzRouter(A): send(message)
LzRouter(A)-->>LzRouter(A): revert if chain unsupported
LzRouter(A)->>LzRouter(B): relay message
LzRouter(B)-->>DestContract: Invoke onMessageReceived method
```

" %}

***

#### Events

| Event             | Parameters                                                                      | Description                                                                             |
| ----------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `LzEidUpdated`    | <p><code>uint32 indexed chainId</code><br><code>uint32 indexed lzEid</code></p> | Emitted whenever the owner sets or updates the mapping for a chain’s LayerZero EID.     |
| `MessageRoutedLz` | `MessagingReceipt msg`                                                          | Emitted after successfully sending a LayerZero message; includes the LayerZero receipt. |

***

#### Errors

| Error                        | When It’s Thrown                                                                    |
| ---------------------------- | ----------------------------------------------------------------------------------- |
| `UnsupportedLzChain()`       | In `_sendWithLz`, if no LayerZero EID has been configured for the target `chainId`. |
| `UnsupportedBridgingRoute()` | In `send()`, if the caller specifies any bridge other than `Bridge.LAYERZERO`.      |


# Axelar Router

This `AxRouter` contract extends the `Router` contract functionality plugging in the Axelar network to send and receive arbitrary cross-chain payloads. It extends the router to:

1. Map a standardised `chainId` to Axelar chain name as string
2. Set the Axelar-powered peer router address on each remote chain
3. Receive incoming messages and dispatch them to the correct smart contract.

{% @mermaid/diagram content="sequenceDiagram
participant SourceContract
participant AxRouter(A)
participant AxRouter(B)
participant DestContract

```
SourceContract->>AxRouter(A): send(message)
AxRouter(A)-->>AxRouter(A): revert if chain unsupported
AxRouter(A)->>AxRouter(B): relay message
AxRouter(B)-->>DestContract: Invoke onMessageReceived method
```

" %}

***

#### Events

| Event               | Parameters                                                                                                                   | Description                                                                                   |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `PeerRouterUpdated` | <p><code>uint32 indexed chainId</code><br><code>string indexed oldRouter</code><br><code>string indexed newRouter</code></p> | Emitted when the owner changes which Axelar contract your router will call on a given chain.  |
| `AxChainStrUpdated` | <p><code>uint32 indexed chainId</code><br><code>string indexed axChainStr</code></p>                                         | Emitted when you set or update the Axelar‐chain name corresponding to your numeric `chainId`. |
| `MessageRoutedAx`   | —                                                                                                                            | Emitted immediately after dispatching a payload via Axelar’s gateway.                         |

***

#### Errors

| Error                  | When It’s Thrown                                                                                                                                            |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `UnsupportedAxChain()` | The chain isn't supported by the router.                                                                                                                    |
| `InvalidPeer()`        | If there is no peer router to send the message to for the specific chain OR if the incoming `sourceAddress` doesn’t match the owner-configured peer router. |


# NullRouter

This **NullRouter** is the simplest `Router` implementation, it doesn’t bridge at all but simply routes messages on the same chain. It immediately delivers the payload to the target contract, otherwise it rejects the call.

All routers support the null route, allowing integrators to also have access to same-chain routing.

{% @mermaid/diagram content="sequenceDiagram
participant SourceContract
participant NullRouter
participant DestContract

```
SourceContract->>NullRouter: send(message)
NullRouter-->>NullRouter: revert if message.chainId != block.chainid
NullRouter-->>DestContract: Invoke onMessageReceived method
```

" %}

***

#### Events

| Event                | Parameters        | Description                                                                                    |
| -------------------- | ----------------- | ---------------------------------------------------------------------------------------------- |
| `MessageBroadcasted` | `Message message` | Emitted when a valid same-chain message is delivered; mirrors the interface’s broadcast event. |

***

#### Errors

| Error                        | When It’s Thrown                                                       |
| ---------------------------- | ---------------------------------------------------------------------- |
| `UnsupportedBridgingRoute()` | If `message.chainId` ≠ `block.chainid`, i.e. it is a cross-chain call. |


# AxLzRouter

A router contract that supports both LayerZero and Axelar. It can be seen as a merge of the two.


# Solvers

The backbone of iLayer is its network of solver bots that pick up orders and fill them cross-chain, in a competitive way with other bot operators to ensure the best price to the user.

#### **Internal order list**

The bot essentially watches orders created on the several `OrderHub` , those filled on the `OrderSpoke` and the incoming requests over the RFQ channel. Combining these two, it can create a list of active orders and fill the ones available:

* the RFQ ones accepted and sent back signed by the user
* the ones on the Hub where the primary filler deadline has expired and that haven't been filled on the corresponding Spoke

#### **How filling an order works**

Solvers maintain only a numeraire token as their balance, ideally a stablecoin like USDC or USDT. Any order is then consolidated into this balance.

For example, filling a multi-token order that wants WETH and WBTC and gives SHIB will be executed in this way: &#x20;

1. a multi-call transaction is executed, containing:
   1. the numeraire token swap into WETH and WBTC according to the required amounts
   2. the order filling on the Spoke
2. on the Hub, the incoming SHIB is swapped into the numeraire token, consolidating the balance into the origin chain.

The bots will then easily rebalance their numeraire token cross-chain to maintain correct ratios depending on volumes.


# Industries

<details>

<summary><strong>DeFi protocols (dexes, perps, marketplaces)</strong></summary>

With a simple intent and a quick integration, one can add multi-token swaps and bridging, cross-chain rebalancing, NFT minting with full gas sponsorship

</details>

<details>

<summary><strong>Wallets</strong></summary>

Offer a chain-abstracted user experience, easily and cheaply consolidate portfolio across different chains or ape in the new L1/L2 just launched.

</details>

<details>

<summary><strong>AI Agents</strong></summary>

Encode any web3-based action into a simple intent and offload the complexity of executing it to the iLayer solver network

</details>


# EVM Smart contracts

## The Order Intent

Fundamentally, the entire iLayer network revolves around the Order intent, a struct that can encode pretty much any action you could perform on-chain.

```solidity
struct Order {
  bytes32 user;
  bytes32 recipient;
  bytes32 filler;
  Token[] inputs;
  Token[] outputs;
  uint32 sourceChainId;
  uint32 destinationChainId;
  bool sponsored;
  uint64 primaryFillerDeadline;
  uint64 deadline;
  bytes32 callRecipient;
  bytes callData;
  uint256 callValue;
}
```

We use **`bytes32`** for what in EVM would be an `address` to ensure compatibility cross-chain. You will find a handy conversion utility library called **`BytesUtils`** in our codebase to assist you with converting from `address` to `bytes32` as simple as calling`BytesUtils.addressToBytes32(address).`

The **user** is the order signer, and the one from which the input tokens will be transferred from. The **recipient** is who will receive the tokens in output in the destination chain.

For both a smart contract account and an EOA, the order creation step will have to be preceded by a token approve transaction. We support multiple input tokens, encoded as follows

```solidity
enum Type {
  NULL,
  NATIVE,
  FUNGIBLE_TOKEN, // ERC20
  NON_FUNGIBLE_TOKEN, // ERC721
  SEMI_FUNGIBLE_TOKEN // ERC1155
}

struct Token {
  Type tokenType;
  bytes32 tokenAddress;
  uint256 tokenId;
  uint256 amount;
}
```

Token structs are identical for both inputs and outputs, we assume a non-zero array in input and a possibly null array as output. The token outputs data can be obtained by querying the RFQ network and picking the preferred quote, usually based on a combination of gas cost and pricing.

"Native" refers to the blockchain native fee token, in the case of EVM Ethereum.

> The `tokenId` field is optional for ERC20

The RFQ will also return the filler param, that binds the order to the picked solver to ensure the correct execution of the received quote. If the solver doesn't fill the order within the defined `primaryFillerDeadline`, then any solver in the network can pick and fill it. For this reason it is very important to correctly choose this parameter. Finally, the `deadline` is the order deadline, a time after which no solver will pick the order and the user can withdraw it and the related funds from the Hub.

The chain identifier (**`chainId`**) can be found on [this website](https://chainlist.org/).

If the order is marked as **`sponsored`** (sponsored ⇒ true), then the filler will execute the order creation and cover for the entire blockchain fees, usually by adding a premium to the quote to recoup the tx gas cost.

The last three parameters are optional, if not needed they can be filled with null values and essentially allow to call an arbitrary smart contract with an arbitrary call data.

```solidity
bytes32 callRecipient; // destination address
bytes callData; // on EVM: abi-encoded selector + arguments
uint256 callValue; // (optional) any value to pass along
```

This **execution** **hook** feature can be very useful to execute DeFi actions with orders or to encode complex interactions. Ideally, an order could not have any output token but simply pay for a cross-chain code execution.

**We block reentrant calls for security reasons!**

### **Order status**

iLayer operates as an on-chain orderbook, that means orders can be recorded on the book in a *pending* state until they are either filled or expired. The contract exposes two deadlines

* `maxOrderDeadline` the maximum value for an order TTL (time to live)
* `timeBuffer` time after an expired order can be withdrawn. This is needed to prevent the attack where an order is filled exactly at the expiration date but, due to the cross-chain message relay time, the user can withdraw the order and rug the solver.

If `time now > order deadline + time buffer` then the order can be withdrawn (if it hasn't been filled yet) and tokens returned to the user.

## Create an order

To add a new order to the iLayer network you need to get the [address](https://docs.ilayer.io/deployments) of the Hub contract of the source chain. Then you will need to craft the order request, the ERC2612 gasless token permits (optional) and pass the order signature.

```solidity
function createOrder(
  OrderRequest memory request,
  bytes[] memory permits,
  bytes memory signature,
  IRouter.Bridge bridgeSelector,
  bytes memory extra,
)
  external
  payable
  nonReentrant
  returns (bytes32 orderId, uint64 orderNonce)
```

The **`OrderRequest`** is as follows

```solidity
struct OrderRequest {
  uint64 deadline;
  uint64 nonce;
  Order order;
}
```

It features an incremental nonce, that doesn't need to be consequent with the previous nonce used but just bigger, the request deadline after which the order won't be created anymore and finally the order itself.

It's important to store the `orderId` and the `orderNonce` as they are useful to withdraw the order or track its status.

The `Bridge` param is an enum that depends on the chain and user bridging choice, see [Router](https://docs.ilayer.io/router) page for more.

## Withdraw an order

```solidity
function withdrawOrder(Order memory order, uint64 orderNonce) external nonReentrant
```

Simply passing the order struct and the nonce will allow the user or the smart contract account to take back funds from the Hub if the order expired. We add a small time delay to avoid the possibility of solvers filling the order and users withdrawing funds at the same time.

The order delay is more or less equal to 1 block time.

## Fill an order

To fill an existing order we need to interact with the corresponding `OrderSpoke` contract on the destination chain, refer to [this page](https://docs.ilayer.io/deployments) to find the correct address.


# Example: cross-chain LPing on Aave

Lets imagine we want to bridge and provide liquidity in USDC on Aave v3. We can set aUSDC (the LP token of the Aave USDC market) as the output token in the order struct and call the OrderHub on the source chain.

```json
{
  sourceChainId: "8453", // Base
  destinationChainId: "42161", // Arbitrum
  inputs: [
    // WETH
    { tokenType: "FUNGIBLE_TOKEN", tokenAddress: "0x0000000000000000000000004200000000000000000000000000000000000006", tokenId: "0", amount: "10000000" }
  ],
  outputs: [
    { tokenType: "FUNGIBLE_TOKEN", tokenAddress: "0x...", tokenId: "0", amount: "9000000" }
  ],
  ...
}
```

The solvers will then pick up the order and obtain the relevant tokens by staking on Aave.


# Example: cross-chain contract call

We need to call a dummy contract that exposes the following function

```
function setValue(uint256 value) external;
```

We need to craft an order that contains calldata for this specific function, starting from the calldata

```
bytes4 selector = bytes4(keccak256("setValue(uint256)"));
bytes memory callData = abi.encodePacked(selector, newValue);
```

then the order itself

```json
{
  sourceChainId: "1", // Ethereum Mainnet
  destinationChainId: "137", // Polygon Pos
  inputs: [
    // WETH
    { tokenType: "FUNGIBLE_TOKEN", tokenAddress: "0x0000000000000000000000004200000000000000000000000000000000000006", tokenId: "0", amount: "10000000" }
  ],
  outputs: [],
  callRecipient: "0x0...", // the contract address
  callData: callData,
  callValue: 0,
}
```


# Deployments

## EVM **Smart Contracts**

**OrderHub**

```
0x123
```

**OrderSpoke**

```
0x456
```

## Supported chains

<table><thead><tr><th width="381.94921875">Chain name</th><th data-type="number">EID</th></tr></thead><tbody><tr><td>Ethereum mainnet</td><td>1</td></tr><tr><td>Base</td><td>8453</td></tr><tr><td>Polygon</td><td>137</td></tr></tbody></table>


# Audit

Security is a core pillar of iLayer. We are committed to maintaining a high standard of safety and reliability across all protocol components. To support this, we conduct independent third-party audits to review and validate our smart contracts and integrations.

Below is the first completed audit, focused on our integration with LayerZero.

#### [**View Audit Report** ](https://github.com/abarbatei/audits/blob/main/reports/solo-audits/iLayer_x_ABA_LayerZero_Integration_Audit_Report-v1.1.pdf)

### Ongoing Security Reviews

This is the first in a series of audits planned for iLayer. As the protocol expands, we will continue to engage external auditors to ensure the integrity and resilience of our infrastructure.


