Docs

Discover how Phala's AI Agent Contract offers the essential tools to develop and profit from intelligent applications.

Explore Now

InDEX Decoded: The Multi-chain Intent Model

2023-12-15

Introduction

The concept of "intent" in web3 is a novel and evolving idea, currently without a set definition. This early-stage innovation is relevant for Phala Network as it spearheads the development of inDEX, a platform designed to interpret and fulfil these intents in a decentralized environment.

This article will explore how inDEX, at the forefront of this technology, is navigating the uncharted waters of intent-based solutions. An intent-centric infrastructure in the blockchain ecosystem, which identifies the best trading prices across liquidity pools on multiple chains, ensuring MEV protection, and preserving user privacy.

Intent: What It Is & Why It Matters

A New Paradigm Beyond Transactions

Traditionally, a transaction represents user requirements - for instance, when a user transfers 1 USDC to another user, we construct the transfer calldata and broadcast it to the blockchain. However, distinct chains and unique dApps entail various transaction data specifications, signature types, validation logic, and interfaces - a massive challenge for both users and applications like wallets.

Therefore intent applications offer an innovative approach to depict user requirements across the blockchain industry. It frees users from concerning themselves with underlying intricacies such as choosing a DEX for swapping ETH to BTC or determining the suitable bridge for moving BTC from the Ethereum to Bitcoin networks.

Intent in Action: A Simplified Example

A simple `Intent` is typically represented as follows:

{
	"amount": "1 ETH",
	"input": "Ethereum/ETH",
	"output": "Bitcoin/BTC"
}

Intent holds value only when it can be effectively executed by any entity (known as solvers). This compatibility enables an open solver system capable of resolving `Intent` based on individual interests. It's noteworthy that `Intent` doesn't necessarily require conventional solutions. For instance, another user might have the following `Intent`, presuming 1 ETH equals 0.1 BTC:

{
	"amount": "0.1 BTC",
	"input": "Bitcoin/BTC",
	"output": "Ethereum/ETH"
}

These two Intents can be aligned in such a way that we facilitate a direct match between them, potentially leading to a more advantageous outcome compared to executing the trade individually on a DEX.

On-chain & Off-chain Strategies

Addressing the `Intent` of these two users could be implemented in a variety of ways, primarily categorised as on-chain and off-chain strategies:

1) On-chain: this method is the traditional path, essentially mirroring the process a user would have to undertake manually. For this approach, the likely steps involved would be:

Send 1 ETH to Uniswap
Receive 0.1 WBTC from Uniswap
Bridge 0.1 WBTC From Ethereum to Bitcoin Network
Receive 0.1 BTC on Bitcoin Network

Though logical, this method lacks capital efficiency. Users must pay an additional fee for the swap and may also suffer from slippage.

2) Off-chain: an alternate, more effective strategy involves off-chain matching of users' `Intent`, transforming the plan to:

User A sends 1 ETH to smart contract
User B sends 0.1 BTC to an escrow account
Unlock 1 ETH to User B's address from the smart contract
Unlock 0.1 BTC to User A's address from the escrow account

Notably, the steps above could occur synchronously within a single transaction on both chains. This introduces more complexity in a cross-chain scenario, which we will delve into in later sections.

Off-Chain Complexity: Trust & Fairness

Transferring `Intent` matching to off-chain also presents hard-to-tackle problems. Despite assuming that the smart contract is fair, the involvement of an escrow account raises trust issues.

Furthermore, how can we determine if the off-chain order matching engine is providing the best prices for both sides? Some current projects operate their off-chain order matching in a centralized manner. However, this aspect requires trustlessness, transparency, and privacy protection. This is one of the key areas where inDEX truly excels and distinguishes itself.

InDEX: What Is It? Why Build It?

InDEX: The Protocol & the App

1) InDEX Protocol: an intent-centric platform (still in beta) that understands and meets user needs. Users are able to submit their intents or create intent-centric apps using its infrastructure. For more information on how InDEX protocol can be used, please refer to the 'Potential Use Cases with InDEX' section.

2) InDEX App: a front-end application (its preview is now live) that allows users to seamlessly interact with the inDEX protocol. Through this app, users can clearly express their intentions, prompting the inDEX protocol to create a tailored execution plan. A concise demo is available below for an initial overview, and for a more comprehensive understanding, you are invited to explore further on the inDEX website.

Optimising Intent-Centric Trading

