APES Application Preferred Execution Sequencing

We are excited to share APES, a proposal that lets applications on Monad express preferences over the order of the transactions that interact with them, without giving up composability. For a high-level overview with examples, see our blog post. The full specification document contains additional details regarding the attacks and the theoretical guarantees, and is available here. We welcome discussion and feedback from the community.

APES: Application-Preferred Execution Sequencing

Status: Draft (v1: design and architecture; some implementation details still open)

Authors: Andrea Canidio, Andrei Constantinescu, Lioba Heimbach, Haythem Sellami

Contents

  1. Motivation
  2. Summary
  3. APES in detail
  4. Attacks and guarantees
  5. Extension: multiple applications within a contract
  6. Backward compatibility
  7. Conclusion

1. Motivation

Many applications want their transactions to execute in a specific order. For example, a PropAMM wants its oracle update to execute before any swap, and an order book wants cancellations of limit orders to execute before market orders. An on-chain auction, on the other hand, wants bids to execute from highest to lowest. However, the ordering of transactions is constrained by the underlying blockchain, so an application with ordering requirements must either find a chain whose default rule happens to match its needs or create its own app-chain (or rollup, or off-chain sequencer), trading off composability.

To overcome this trade-off, we make use of unanimity override: an algorithm that produces a global execution order from the applications’ stated preferences over the order of their transactions. Whenever all the applications with a stake in two transactions agree on their relative order, the protocol respects that agreement, unless the resulting unanimity relation has cycles. If cycles are present, a fallback rule breaks them through a process called demotion, and the default order (e.g., the priority-fee order) completes the resulting partial order into a total execution order. Check out our previous post for more details.

This post presents a concrete implementation proposal for unanimity override on Monad, which we call Application-Preferred Execution Sequencing (APES).

2. Summary :light_bulb:

APES has four parts:

  1. Interaction declaration. Transactions that want to access one or more applications with registered ordering preferences must carry a static declaration, similar to Solana’s per-transaction account lists. The declaration lists all applications with registered ordering preferences that the transaction may access and, for each, the methods and parameters these applications need in order to compute their preferences over the transaction.
  2. Preference registration. Applications express their preferences by registering them in a precompile. Preferences are represented by a function that produces a score for each transaction that has statically declared that application.
  3. Protocol-controlled ordering. The protocol computes the execution order from the scores, using unanimity override.
  4. Execution check. At execution, each call is checked against the transaction’s declaration.

In this post, we describe each component of APES. We also discuss how a malicious actor could try to attack the system, derive the guarantees that the system provides, and recommend best practices for application designers and users. The companion blog post discusses how to use APES to design four applications with ordering preferences: a PropAMM, an order book, a cross-market batch exchange, and a liquidation auction. The full specification document contains additional details.

We need you! :index_pointing_at_the_viewer:

Before diving into the details, we would appreciate your feedback on two questions. Please keep them in mind as you read.

  • Is there an application with ordering preferences that does not fit our proposal? The preference semantics we propose aims to strike a balance between expressiveness and computational simplicity, and it supports all the use cases we considered. Other use cases may require different preference semantics.
  • Did we miss an attack? W describe different types of attacks and the guarantees that survive them. There may be other attacks we have not considered.

3. APES in detail

APES leverages the Multiple Concurrent Proposers (MCP) architecture of Cadence, the consensus protocol recently proposed for Monad. The reason is that, under MCP, no single party can censor a transaction, which APES assumes. Furthermore, APES computes the execution order during translation, a new step that takes as input a consensus block (i.e., the output of the consensus protocol) and outputs a block that can be executed. MCP itself and other upcoming features, such as encrypted transactions, also rely on translation.

Throughout, t and u denote transactions, A an application, m a method named by its four-byte selector, and v a declared parameter. Here, an “application” is a smart contract. Section 5 discusses an extension that allows several applications within one contract (for example, several markets).

3.1 Interaction declaration

A transaction t declares which opinionated applications it intends to access in its interaction_list, a new field covered by the signature. An opinionated application is one with ordering preferences in force (Sections 3.2 and 3.2.5). An interaction_list holds zero or more entries, and each entry specifies:

  • the address field: the address of an opinionated application, distinct across the entries of t;
  • the methods field: all methods that t may call on that application, among those for which the application registered preferences. Each method is named by its four-byte selector and appears at most once per entry;
  • a parameter field for each named method: an unsigned integer no greater than max_parameter, or empty. The upper bound lets the preference registry verify that every possible score fits fixed-width arithmetic (Section 3.2).

For example, consider a transaction that cancels a limit order on market A, while also placing a market order on the same market, declaring a value of v for that method. Such transaction carries the entry (A, [cancel: -, order: v]).

The meaning of a parameter is application- and method-specific. For example, the parameter can be an argument of the call. An auction that ranks bids from highest to lowest can use the bid amount as the parameter for its bid method. Similarly, an AMM that ranks swaps by fee can use the swap fee as the parameter for its swap method.

A parameter can also combine several arguments of the call. For example, an AMM that ranks swaps by the total fee they pay can use “swap fee × amount” as the parameter, where both are arguments of its swap call. Finally, a parameter can be unrelated to the call’s arguments altogether, such as the transaction’s priority fee or the sender’s balance of a given token.

Not every application expresses preferences, and an opinionated application may rank some of its methods but not others (an AMM may leave deposits and withdrawals unranked). A transaction that calls only unranked methods can carry an empty interaction list. Conversely, whenever a transaction may call a method that an application ranks, it must declare both the application and the method.

A transaction cannot declare the pseudo-method fallback(). If fallback() forwards to another contract’s method (as is common in proxy contracts), then the transaction declares that method’s selector. Whether transactions should be able to declare the pseudo-method receive() is still an open question (see the full specification document).

3.1.1 Transaction classes

The wildcard entry is a reserved entry declaring that the transaction may call anything. A transaction whose interaction list holds the wildcard entry is a wildcard transaction. All other transactions are declaring transactions. Note that this includes transactions with an empty interaction list.

Wildcard transactions can access every method of every application, but they are ordered after declaring transactions (Section 3.3). They are useful when specifying the full list would be impractical, for example for a swap that goes through a router.

A legacy transaction (one of the existing transaction types, which carry no interaction_list) is treated as a wildcard transaction.

3.1.2 Validity

A declaration is valid when it holds no entry, when it holds the wildcard entry and nothing else, or when all of the following hold:

  • Decoding: the list decodes into entries, each naming an application and a list of methods, and every non-empty parameter field decodes to a number no greater than max_parameter;
  • Size: the list has at most max_declared_applications entries, and each entry names between one and max_methods_per_application methods;
  • Uniqueness: no application appears in two entries, and no method appears twice in the same entry, so each named method corresponds to exactly one parameter field;
  • Registration: each entry names an application with a registration in force (Section 3.2.5), and only methods held by a clause of those preferences (Section 3.2.2).

Intrinsic gas

As with EIP-2930 access lists, the declaration is charged in the intrinsic gas of t: gas_per_declared_application per entry and gas_per_declared_method per method. The wildcard entry carries no charge, so that a legacy transaction and a transaction declaring the wildcard entry pay the same intrinsic gas.

3.2 Preference registration

Applications register their preferences, a list of clauses (Section 3.2.2), in a precompile at the reserved address PREFERENCE_REGISTRY:

struct Preference {
    Clause[] clauses;          // Section 3.2.2, or empty after a revocation.
    uint256 activationBlock;   // Block from which these preferences are in force.
}

function register(Clause[] calldata clauses) // Set the caller's preferences
    returns (uint256 activationBlock);       // (at least one clause).
function revoke()                            // Set the caller's preferences to none
    returns (uint256 activationBlock);       // (no clauses).

function getPreferencesOf(address app) view  // Preferences in force (if any), then pending
    returns (Preference[] memory);           // ones, ordered by activationBlock.

An application registers by calling register(clauses), which sets the preferences of the caller (msg.sender).

An application deployed behind an upgradeable proxy can adopt preferences without being redeployed at a new address. Instead, it only needs to upgrade to an implementation that implements isApesEnabled (Section 3.2.1) and has an admin-only function that calls register. Because the proxy runs this code via delegatecall, the registry sees the proxy as the caller and stores the preferences under the proxy’s address.

An application can call register again whenever it wants to update its preferences, or call revoke to remove them. Through getPreferencesOf, anyone can read an application’s preferences, both those in force and any pending ones: any modification to an application’s preferences takes effect after a delay of a few blocks (Section 3.2.5).