InDEX finds the best trading prices across multi-chain liquidity pools, boosting trading efficiency and potential profits by optimising transaction values. It also provides strong MEV protection and maintains user privacy. Uniquely, inDEX also handles transactions across many blockchains.

Phala Network: The Force Behind InDEX

The complexity and subpar user experience often encountered in blockchain, particularly in cross-chain operations, are well-known issues. Phala Network has been at the forefront of leveraging off-chain technology for solving intricate on-chain problems. By integrating Phat Contract into inDEX, Phala has created the first trustless intent execution layer, solving intents without dependence on any particular entity and thus boosting security.

InDEX & Phat Contract

InDEX ensures trust and preserves privacy by utilising Phala Network's innovative off-chain programming model Phat Contract. While Phat Contract shares some similarities with other smart contract models like Solidity, it is distinguished by two key advantages:

  1. Http requests: smart contracts, through Phat Contract, can now connect to the internet for blockchain RPC transmissions and external HTTP requests, like fetching token prices. These connections are secured by SGX hardware-equipped workers registered on the Phala network, keeping their private keys confidential within the SGX environment. The diagram below illustrates 'E' for encryption and 'D' for decryption processes.
  1. Off-chain computation: the smart contract operates off-chain, executed by a single worker each time, unlike the typical approach where all workers are involved. It engages all validators of parachains only for contract state changes. For a detailed explanation of Phat Contract's operation, please check our latest documentation.

Therefore, empowered by Phat Contract, inDEX will be the first protocol seamlessly functions as a chain-agnostic intent execution layer. We envision a near future where users of the inDEX App can effortlessly fulfil their Web3 intents, much like using Google search to navigate the Web2 world.

Overcoming Multi-Chain Hurdles & Liquidity Silos

InDEX: Streamlining Cross-Chain Operations

In the current crypto landscape, every blockchain ecosystem operates in isolation, similar to a solitary island. Every blockchain has its unique consensus protocols, transaction validation methods, and API interfaces. Liquidity exists within these distinct ecosystems, making seamless movement a challenge.

InDEX steps in to construct a chain-agnostic layer that provides unified interfaces for users and applications to express `Intent`. For this purpose, we've abstracted representations of account, asset, and chain themselves, enabling cross-chain identification.

Chain Information

A `Chain` in inDEX consists of the following information:

  1. Name: also recognized as ID, it is used when the solver generates a solution.
  1. BalanceFetcher: this module fetches the asset balance from the blockchain. Different blockchain platforms might have varied RPC interfaces.
  1. Gateway/EntryPoint: this smart contract is deployed on every blockchain we support, acting as an entry point to create and settle user Intents.
  1. TxIndexer: this off-chain indexer tracks the result of transactions sent by the inDEX Executor.
The Gateway contract serves two main purposes:
1. User submitted Intents: it provides an interface for users to create their `Intent` on-chain. User assets are temporarily transferred from their account to the contract.
2. Intent settlement: it settles every operation within the Intent Step occurring on the chain. The operation could be a swap call on a DEX or a bridge call with a specific bridge contract. More details will be provided in the Intent execution section.

Accounts & Assets Across Multiple Chains, Bridges, & DEXs

Account representations vary across chains. Essentially, in the blockchain realm, user accounts are derived from a key pair, with addresses encoded using different mechanisms from the public key. For instance, an Ethereum account has a fixed length of 20 bytes, while on a Substrate-based chain, it could be a 32-byte sr25519 public key or others.

InDEX abstracts the account as dynamic bytes, converted according to the current blockchain's context. It's beneficial when inDEX workers (an account derived in Phat Contract, not the SGX worker in Phala Network) submit transactions on different chains using the same private key on behalf.

Therefore addressing assets presents a different challenge. You cannot use a single format to represent assets across multiple blockchains. An asset is usually represented through an asset address, such as an ERC20 contract address deployed on EVM chains.

However, interaction with the blockchain requires considering additional asset information like symbols and decimals. More significantly, an asset should be bound to a specific blockchain. For instance, `USDC` on Ethereum and `USDC` on Moonbeam are different assets, despite appearing identical to users and possibly having the same contract addresses on the chain. This differentiation is necessary for identifying which assets are supported by a bridge.

Based on this principle, a bridge operation in inDEX can be depicted as:

{
	"bridge": "Wormhole",
	"spendAsset": "Ethereum/USDC",
	"receiveAsset": "Moonbeam/USDC"
}

What Are Actions & Solutions?