The precompile can only be invoked with a plain CALL, plus STATICCALL for its view functions. In particular, it rejects DELEGATECALLs.

3.2.1 Explicit opt-in

Applications that want to register preferences must enable APES explicitly by implementing a method:

bytes4 constant MAGIC_VALUE = bytes4(keccak256("isApesEnabled()"));
function isApesEnabled() returns (bytes4) { return MAGIC_VALUE; }

The registry precompile gates register() and revoke() to only such applications by asserting that isApesEnabled() == MAGIC_VALUE on the caller.

3.2.2 Clauses

An application’s preferences are a list of clauses. Each clause is a tuple

(m, S, [a1, a2, a3, a4], [b1, b2, b3, b4])

where m is a method selector, S is a set of addresses (the same set can appear in several clauses), and the coefficients a1, ..., a4 and b1, ..., b4 are signed integers. A method appears in at most one clause. One clause may name no method, in which case it holds every method that the other clauses do not (i.e., an optional catch-all clause).

A registration holds at least one and at most max_clauses clauses, at most one of which names no method, and each S holds at most max_senders_per_clause addresses. register reverts unless, for every coefficient pair, both b_i and a_i · max_parameter + b_i fit in an int128.

At the ABI level, a clause is represented by the following Solidity layout (where LinearScore refers to the scoring rule discussed in Section 3.2.3).

enum MethodMatch { Exact, AllOtherSelectors }

struct LinearScore {
    int128 slope;
    int128 intercept;
}

struct Clause {
    MethodMatch matchKind;      // Whether the clause is catch-all or not.
    bytes4 selector;            // Method m (ignored for catch-all).

    address[] senders;          // Sender set S.

    LinearScore singleInSet;    // a1, b1.
    LinearScore singleOutOfSet; // a2, b2.
    LinearScore multiInSet;     // a3, b3.
    LinearScore multiOutOfSet;  // a4, b4.
}

3.2.3 Scoring

A transaction t that declares a method m at application A gets a score for that method if a clause of A’s preferences holds m (possibly the catch-all clause). The score depends on the clause for m, on whether t’s sender belongs to S, and on whether t is single-opinion (it declares a single opinionated application) or multi-opinion (it declares several). With v the parameter declared for m (zero if empty), the score is:

Transaction Sender in S Sender not in S
single-opinion a1 · v + b1 a2 · v + b2
multi-opinion a3 · v + b3 a4 · v + b4

Note that, in a relayed transaction, for example under ERC-4337, the sender is the relayer, not the account on whose behalf the relayer acts.

The overall score that application A assigns to t is the lowest score among the methods that t declares for A:

U_A(t) = min { score of m in t : m declared by t for A }

A higher score for a transaction means earlier desired execution: A prefers t before u if and only if U_A(t) > U_A(u), and is indifferent if and only if U_A(t) = U_A(u).

For example, a PropAMM that wants its keepers’ oracle updates before every swap registers a clause for update that gives a score of 1 to senders in S (its keepers) and 0 to everyone else, plus a clause for swap with score 0. A transaction that declares both update and swap at the PropAMM therefore scores 0, like any other swap.

Similarly, a lending protocol may want the oracle update to execute first, followed by liquidations ordered by bid. Suppose the oracle updates prices by calling update from a known set of addresses S. The lending protocol can register two clauses: one for liquidate with a = 1 and b = 0, so that a liquidation declaring a bid v scores v, and one for update that gives a score LARGE_VALUE larger than the max value of v to transactions calling update from S and 0 to everyone else, so that the oracle update scores above all liquidations.

3.2.4 Validity and gas

register reverts unless all of the following hold: the list holds at least one and at most max_clauses clauses, at most one of which is the catch-all; no method appears in two clauses; each senders set holds at most max_senders_per_clause addresses; and, for every i, both b_i and a_i · max_parameter + b_i fit in an int128. The last condition is checked once, at registration, and guarantees that every score the clauses can produce fits fixed-width arithmetic, whatever a transaction declares.

Like any precompile call, register, revoke, and getPreferencesOf charge gas; the cost of register should grow with the number of clauses and of addresses in the registration, since translation has to load and evaluate all of them. The gas values, like max_clauses and max_senders_per_clause, are still to be decided.

3.2.5 Activation delay and compatibility with asynchronous execution

An update to the registry takes effect with a k-block activation delay after a call to register() or revoke(): a call in block b sets activationBlock to b + k, and returns it. Until then, the new preferences are pending; if an application calls register or revoke several times in the same block, only the last call counts. The delay gives users and front ends time to see new preferences before they take effect.

The delay is also what makes APES compatible with Monad’s asynchronous execution. To order block r, translation needs the preferences in force at r, all of which were set by calls in block r − k or earlier. Since execution lags behind consensus and translation, the registry’s state after block r − k is available to block r’s translation only if k is at least Monad’s asynchronous execution delay (3 blocks today).

3.3 Protocol-controlled ordering

The execution order of a block is computed in translation (i.e., the step between consensus and execution). The ordering algorithm depends only on the transaction declarations, on the applications’ preferences in force (Section 3.2.5), and on the default order.

3.3.1 Default order

The default order is built one transaction at a time. A transaction can be placed only after its nonce predecessor (Section 3.3.3). Among the transactions that can be placed, the next one is chosen as follows:

  1. a non-wildcard transaction if there is one, otherwise a wildcard transaction;
  2. among these, the one with the highest effective priority fee e = min(priority_fee_per_gas, max_fee_per_gas - base_fee);
  3. among these, the one with the lowest transaction hash.

Absent wildcard transactions, this is the order the block would have under standard priority-fee ordering. A non-wildcard transaction whose nonce predecessor is a wildcard transaction can only be placed once that predecessor is placed, so it is ordered among the wildcard transactions.

3.3.2 Unanimity relation

The applications’ scores for each transaction are collected into a preference matrix M, with one row per declaring transaction and one column per opinionated application: the cell M(t, A) holds U_A(t) when t declares A, and is empty otherwise. The unanimity relation is a dominance relation between rows. For two declaring transactions t and u, consider the columns where both rows hold a score. The relation places t before u when M(t, A) ≄ M(u, A) in every such column, with at least one strict inequality. A pair with no common column is left unranked, and so is a pair on which two columns disagree. The unanimity relation can be visualized through a directed graph with the transactions as vertices and the resulting unanimity links as edges (Figure 1).

Figure 1: the unanimity relation. (a) Applications A, B, and C score four transactions. (b) A prefers t1 to execute before t2, and B is indifferent, so t1 is unanimously ranked above t2. A and B disagree on how to rank t3 relative to t1 and t2. t4 shares no column with any other transaction, so it is unranked.

3.3.3 Nonce constraints

Within a block, a sender’s transactions must execute in nonce order. For a transaction with nonce n, we call the sender’s transaction with nonce n − 1 (if in the same block) its nonce predecessor, and the edge from it to the transaction a nonce edge. More generally, we call the sender’s transactions in the block with lower nonces its nonce predecessors, and those with higher nonces its nonce successors. The nonce edges have no cycles. Unlike unanimity links, which can be broken when the situation calls for it, nonce edges are hard constraints.

3.3.4 Pruned unanimity relation

We construct the pruned unanimity relation by removing the following unanimity links:

  • unanimity links that would place a transaction before one of its nonce predecessors (e.g., with nonce edges a → b → c → d, a unanimity link d → a), which would trivially violate the nonce constraints;
  • all unanimity links of nonce successors of wildcard transactions.

The second rule means that any non-wildcard nonce successors of a wildcard transaction are ordered like wildcard transactions: applications’ preferences no longer apply to them, and they execute among the wildcard transactions.

3.3.5 Cycle detection and cycle breaking

The graph built from the pruned unanimity relation and the nonce edges can have cycles. A cyclic component is a strongly connected component with at least two transactions. Standard algorithms, such as Tarjan’s or Kosaraju’s, find all cyclic components in time linear in the size of the graph.

If the graph is found to contain cycles, the next step is to break them. We do so by repeatedly applying an operation called demotion. Let d be a transaction in a cyclic component Y, and let D be the set containing d and its nonce successors in Y. Demoting d means:

  • removing all unanimity links between D and the other transactions of Y, in both directions; and
  • imposing new comparisons that place every other transaction of Y before every transaction of D.