Within inDEX, an `Action` refers to the implementation of a specific on-chain operation. This operation could be a swap operation on Uniswap, or a bridge operation with a bridge. An Action contains a name, used as an ID in `Solution`. `Action` accepts a set of arguments as input, constructing the calldata that will be submitted to the blockchain for execution when the `Intent` gets executed.

Now, let's create a `Solution` that represents the `Intent` of initially swapping WETH to USDC on Ethereum, then bridging USDC from Ethereum to Moonbeam. Following the principles outlined earlier, it would look like this when represented as a JSON object:

[
	{
		"action": "uniswap",
		"spendAsset": "Ethereum/WETH",
		"receiveAsset": "Ethereum/USDC",
	},
	{
		"action": "wormhole_bridge",
		"spendAsset": "Ethereum/USDC",
		"receiveAsset": "Moonbeam/USDC",
	}
]

Please note, a complete `Solution` would be more intricate; the example above is intended for illustrative purposes only.

How We Achieve The Best Prices Across Multiple Chains

Pursuing the Optimal Amidst the Impossible

Securing the best price is crucial for traders, especially in large block trades. However, achieving this in cross-chain scenarios is near impossible due to the inherent difficulty in specifying transaction timing (although it can be conditioned) when an Intent is executed across multiple chains.

Compare this to solving `Intent` on a single chain: once the price on the source chain meets the set conditions, the transaction can be executed, and you obtain the desired liquidity change on the DEX. However, in cross-chain solving, there's no guarantee when operation execution can happen on the second chain. While a bridge may offer a time estimate, it's not 100% accurate, and the liquidity may already have shifted on the other chain during this wait time.

We must account for these extreme cases in inDEX’s system design. However this certainly doesn't leave us without ways to tackle these challenges.

What We've Incorporated into InDEX's Default Solution Provider

Achieving the best price on a multi-chain ecosystem is somewhat similar to securing the best price on a single chain. The objective is to maximise the output amount for each single step of the `Intent`. For now, inDEX aims to identify the best trading prices across multiple DEXs on numerous chains.

The diagram below explains a setup where more than one DEX (AMM based) exists on Ethereum, supporting a swap from asset X to asset Y, and more than one DEX (AMM based) exists on Moonbeam, enabling a swap from asset Y' to asset Z, with a bridge having a bridging pair Y-Y' between Ethereum and Moonbeam.

Given that each DEX will have slippage (unavoidable due to the fundamental formula k = a*b used by AMM), the larger the relative amount you trade with the liquidity, the more slippage you will incur. The diagram below suggests that we should aim to go from point A -> B, instead of A -> B'. Therefore, we should split the swap amount across different DEXs according to each DEX's current liquidity.

For instance, if a user spends 100 X on Ethereum to get Z on Moonbeam, instead of swapping the entire 100 X on Ethereum/D1, it's divided according to the liquidity of X, where D1:D2 is 2:5, so D1 gets 20 to swap, and D2 gets 50 to swap. Applying the same mechanism, suppose we ultimately get 200 Y on Ethereum and swap it to Z on Moonbeam with Y'.

Future Plans: Off-Chain Order Matching

Decentralized off-chain order matching doesn't exist in the initial version of inDEX but will be incorporated in future versions.

The diagram below illustrates a typical setup where instead of conducting a direct swap on the DEX, the market maker provides a matching price as the counterparty to the user's order. The Intent executor's task boils down to constructing transaction data and submitting it for execution.

This process is atomic and avoids slippage problems as assets are temporarily transferred to the settlement contract and sent directly to the counterparty within the same transaction. What's more, due to the price is fixed, this approach is anti-MEV naturally.

Implement Off-Chain Order Matching in A Trustless Way

However, the reality is that, in the short term, it's challenging to fully decentralize off-chain order matching and ensure trustlessness while protecting user privacy simultaneously.

Therefore, mechanisms to guarantee each party gets a fair price, including the market maker, are crucial. Projects like UniswapX attempt to address these issues by introducing Dutch Auction (A common solution used in NFT sales, fee setting, etc).

Solver & Solution

As the `Intent` concept is still in its early stages (at the time of writing this article), there isn't a standard for what a `Solver` should do or what format a `Solution` should adhere to. Projects like Essential and Anoma are striving to achieve that. Considering that inDEX is more focused on cross-chain Intent solving and based on Phala's off-chain technology, significant differences exist between it and other Intent-centric projects.

Distinctions Between an InDEX Solver & Other Solvers

Typically, a `Solver` acts as a counterpart to a user Intent order and provides the solution in accordance with the user's Intent. In UniswapX, an array of solvers bid with their solutions through a Dutch Auction, and the winner's solution gets the right to be executed. However, not all projects offer an auction mechanism. Some are centralized, with algorithms running on the backend choosing the best price for the users.

However, the concept of `Solver` in inDEX is a bit different. As mentioned earlier, the decentralized off-chain order matching is targeted to launch later. Currently, the initial MVP of inDEX focuses on finding the best trading price across multiple DEXs on multiple chains.

Essentially, one can consider the inDEX solver to consist of

1) InDEX Executor: powered by Phat Contract and running in Phala's off-chain network, guarantees trustlessness and decentralization

2) InDEX Solution Provider: an algorithm that calculates the best trading and routing solution across multiple DEXs and chains it observes.

It's worth highlighting that the inDEX protocol is designed as permissionless from the beginning, allowing anyone to run their own solution provider and submit their solution to the inDEX executor for execution.

Required Interfaces For A Solver

At a basic level, a solver should provide two interfaces: one for intent submitting and one for future solution queries.

1) Intent submission: for this, a solver needs to provide a POST REST API (sort of application programming interface) to submit intent data, e.g., inDEX's default solver provider. Intent data should be passed as arguments along with the POST request, and `Solution` along with solver's signature should be returned as part of the response.

2) Intent query: the solver should provide interfaces that the inDEX executor can use to query the solution data based on a given identification during the Intent execution. This should return the `Solution` and its signature.

Solution Specifications

At its core, the solution should detail the operations to be executed, the input asset, and the output asset. It's crucial to note that an asset is always linked to a specific chain.

Additionally, conditions should also be included in the solution. This can be useful for users to set expectations, such as the minimal output amount for a swap operation.

Based on this principle, the basic `Solution` should contain several pieces of information, like below (which we call `Step`):

Step
	- Action
	- Spend amount
	- Source chain
	- Input asset
	- Destination chain
	- Output asset
	- Condition
	- Minimum output
	- Expiry time

Solution
	- Array(Step)
	- Solver account
	- Solver expected reward

How InDEX Resolves Intents

InDEX is designed to function as a generic Intent execution engine, which means it's not limited to asset trading, but can perform generic operations as well. While currently, it only supports bridge and swap operations, it's set to broaden its range.

To resolve an intent, as a protocol, inDEX should first be able to interpret the user intent data. We have designed a simple intent expression that's adequate to accommodate most of our use-cases before a standard is established.

Not every intent will find a solution, similar to how a Google search doesn't always yield an answer. However, by expanding support to more chains, DEXs, and bridges, we increase our capability to resolve a greater number of intents

Intent Representation

At the start of this article, we mentioned that an intent could be simplified with the following JSON:

{
	"amount": "1 ETH",
	"input": "Ethereum/ETH",
	"output": "Bitcoin/BTC"
}

This representation is adequate for a user if no condition is set. However, in practical applications, the effectiveness of any intent-based system, including its overall design, often requires an intent to encompass more detailed information.

In inDEX, when sending `Intent` to the Gateway contract on the source chain (currently we only support submitting `Intent` via transaction, off-chain signing like CowSwap and UniswapX will be supported in the near future), additional information will be required. A complete version can be represented as follows (fungible asset only, expressed by field-type):

{
	spendAmount: U256,
	sourceChain: string,
	spendAsset: bytes,
	destChain: string,
	receiveAsset: bytes,
	worker: bytes,
	id: byte32
}

Condition setting will be added once we lend support to it. These data will be saved to the Gateway contract when a user creates an `Intent`, and will be deleted when the `worker` assigned to execute the Intent in the future claims the `Intent` task from the Gateway contract.

Building Call According to Solution

The `Solution` contains several `Step`s, each one correlating with a specific on-chain operation. Taking the Solidity implementation in the EVM chain as an example, in other words, it's a smart contract call. Here we introduce the `Call` object defined as follows (Solidity object). Apart from the basic information like `calldata` and `target` smart contract address, crucial for `Call` operation with Solidity contract keywords at the context of Gateway contract, it also houses other necessary information.

struct Call {
	address target;
	bytes callData;		
	bool needSettle;
	// some other metadata
	...
}

We won't delve into more details in this article, but basically, the extra information is used to facilitate the on-chain settlement.

Parallel Execution by Multiple Workers