After each demotion, the strongly connected components of Y are recomputed, and the process continues until no cyclic components are left in the graph. The process is guaranteed to terminate: every demotion removes at least one unanimity link, and the nonce edges and newly imposed comparisons alone close no cycles.

In each step, the protocol demotes a single transaction, chosen as follows (batch demotion is also possible; see the full specification document):

  • If there exist multi-opinion transactions in any of the cyclic components, the protocol demotes the one that is lowest in the default order;
  • Otherwise, among transactions residing in cyclic components whose nonce predecessor is in the same cyclic component, the protocol demotes the one that is lowest in the default order.

Figure 2 illustrates the procedure.

Figure 2: cycle breaking. (a) Four transactions form a cyclic component; t1, t2, and t3 are multi-opinion (shaded), and t4 is single-opinion. (b) The protocol demotes t2, the multi-opinion transaction lowest in the default order: t4 pays less, but the protocol demotes multi-opinion transactions first. t2 loses its unanimity links with the rest of the component, and new comparisons (dashed) place t1, t3, and t4 above it. (c) The graph is now acyclic, and it fixes the execution order: t3, t1, t4, t2. In general, the graph left once no cyclic component remains only induces a partial order, and completion (Section 3.3.6) turns it into the execution order.

3.3.6 Completion

Cycle breaking leaves a directed acyclic graph of surviving unanimity links, imposed comparisons, and nonce edges, that is, a partial order. We complete it into the total execution order E with Kahn’s topological-sort algorithm, using the default order to break the choices it leaves open. Concretely, E starts empty and grows one transaction at a time: at each step, among the transactions whose incoming edges all come from transactions already in E, it adds the one highest in the default order.

The full specification document gives the pseudocode for the whole procedure, including cycle breaking.

3.4 Execution check

The transactions of the block execute in the order produced above. Since the order is computed from the declarations alone, execution must check conformance with the declarations.

3.4.1 Interactions

A transaction t interacts with an application A whenever some non-static frame of its execution has A as its executing account (the address returned by ADDRESS), that is, t opens a frame that could modify A’s storage. Such a frame is either a call to A, including the transaction’s top-level call, or a DELEGATECALL or CALLCODE issued from a frame whose executing account is A.

The method of the interaction is the first four bytes of the frame’s calldata. This matches the ABI convention that Solidity uses to dispatch calls, where these bytes are the method selector. If the calldata is shorter than four bytes, the frame has no method: the protocol skips the check of Section 3.4.2 for it (even if A’s preferences have a catch-all clause).

3.4.2 Protocol check: methods

Let t be a declaring transaction and let A be an opinionated application. If t interacts with A through a method that A ranks (one held by a clause of its preferences in force, Section 3.2.5) without having declared it for A, that frame reverts without running any code.

Note that the check does not look at the code that runs in the frame, whether A’s own or code that A delegates to. For example, a Solidity proxy whose fallback() forwards every call to an implementation contract is checked against the selector of the call it forwards, even though, on the proxy, fallback() handles the call.

3.4.3 Application check: parameters

Each application enforces that a transaction’s execution honors its declared parameters: it reads the declared parameter of the call through a new opcode DECLAREDPARAM and decides how to treat a call that does not honor it, for example by reverting.

DECLAREDPARAM pushes one word onto the stack for the frame it runs in: the first byte holds a tag, and the other bytes hold a payload.

Tag Meaning Payload
0x00 t declared the method of the frame the declared parameter, or zero if the field was left empty
0x01 t did not declare this method, or the frame has no method empty payload
0x02 t is a wildcard transaction empty payload

3.4.4 Phantom declarations

A transaction can declare a method and never call it. The protocol checks then never fire, but the declaration still affects the order. Such phantom declarations cost only intrinsic gas.


4. Attacks and guarantees

4.1 Threat model

We consider a strong attacker who sees every transaction in the block, injects transactions from any address outside the sets S of the clauses, and deploys its own opinionated applications. The attacker cannot censor other users’ transactions.

Importantly, this threat model is conservative. First, BTX will allow users to encrypt their transactions. Thus, these will not be visible to the attacker prior to inclusion. Second, in addition to providing censorship resistance, Cadence also allows users to send their transactions privately to one or multiple concurrent proposers, for example based on past behavior, so that no one else sees it before inclusion.

Note that today, Monad’s block proposers choose the order of transactions freely, so every manipulation described below is already possible. With APES, the protocol enforces the ordering instead, which removes most of this freedom. However, some ways to manipulate the order remain.

Here we provide a high-level overview of the possible attacks and the guarantees provided by APES. The interested reader will find more details (including propositions and proofs) in the full specification document.

4.2 Overturning the applications’ preferences

Call x_i the victim’s transaction and x_j the attacker’s. Suppose that the applications unanimously rank x_i above x_j so that, absent any attack, x_i would execute before x_j. There are two ways in which an attacker could overturn the execution order:

  1. Place both x_i and x_j on a cycle, so as to exploit the cycle-breaking demotions and have x_j execute before x_i (Figure 3);
  2. Replace x_j with a functionally identical transaction x'_j that carries additional phantom declarations. These create a disagreement between applications, so that x_i and x'_j are no longer unanimously ranked, and their relative order falls to the default order (Figure 4).

Figure 3: the cycle attack. (a) The applications unanimously rank x_i above x_j. (b) The attacker deploys an application Z and injects transactions y_1 and y_2: A ranks x_j above y_1, Z ranks y_1 above y_2, and B ranks y_2 above x_i, closing a cycle. (c) If x_i is lowest in the default order, cycle breaking demotes it, and the final execution order places x_j before x_i.

Figure 4: the disagreement attack. (a) Application A ranks the victim’s x_i above the attacker’s x_j. Transaction x_i interacts with another application B that x_j did not declare. (b) The replacement x’_j carries a phantom declaration at B and scores above x_i there, so A and B disagree and there is no unanimity link between the two transactions. (c) The two transactions’ relative order falls to the default order, which the attacker wins by outbidding x_i.

Note that both attacks rely on the fact that the victim’s transaction interacts with several opinionated applications. The unanimity ranking between a single-opinion transaction x and any other transaction y interacting with the same application equals the relevant application’s preferences, because no other application scores both. If y is multi-opinion, it may still be demoted if there is a cycle, but if the application prefers x to execute before y, this preference will be respected. Hence, single-opinion transactions are safe from those attacks.

Furthermore, even if the victim’s transaction is multi-opinion, both attacks rely on the attacker being able to craft one transaction that ranks above the victim’s and one that ranks below it. When either is not possible, the victim’s transaction is safe from both attacks.

4.3 Cheap front-running

A second class of attacks aims at overturning the default order based on priority fees whenever applications are indifferent. Because unanimity comparisons take precedence over the default order, an attacker can front-run a transaction by maliciously creating unanimity links. This type of attack emerges when an application is indifferent where it should not be: the relative order of two transactions affects their outcome but the application’s registered preferences treat them as equal.

For example, consider two markets, A and B, each ranking cancellations above market orders and indifferent between different market orders. Transaction x places market orders on both. The attacker submits transaction y, which places a market order on A and phantom-declares a cancellation on B. At A, the two transactions tie. At B, y scores above x. So y ranks above x, and executes first even if it pays the minimal priority fee (Figure 5).

Figure 5: cheap front-running. Each column is a market, with cancellations ranked above market orders and each transaction is a line through the methods it declares (filled dots: actual calls, hollow dots: phantom declarations). (a) Without the phantom declaration, y ties x at A, and the pair falls to the default order, where x pays a higher priority fee. (b) A phantom cancellation at B lifts y above x at B, while the two still tie at A. Thus, y executes first, even at the minimal priority fee.

The same attack works if A is a traditional AMM with no preferences: a transaction x that swaps on A and also places an order on an opinionated market B can be front-run on A. Note that x is single-opinion in this case.

A similar attack even works against a transaction x that places a single market order on A. The attacker submits a phantom cancellation c at A, which ranks above both x and the attacker’s own order y on A, and places c on a cycle with y through two applications it deploys, Z1 and Z2, and a helper transaction h. Cycle breaking then demotes c, which pays the lowest fee, below y but not below x, which is not on the cycle: y executes before x, at almost the minimal fee (Figure 6).

Figure 6: cheap front-running through a cycle. (a) The transactions are drawn as in Figure 5. The victim’s transaction is x. The attacker deploys applications Z1 and Z2 and injects transactions c (fee=0), y (fee=2), and h (fee=2). (b) In the resulting unanimity relation, the attacker’s three transactions form a cycle (orange), and cycle breaking demotes c, which is the lowest fee amongst them. (c) The execution order then places c above x (the relation survives as x lies outside the cycle). Thus, y executes before x.