As we pointed out earlier, when a user submits their Intent to inDEX, the worker to be allocated is already specified in the Intent. Each worker only run one Intent task at a time. In case there are too many tasks submitted, the Gateway contract has an Intent Queue to schedule the task execution in the future.

InDEX supports multiple workers. The `Worker` account private key is derived from the Phat Contract, which is created when deploying the Phat Contract, and never revealed externally in the whole lifecycle, secured by Phala's Distributed Key Management system. In the first version, we plan to set up to 10 workers, and in the near future, it should accommodate more, e.g. 100 workers, depending on the level of the demand. The number of workers represents the throughput of the entire system, i.e., the number of `Intents` that can be executed simultaneously.

The execution of each step is idempotent to facilitate concurrency control in the highly complex async and distributed cross-chain environment. During the Intent task initialization, we allocate each step a distinctive account nonce on the blockchain that the transaction will happen on. The nonce is unique to the worker account and is tied to the step. No matter how many times the engine submits the transaction to execute the step, the nonce for this step remains constant. We refer to this as the idempotent execution module.

Gateway Contract & On-chain Settlement

The Gateway contract in the inDEX protocol serves as an settlement contract on every blockchain we support (for blockchains that support smart contracts only) and is responsible for managing user Intent requests, storing Intent data, and temporarily holding user asset.

Use Cases and Inspiration

Besides the official cross-chain swap DApp, the inDEX SDK also enables developers to build a variety of applications. Here, we list some potential use cases that we envision being built. We also look forward to hearing more innovative ideas from the community.

1. Customized Cross-chain Swaps

While the inDEX protocol provides interfaces to submit `Intent` and execute it, by customizing your solution instead of using the one offered by our provider (an off-chain module), you can easily create a cross-chain swap application with your own preference or customized logic. For instance, envision building a cross-chain swap between Ethereum and Moonbeam; you could customize the solution with the following actions (for illustrative purposes only):

[
	{
		"action": "uniswap",
		"spendAsset": "Ethereum/SOURCE_ASSET",
		"receiveAsset": "Ethereum/USDC",
	},
	{
		"action": "wormhole_bridge",
		"spendAsset": "Ethereum/USDC",
		"receiveAsset": "Moonbeam/USDC",
	},
	{
		"action": "stellaswap",
		"spendAsset": "Moonbeam/USDC",
		"receiveAsset": "Moonbeam/DEST_ASSET",
	}
]

You can submit this solution to the inDEX executor through the SDK.

In this example, you need to ensure a trading pair of `SOURCE_ASSET-USDC` exists on Uniswap and a trading pair of `USDC-DEST_ASSET` exists on Stellaswap (a DEX deployed on Moonbeam).

2. One-click + XYZ

InDEX isn't confined to bridge or swap operations. It offers a generic operation framework, though you should still consider your specific needs, as it's deeply related to the services' interfaces. Here are some general use cases:

  • Cross-chain Staking: suppose you're building a staking service on ChainA and want users on ChainB to onboard. Integrating inDEX into your UX workflow will allow for a smooth onboarding experience by providing a 'one-click' button on your interface, enabling asset bridging from ChainB (you can customize the solution to combine swap + bridge).
  • Social App Asset Transfer: the growing Web3 social sphere requires users to send assets to anyone conveniently. With inDEX, it’s possible to build a on-click solution to send money to your friend in a chat app, no matter where your token is and where it will go.

3. Multi-chain Asset Management tools

People in Web3 always struggle with the fragment of their assets which may distributed in many chains, they are eager to have a tool can help them aggregate their assets to a specific chain, especially for users with small amounts of tokens scattered across various platforms. In Web2, countless utility tools assist users in accessing data from the internet effortlessly. Yet, in Web3, such tools are sparse due to the isolation between chains and liquidity fragmentation. Even small, helpful tools often go unnoticed by developers.

Conclusion

In the rapidly evolving landscape of decentralized finance, achieving the best-price execution across different chains presents a challenging frontier that many projects are striving to conquer. As a robust, generic Intent execution engine, inDEX enables seamless asset trading and a host of generic operations across multiple chains, all while ensuring trustless and decentralized execution.

Explore inDEX further:

About Phala

Phala Network is a decentralized cloud that offers secure and scalable computing for Web3.

With Phat Contracts, an innovative programming model enabling trustless off-chain computation, developers can create new Web3 use cases.

Get the latest Phala Content Straight To Your Inbox.