The defense against cheap front-running attacks is to make the ranking reflect what users compete for. Suppose that market A ranks market orders by priority fee: each order declares its fee as the parameter, and the market checks it with DECLAREDPARAM. Then a transaction that trades only on A can be front-run there only by an order that declares, and pays, at least the same fee. Any other value the application uses to break its indifference, such as a bid or the size of a stake, also works.

4.4 Protocol guarantees

The full specification document shows that, even in the presence of an attacker, APES provides the following guarantees to non-wildcard transactions with no same-block nonce predecessors:

Guarantee 1: single-opinion transactions are safe. Suppose a transaction only interacts with a single application that expressed preferences (plus any number of applications with no preferences, like ERC-20 contracts). If its opinionated application ranks this transaction above another, the first executes before the second, whatever the attacker does. Also, all single-opinion transactions interacting with the same application are always ordered according to this application’s preferences.

Guarantee 2: gated transactions are safe. A transaction is gated if no transaction an attacker can craft outranks it in the unanimity ranking, directly or indirectly. A gated transaction executes as the applications unanimously prefer, however many applications it touches. The mirror image also holds: a transaction that no attacker can rank below, directly or indirectly, executes after every transaction that the applications unanimously rank above it.

Guarantee 3: simple transactions cannot be cheaply front-run. Consider a non-wildcard transaction that interacts with one application where ordering matters, plus any number of applications where it does not, such as token contracts. Suppose that application either expresses no preferences, or also ranks the method the transaction calls by a value that it checks at execution. Then front-running the transaction costs at least as much as under priority-fee ordering.

These guarantees suggest a few rules. For application designers:

  • Reserve the top of the ranking. If the highest-ranked method is reserved to the addresses that legitimately call it (e.g., a pool keeper or a market or vault owner), with everyone else getting a low score, then transactions calling the next method down are gated and therefore covered by Guarantee 2 (see the PropAMM example in the blog post).
  • Otherwise, reserve it to single-opinion transactions. If the highest-ranked method cannot be reserved to a few addresses, it can be reserved to single-opinion transactions, with multi-opinion transactions getting a low score. An attacker can then outrank transactions calling the next method down only with single-opinion transactions, which cannot place them on a cycle or break their unanimity links (the full specification document gives an example; the batch exchange in the blog post applies the same idea to the bottom of the ranking).
  • Rank by value where position matters. If executing earlier is still valuable for users once your preferences apply, rank that method by priority fee or by a bid, so that simple transactions are covered by Guarantee 3 (see the liquidation auction and order book examples in the blog post).

For users:

  • Keep it simple. As far as possible, each transaction should interact with only one application where ordering matters.

See the blog post for examples of how to apply these principles to four applications with ordering preferences: a PropAMM, an order book, a cross-market batch exchange, and a liquidation auction. The full specification document contains an additional example: an order book with an operator-only “halt trading” action and special swaps from partners, which execute before regular market orders.

5. Extension: multiple applications within a contract

In the implementation discussed above, an application is a contract. This means, for example, that a contract holding several pools or markets cannot define different preferences for each market. In particular, the preference registry cannot reflect the fact that those markets may have different keepers or owners. However, several existing protocols hold many markets created by different parties in a single contract. To accommodate these protocols, APES could be extended with ordering domains: an identifier d chosen by the application, such as a pool identifier, that transactions declare together with each method (similarly to the parameter). The address field of an entry of the interaction_list would then contain both the contract address A and the domain d, and each pair (A, d) is a separate column of the preference matrix.

In principle, each domain within the same contract could specify completely different preferences for the same method. However, for the applications discussed in the blog post, a simpler implementation would keep the clauses defined at the level of the application and the method, and let only the sender set S depend on the domain. That is, each pool, market, or vault can have its own keepers, while the ranking rules follow the design of the application. Also, declared domains could be treated like parameters: the protocol uses them for ordering, and the application checks them, for example through a version of DECLAREDPARAM that takes the domain as input.

The main downside of this extension is that a transaction touching several domains of the same contract becomes multi-opinion. Without domains, such a transaction declares a single application and is therefore single-opinion, as long as it touches no other opinionated application: Guarantee 1 protects it and, if the contract ranks by value, so does Guarantee 3. With domains, it loses this protection. To keep the current specification simple, we have not included this extension, and we welcome feedback on whether applications need it.

6. Backward compatibility

Case Result
Legacy transactions (existing types) Treated as wildcard transactions. They can call any application, ranked methods included, but they are placed after declaring transactions, whatever fee they pay.
Applications that do not register Unaffected. Transactions that touch only such applications can carry an empty list and keep competing on priority fees.
Deployed upgradeable proxies Can become opinionated without being redeployed, by upgrading to an implementation with an admin-gated function that calls register and that additionally implements isApesEnabled.
Deployed non-upgradeable contracts Cannot register, since only APES-enabled contracts can. Without this check, a contract that lets users make arbitrary calls could be abused. An attacker could make it call the registry and register preferences on its behalf, making it opinionated against its developers’ intent. A similar issue affected a precompile on Avalanche.
ERC-4337 bundles A bundle carries the operations of several accounts, which cannot be ordered separately. A bundle can declare every opinionated application and method that its operations may call, but since this is impractical, bundles will likely use the wildcard entry. Also, the sender of the bundle is the relayer, not the account behind each operation.

Wallets and tooling. Wallets and other tooling will need to support the new transaction type. This includes an RPC call that simulates a transaction and returns its declaration, similar to eth_createAccessList.

7. Conclusion

Composability is one of the main economic benefits of blockchains. However, applications that need a specific order have so far had to either accept the chain’s ordering rule or move to their own chains. APES lets these applications stay on Monad and get the order they want.

As the attacks above show, how well transactions are protected depends on the preferences applications set and the transactions users send. However, simple transactions, which interact with one application where ordering matters plus any number where it does not, are safe under mild conditions.

The specification document has the remaining details, including all the attacks, the proofs of the guarantees, and the implementation details that are still open. We look forward to your comments!

6 Likes

Thanks for sharing APES. We’re developing an application on Monad that uses an external oracle.

After reviewing Sections 2.2, 2.4 and 4.1, we understand that:

  • STATICCALL does not count as an APES interaction.
  • Sender-set membership uses the transaction sender, including for relayed transactions.
  • A combined update-and-operation transaction receives the minimum score of its declared methods.

Our remaining question concerns the recommended integration pattern for a shared external oracle.

Suppose contract A receives keeper updates, while independent applications B and C read A through STATICCALL. An update to A and an operation on B need not share an opinionated application column, so preferences registered on A alone would not enforce update-before-operation ordering.

Would you recommend keeper-callable forwarding methods on B and C, allowing updates and user operations to share the respective application column? If one keeper transaction updates A for several applications, how should this be structured to preserve the intended ordering guarantees without introducing unnecessary multi-opinion interactions?

A worked example covering a shared external oracle would be helpful.

As a small follow-up, our local model reproduces the distinction between an update to a separate oracle contract and an update declared at the consuming application. In the first case, the static read alone creates no shared application column; in the second, keeper-restricted preferences produce update-before-operation ordering in the simple scenario we tested.

This supports our reading of the specification. Our remaining question is the recommended integration pattern when several independent applications consume the same external oracle.

The method check keys on the frame’s selector, so an unranked entry point that reaches a ranked action gets past it. Take the PropAMM: if it also has a multicall that runs swaps through internal calls, or a swapWithPermit wrapper, and only update and swap are ranked, a transaction can swap through that method with an empty list. It shares no column with the keeper’s update, so their order falls to the priority fee and the swap can run before the update by paying more. A catch-all clause covers the other selectors but not frames under four bytes, a buy through receive() for example. Reading DECLAREDPARAM inside the internal swap path and reverting on 0x01 covers both, and could go next to “reserve the top of the ranking” in the designer rules.

Legacy and wildcard transactions run after every declaring transaction whatever fee they pay, and an exploit can go out as a declaring transaction. So a pause sent through a Safe, a monitoring bot or any tooling that still builds the existing transaction types, or inside a 4337 bundle, which the post expects to use the wildcard entry, runs after the exploit when both land in the same block. Guardians would need to send pauses as declaring transactions, and the backward compatibility table could say so.