---
# System prepended metadata

title: MEV

---

# MEV
We want to explore and protect against the attack vectors introduced by the ability of miners or validators to manipulate the order of transactions. The profit that miners/validators extract by reordering transactions is called Miner Extractable Value (MEV).

## Ordering of actions
If an agent takes action h first, g second, f third, the order of actions is represented as:

$$f(g(h(x)))$$

A possible reordering of action here would be: f first, h second, and g third

$$g(h(f(x)))$$

If $g(h(f(x)))$ is more profitable than $f(g(h(x)))$, then the validator is able to perform an MEV.

### Transaction fees on Sifchain network
This is the default configuration for transaction fees in Cosmos, where it charges for reads and writes to the store. The default setup is analagous to the Ethereum gas limit table. Default config values shown below
![](https://i.imgur.com/sUdfdWX.png)

### Validation on Sifchain
Sifchain is a PoS system that offers instant deterministic finality as it operates on Tendermint consensus with pBFT. The section below walks through the process of validating transactions especially as it pertains to aspects that affect the probability of a transaction being ordered differently.

1. Each validator has their own mempool.
2. Validators are selected via a round robin for a proposer role.  When it's their turn, they select transactions from their own mempool to form a proposed block and then the other validators vote on whether to admit that block into the blockchain. 
3. Within a block, all transactions are ordered based on their respective transaction fees. This is a modification of Tendermint consensus.
4. Due to latency between the transactor sending the message and the validator receiving it, a transactor cannot necessarily know that their message will be prioritized for an upcoming block even if it has a high transaction fee.  The proposer for the upcoming block simply might not receive it on time. This is related to Assumption 2 below.
5. Alternatively, the validator may see it in the mempool on time but not propose it in the upcoming block. This is censorship and it could be a opportunity for MEV. Under the current conditions, the other validators would have no way of knowing that the transaction was censored because they cannot view the proposer's mempool.  



Sifchain allows users to set their own transaction fee so as to move their transaction forward in the mempool i.e increase the probability of their transaction being executed in the current block. However, increasing a transaction's fee increases the probability of it being added to an upcoming block only if it is received on time by an honest validator.


The transaction fee associated with each action can be structured such that there is a base fee $F_{base}$ and a user-set transaction ordering fee $F_{order}$. $F_{base}$ is based on cost of reads, writes, and other computational operations made to the blockchain. This can be based on the default config values shown above. The ordering fee $F_{order}$ is set by the user i.e transaction issuer and can be made sufficiently large should they wish to have their transaction completed in the nearest block. 
$$F = F_{base} + F_{order}$$


### Assumptions
**Assumption 1**: Ordering of action assumed to be in order of transaction fees

**Assumption 2**: If transaction fees are known, re-ordering can be done through specifying transaction fee to get the action placed in desired order in the mempool. Note that transaction fees alone, even if sufficienty high, cannot guarentee that a transaction will be passed due to two reasons:
1. Latency; transaction has been sent but the validator has not yet received it in time to include it in their mempool
2. Transaction was censored due to validator attempting an MEV attack

:::warning
Even if transactions fees are not known, there is likely an expected transaction fee associated with an expected order, based on historical data.
:::

**Assumption 3**: Tendermint consensus - which the Sifchain system employs - works as expected. We assume that this underlying consensus mechanism is not violated in the scope of this exploration.

## Attacks that create MEV opportunities

Here we explore the many ways in which miners/validators/arbitrage bots can exploit inefficiencies of DEXs. Note that the quantity and magnitude of all possible MEV opportunities is infinite and cannot be exhaustively predetermined in any blockchain. The curse of dimensionality applies here - generally, the greater the degrees of freedom, the greater are the potential MEV vectors and the faster value extracted accumulates. 

While most of these attacks have been studied in the context of exisiting DEXs, the Sifchain system is unique in that it offers margin trading instruments. The fundamental difference is that leverage exists, and this calls for the analysis of each MEV attack type to determine its sensitivity to leverage.

1. Frontrunning
    - Classic problem present in all trading systems and enabled by HFT, however it is often regulated away in centralized systems. In decentralzied systems and DEXs it continues to occur as a natural consequence to time-sensitive information asymmetries. Frontrunning allows sandwich attacks.
2. Undercutting attack
    - Miners ignore a block so as to reap a profit. Destabilizes short-term consensus. Blocks can be forked to extract MEV. These attacks are particularly significant in cases where tx ordering fees are present and dominate block rewards. Miners are incentivized to fork high-fee blocks, encouraging other miners to build on the fork. In extreme cases, this leads to a deviation from the protocol and compromises security.
3. Fee-based forking attack
    - Secondary attack type arising from the existence of transaction ordering fees $F_{order}$ 
4. Time-bandit attack
    - Secondary attack type that emerges in high-MEV regimes. Miners/validators are able to rewrite blockchain's history to falsely allocate funds that were previously allocated to smart contracts to themselves, effectively stealing those funds.
5. Smart contract enabled batching of buy/sell orders
    - Arbitrageurs are able to use a smart contract to batch multiple orders sequentially within a single transaction, effectively guaranteeing that if even a single order is successful, all buy and sell orders in the contract will be successful as well. A single tx can execute multiple trades across multiple DEXs sequentially and atomically thus resulting in a profit equivalent to the difference between the sell price and buy price.  
    
## MEV on Sifchain

In the context of Sifchain, we have made [Assumption 3](https://hackmd.io/xMgW5IiVTryllHgmCIw8sA?both#Assumptions)

As Tendermint offers a Practical Byzantine Fault Tolerant-based (pBFT) and PoS consensus algorithm, Sifchain is able to offer instant finality. There are no re-orgs, uncles, or orphaned blocks as in probabilistic finality systems. There is an immediate convergence on a single correct block via a deterministic process. This fact narrows down the attack space of all MEVs under consideration to the following:

### Stealing arbitrage opportunities through censorship
- This happens when an honest arbitrageur makes an entirely legal transaction and this transaction is observed by a validator. The validator determines that this transaction is profitable for whoever issues it, and selectively censors the arbitrageur's transaction from passing. Instead, they make the same transaction and allow it to pass instead, thus reaping the profit from the arbitrage. 
- This type of MEV is currently legal but considered stealing as the validator is reaping the benefit of an arbitrage opportunity without expending effort to find it, and by doing so they steal unrealized profits from an arbitrageur who did expend effort to identify the opportunity.

### Sandwich attacks via artificially induced price changes
Transaction issuers on the Sifchain sysetm engage in a continuous time Priority Gas Auction (PGA) to bid higher transaction fees so as to get a more favourable block position.

In the Liquidity Provider Subsystem, this would typically manifest in a sequencing where a $mtp$ position is force closed via an artificially induced price change. As validators have the privilege of censoring transactions, they also end up being the keepers of liquidity pools, thus being able to selectively pass transactions such that they can always collect forced settlement rewards.

Consider an X-Y liquidity pool
1. An $mtp$ which has been collaterialized with X token assets exists 
2. If it is profitable to force close this $mtp$ and the validator has sufficient funds to acheive the desired temporary state, the validator - who is also a keeper - intervenes and performs the following actions.
    - Profitiability is determined by MEV being $+ve$ or $-ve$ using the MEV equation below
3. Validator performs a large swap of X-tokens to Y-tokens, causing the price of X tokens to fall. The swap carries a fee $f_{swap}X\rightarrow Y$ which is paid by the validator.
4. The $mtp$ defaults as the price of X tokens have drop sufficiently that its health moves below the threshold $h(x) < b$
5. Validator - as a keeper of the MTP pool - calls upon the now default $mtp$ via Forced Settlement by Any Address mechanism
6. The validator is also able to ensure that their transaction is included in the proposed block due to the round robin nature of validator selection, they can ensure that their force settlement action passes
7. The $mtp$ is force closed and the validator receives a forced settlement reward $R_{FS}$
8. The validator swaps back a similar amount of Y-tokens back to X-tokens thereby restoring price. The validator pays swap fees $f_{swap}Y \rightarrow X$

The above sequence of actions constitue a sandwich attack that results in an MEV to the validator where
$$ MEV = R_{FS} - (f_{swap}X\rightarrow Y + f_{swap}Y \rightarrow X) $$

An added advantage of performing this type of attack as a validator is that as a validator, they are able to perform the swaps atomically and ensure sequence. This is possible as validators are able to batch multiple orders within a smart contract thus processing multiple orders through a single transaction even across exchanges. 

These attacks can be performed by any keeper/validator as long as they have sufficient funds to move an $mtp$ to default by manipulating price. 

$$Wealth_{validator} \propto ability \ to \ perform \ sandwich \ attack$$ 

One proposed protection mechanism is to set thresholds or warning tracks around $mtp$ health such that if the $mtp$ is close to being subject to a sandwich attack, they $mtp$ holder will be alerted to perform margin maintenance. 

Realistically determining this threshold will require prior knowledge of $Wealth_{validator}$ but this information is not directly observable. A validator with a relatively large enough $Wealth_{validator}$ will be able to drive price so wildly that they can force close even healthy $mtp$'s.

Thus we explore two other protection mechanisms to prevent MEV:
1. Price correction mechanism
2. Modulating forced settlement rewards $R_{FS}$ based on history

## Price Correction Mechanism

| Name | Description | Symbol |
|----|----|----|
| Price Correction Pool Funds | Funds available in the Price Correction pool, denominated in Rowan | $\mathbf S_{PC}$ |
| Validator block rewards | Block rewards with rebalancing parameter $\lambda_v$ | $\mathbf b(\lambda_v)$ |
| Minimum Price Correction Pool Funds | Lower threshold on funds that need to exist in the Price Correction pool | $\mathbf S_{PC,min}$ |
| Gas Cost | Gas cost of performing an action | $g$ |

We introduce the Price Correction mechanism as the first pass for default $mtp$'s to be called. The two other force closure mechanisms i.e *Forced Settlement by Any Address* and *Forced Global Settlement by Pool* still exist, and they are the mechanisms employed to close default $mtp$'s following the Price Correction mechanism respectively. 

The Price Correction mechanism comprises of two steps:
- force closure of the $mtp$, described below
- [correction of liquidity pool price](https://hackmd.io/xMgW5IiVTryllHgmCIw8sA?both#Community-Action-to-Correct-Liquidity-Pool-Price), which follows immediately after.

To set up this mechanism, there should exist a Price Correction Pool (PCP) across all liquidity pools at the Sifchain blockchain level. This global PCP comprises of validators as they have an implicit stake in the PCP. This is because the validators hold block rewards, and a portion of the block rewards minted flow into the Price Correction pool as inflation. 

#### Option A: Price Correction Pool funded by validator rewards

The Price Correction pool can be funded by validator rewards and forced settlement rewards. Only a portion of all minted block rewards (validator rewards) go to the Price Correction pool. Only a portion of $x_L$ i.e the remaining liabilities when $mtp$ has been force closed is covered by the Price Correction pool. Note that the below stock and flow diagram is representational.


![](https://i.imgur.com/vSDlFS2.jpg)


#### Option B: Price Correction Pool funded by validator rewards and swap fee from $mtp$ open and close actions

In this mode, the Price Correction pool funds $S_{PC}$ are sourced from both validator and liquidity proovider subsystems. $x\%$ of total validator rewards can be used as an input to the Price Correction pool. 

$x$ can be smaller if more security is desired, as it will allow for a greater portion of funds to be rewarded to validators. The remainder of the Price Correction pool funds will be sourced from swap fees that are incurred when an agent opens or closes an $mtp$, and from forced settlememt rewards $R_{PC}$. 


![](https://i.imgur.com/0d1Lsrh.jpg)



<br>
<br>
<br>

Default $mtp$'s need to be closed frequently in order to maintain overall liquidity pool health. With the introduction of the Price Correction mechanism, we can ensure that default $mtp$'s are closed as quickly as possible via programmatic action. 

**Policy for programmatic action**
Always close default $mtp$'s as long as their health $h(x)$ is lower than threshold $b$. However, the Price Correction pool will only price correct if available funds in the Price Correction pool are greater than a threshold $\mathbf S_{PC,min}$. 

Algorithmically, 

- Maintain a running list of $mtp$'s ordered by their health $h(\mathbf x)$
    - This can use [$mtp$ health computation](https://hackmd.io/@mbarlin/S1o48Vtm_#mtp_Health_Computation)

While $\mathbf S_{PC} > \mathbf S_{PC,min}$,
- Price Correction pool calls the first default $mtp$ where the $mtp$'s health $h(\mathbf x) < b$ 
    - Perform [excess liability computation](https://hackmd.io/@mbarlin/S1o48Vtm_#Excess_Liability_Computation_on_mtp)
    - $mtp$ is forced closed using the [Forced Settlement By Any Address](https://hackmd.io/@mbarlin/S1o48Vtm_#Forced-Settlement-by-Any-Address) mechanism, where $R_{FS} = R_{PC}$ is paid to the caller. In this case, it's paid to the Price Correction pool
        - $\mathbf S_{PC}^+ = \mathbf S_{PC} + R_{FS}$
    

#### Computing $R_{PC}$
There are multiple ways to compute the reward for forced settlement by the Price Correction pool $R_{PC}$.

##### $R_{PC}$ covers gas costs
On the lower end, $R_{PC}$ can be equivalent to, or approaching the gas cost required to make the margin call, plus the average gas cost of monitoring all the $mtp$'s. 

$$ R_{PC} = g_{margin \ call} + g_{EMA, monitoring \ mtp's} $$

The exponential moving average gas cost of monitoring $mtp$'s can be computed similarly to how $P_{EMA}$ is computed, with a forgetfulness factor $\alpha_g$.

$$ \alpha = \frac{2}{N+1} $$ where $N$ is the number of blocks or epochs.

$$ g_{EMA, monitoring \ mtp's}^+ = \alpha_g \cdot g_{monitoring \ mtp's} + (1-\alpha_g) \cdot  g_{EMA, monitoring \ mtp's} $$

##### $R_{PC}$ covers gas costs and gives additonal reward
On the higher end, $R_{PC}$ can be the gas costs of making the margin call, gas cost of monitoring all $mtp$'s, plus an additional reward that is modulated by a by a price difference factor. 

Price difference $\gamma_{EMA}$ between the price of the token as given by the liquidity pool and the exponential moving average price is 

$$ \gamma_{EMA} = | P - P_{EMA} | $$

The additional reward on top of gas costs is modulated by $\gamma_{EMA}$ to prevent MEV. This makes it such that the reward isn't as high at times of wild price swings.

$$ R_{PC} = f(g_{margin \ call} + g_{EMA, monitoring \ mtp's}, x_A, \gamma_{EMA})$$

### Price Correction Mechanism to Correct Liquidity Pool Price
This is the second step within the Price Correction mechanism. Here, the difference between the pool price $P$ and the true price (obtained either from an exponential moving average $P_{EMA}$ or from an external oracle $P_{oracle}$) is used to correct the pool price in the next state following an $mtp$'s force settlement by Price Correction pool.

Let's use $P_{EMA}$ for the following analysis. The same computations can be applied employing $P_{oracle}$.

Given a X:Y liquidity pool. There is an unhealthy $mtp$ in this pool with assets in token X. The current price difference $\gamma_{EMA}$ is
$$ \gamma_{EMA} =  | P - P_{EMA} |$$

Perform Price Correction mechanism to force close this $mtp$. The Price Correction pool - which is global - provides cover for the remaining liabilities that were not covered by the $mtp$

$$ S_{CP}^+ = S_{CP} - x_{L}$$

As the $mtp$'s assets were of type $X$, the decrease in the price of X relative to Y led to its default. The correction mechanism aims to match the pool price $P$ to the exponential moving average price $P_{EMA}$. In the case of this $mtp$, we should consider $P_{X \rightarrow Y}$ price.

#### Price Correction Pools as Insurance 
The Price Correction pool exists across all the liquidity pools that provide margin trading in the system. A governance mechanism shall allow for the Price Correction pool to set parameters across liquidity pools. 

In the simplest case, the only parameter that Price Correction pool participants would set is the insurance amount $I$, i.e. the percentage of Price Correction pool funds $S_{PC}$ allocated to cover defaulted $mtp$ liabilities of a liquidity pool in a given time period. The global Price Correction pool governance mechanism sets different insurance amounts allocated to each liquidity pool with $mtp$'s, and these can be reset periodically. It is possible that some liquidity pools may be rather high-leverage thus the Price Correction pool may not wish to insure them. In these cases, $I = 0\%$


Continuing the analysis, the Price Correction pool must perform a volume of swaps in order to bring $\gamma_{EMA} = 0$ due to the decrease in the price of X relative to Y. Thus the Price Correction action mechanism will automatically swap in, i.e. swap $Y \rightarrow X$ the amount required to cover the liabilities provided that the allocated insurance amount is not exhausted.

#### Agent Price Beliefs
We know that agents in the Price Correction pool have private price beliefs, as in any market. These agents make their buy/sell decisions considering both their private price belief as well as the market price. 

The agent's next state private price belief is a convex combination of their current price belief $\ p_{private}$ and the market price, in this case the pool price $P$. Parameter $\epsilon \in [0,1]$ is applied to weigh the influence of the agent's price belief. 
$$p_{private}^+ = \epsilon \ p_{private} + (1-\epsilon) P$$


Intuitively, if $\epsilon < 0.5$, the correction mechanism may induce a real price correction by the Price Correction pool participants. This is because their trading decisions are more heavily influenced by the pool price, so a change in that will induce trades.

If $\epsilon > 0.5$, the correction mechanism will not induce a price correction as agents weigh their own price beliefs higher, thus their trades are less influenced by fluctuations in pool price. 

We propose a parameter sweep test across $\epsilon$ over its domain $[0,1]$ to deduce under which weights the correction mechanism would work as intended.


### Forced Settlement Rewards based on $mtp$ history

A classic giveaway of a sandwich attack is a recent spike in price movement. This holds even more true if the price movement is induced by a single agent, indicating price manipulation.

One way to overcome force closure sandwich attacks that result in MEV is by basing forced settlement rewards $R_{FS}$ on the $mtp$'s recent history.

An $mtp$ whose health has rapidly deteriorated over a short timespan, say a block, is likely to have undergone a price manipulation event. In order to make this not manifest in a sandwich attack, we can decrease $R_{FS}$ such that this MEV nets negative. 

Set an $R_{FS}$ such that
$$ (f_{swap}X\rightarrow Y + f_{swap}Y \rightarrow X) \geq R_{FS} $$ so
$$MEV \leq 0 $$

To ensure that this rule is only applied to artificially induced price movements, we need to check if price manipulation indeed happened or not. We can do this in one of the following ways:
1. Implement time-based and number of attackers-based checks
2. Directly modulate $R_{FS}$ using price difference

#### Checks on number of blocks and number of attackers

1. Check if the percentage change in the $mtp$'s collateral token price - that is large enough to move the $mtp$ to default - has occured over the last $n$ number of blocks. The percentage change in collateral token price is given by
$$ \frac{P_{\alpha-n} - P_{\alpha}}{P_\alpha}$$
where 
- $P_{\alpha}$ is the price of the collateral token in the current state
- $P_{\alpha-n}$ is the price of the collateral token in the state where the price manipulation began

The smaller $n$ is, the more likely that the price movement is a price manipulation.

The prices must satisfy the condition that at current price $P_{\alpha}$, the $mtp$ is in default. Considering a $mtp$ with collateral in X tokens,  
$$h_{\alpha}(\mathbf x) = \frac{x_A}{x_A + x_L^{P}+ x_L^{E}} < b$$

2. The price manipulation has been artificially induced by a single agent or a sufficiently small group of $m$ agents. Here we assume Sifchain is not Sybil resistant.

Check that $m$ agents have perfomed swaps converting away from the $mtp$ collateral token, in this case X tokens.

The smaller $m$ is, the more likely that the price movement is a price manipulation and also that
-  The agents are all a single self-interested entity in meatspace
- The agents are multiple entities but are colluding to earn MEV

Both the number of blocks $n$ leading up to an $mtp$ defaulting, and the number of agents $m$ that were involved in moving the price are thresholds that can be set in the above conditional statements. Both $n$ and $m$ can be determined by cadCAD experiments or using historical data of Sifchain system activity, or a combination.

#### Modulate $R_{FS}$ using price difference 

We explore two ways to modulate force settlement rewards using price differences. Both methods are used to determine how much of the price movement is a result of price manipulation activity. These methods compare the price computed in the liquidity pool in which the movement happened, to a *true price* that is obtained through:
1. Price data from an external oracle 
2. Exponentially weighted average price from Sifchain's own price history

Below we demonstrate how to craft a function for $R_{FS}$ that is both **market insured**, using oracle price data and **protocol insured**, using exponential moving average price.

##### Price data from an external oracle
Any time an $mtp$ is called to be force settled, we can poll the X:Y price of the token from an external oracle ($P_{oracle}$)  and compare it to it's equivalent X:Y price in the liquidity pool ($P$). This is a relatively quick method to determine if the price movement on the liquidity pool is deviant from the true market price that exists on all other sources.

$$\gamma_{oracle} = |P - P_{oracle}|$$

If the price gap $\gamma$ is too high, $R_{FS}$ will be proportionally low such that the $MEV$ that can be extracted from force closing the $mtp$ is negated. 

$$R_{FS} \propto \frac{1}{\gamma_{oracle}}$$

This factor can be applied to the computation of $R_{FS}$, along with the amount of assets held by the $mtp$ to be force closed.

$$R_{FS} = f(x_A, \gamma_{oracle})$$

The oracle price data can be composed of price data from multiple external oracles, weighed by the level of data integrity.

##### Exponential moving average price 
An alternative to using a price oracle in the treatment above, we may be able to use an exponential moving average of the on-chain price. 
##### Stateful Metrics
| Name | Description | Symbol |
|----|----|----|
| Price | Token price, derived from ratio of tokens in liquidity pool | $P$ |
| Price Signal | Exponential Moving Average of Price | $P_{EMA}$ |

##### Stateful Parameters

| Name | Description | Symbol | Domain |
|----|----|----|----|
| Forgetfulness factor| Lag used in weighted average computation | $\alpha$ | [0,1] |

##### State Update

Given a Price, $P$, presumably the spot price of the liquidity, we can compute a state-based exponential moving average ($P_{EMA}$) of that price without having to store previous price values.

$$ P_{EMA}^+ = \alpha \cdot P + (1 - \alpha) \cdot P_{EMA} $$

##### Parameter Value Choice and Implementation Considerations

The choice of value of the forgetfulness factor $\alpha$ parameter determines the period of the moving average. 

For a given period of updates to price, $N$, (presumably blocks, but may be epochs), $\alpha$ should be computed as:

$$ \alpha = \frac{2}{N+1} $$

Values closer to 1, discount older observations quicker. While $\alpha$ values closer to 0, represent longer periods to average over.

A table of selected values for averaging period and corresponding alpha. 
| N | $\alpha$ |
|----|----|
| 1| 1 |
| 2| 0.67 |
| 3| 0.50 |
| 7| 0.25 |
| 10| 0.182 |
| 21| 0.091 |
| 30| 0.065 |
| 50| 0.039 |
| 99| 0.02 |

Given the computation limits and the need for decimal datatypes, it may simpler to use $N$ as the parameter and compute $P_{EMA}^+$ directly from $N$:
$$ P_{EMA}^+ = \frac{2}{N+1} \cdot P + (1 - \frac{2}{N+1}) \cdot P_{EMA} $$

$$R_{FS} = f(x_A, \gamma_{EMA})$$

## MEV Scenario Testing on cadCAD

### Sandwich attack using swaps
Scenario A: Control scenario where $mtp$ naturally moves to an unhealthy state

```TEST_ACTION = [pricecorrection_action]```

Scenario B: Attack scenario where $mtp$ is sandwiched by *Swap out* and *Swap in* actions to artificially move the $mtp$ to an unhealthy state


```TEST_ACTION = [swap_out, pricecorrection_action, swap_in]```

Note: Swap from the token type (X or Y) that the $mtp$'s assets are stored in. If $x_A$ is of X denomination, swap on X side, then force close using Price Correction action, then swap back in the same amount on X side.

### Sandwich attacks using liquidity removes
Scenario A: Control scenario where $mtp$ naturally moves to an unhealthy state

```TEST_ACTION = [pricecorrection_action]```

Scenario B: Attack scenario where $mtp$ is sandwiched by *Liquidity remove* and *Liquidity add* actions to artificially move the $mtp$ to an unhealthy state

```TEST_ACTION = [liquidity_remove, pricecorrection_action, liquidity_add]```

Note: Remove liquidity from the token type (X or Y) that the $mtp$'s assets are stored in. If $x_A$ is of X denomination, remove liquidity on X side, then force close using Price Correction action, then add the same amount of liquidity back in on X side.

### Price Correction Mechanism vs Force Settlement By Any Address
Scenario A: Default $mtp$ settlement mechanism is Force Settlement By Any Address. Price Correction Action mechanism does not exist, or is disabled.

```TEST_ACTION = [force_settlement_by_any_address]```

Scenario B: Default $mtp$ settlement mechanism is via Price Correction mechanism. If an $mtp$ is unhealthy and is not yet closed by the Price Correction mechanism, then it can be called by any agent for force closure using the Force Settlement By Any Address mechanism.

```TEST_ACTION = [pricecorrection_action, force_settlement_by_any_address]```

Note that ```force_settlement_by_any_address``` is only executed if the $mtp$ is not closed by ```pricecorrection_action```

### Coefficient on $R_{PC}$ 
This parameter sweep helps determine the most optimal coefficient that needs to be applied to the price difference factor $\gamma_{EMA}$ on Price Correction rewards.

We know that Price Correction rewards is given by:
$$ R_{PC} = f(g_{margin \ call} + g_{EMA, monitoring \ mtp's}, x_A, h(x), \gamma_{EMA})$$
where $\gamma_{EMA} = | P - P_{EMA} |$

Say we devise a formula for $R_{PC}$ to include a coefficient or weight $w_{CP}$ applied to the price difference factor $\gamma_{EMA}$, like so

$$R_{PC} = g_{margin \ call} + g_{EMA, monitoring \ mtp's} + R_{PC}(\cdot)x_A + w_{PC}\gamma_{EMA}$$

where $R_{PC}(\cdot) = f(h(x))$ and $w_{PC} \in [0,1]$.

Coefficient $w_{PC}$ is a parameter that can be swept across it's range of values, i.e from 0 to 1, with granularity $\frac{1}{100}$.

- $R_{PC}$ with $w_{PC}=0$ is not affected by price volatility at all, thus incentivizes MEV sandwich attacks 
- $R_{PC}$ with $w_{PC}=1$ is highly sensitive to price volatility, thus maximizing the avoidance of MEV sandwich attacks


### Coefficient on $R_{FS}$ 
Similar to above, this parameter sweep helps determine the most optimal coefficient that needs to be applied to the price difference factor $\gamma_{EMA}$ on force settlement rewards.

We know that force settlement action rewards is given by:
$$R_{FS} = f(x_A, \gamma_{EMA})$$
where $\gamma_{EMA} = | P - P_{EMA} |$

Say we devise a formula for $R_{FS}$ to include a coefficient or weight $w_{FS}$ applied to the price difference factor $\gamma_{EMA}$, like so

$$R_{FS} = R_{FS}(\cdot)x_A + w_{FS} \gamma_{EMA}$$

where $R_{FS}(\cdot) = f(h(x))$ and $w_{FS} \in [0,1]$.

Coefficient $w_{FS}$ is a parameter that can be swept across it's range of values, i.e from 0 to 1, with granularity $\frac{1}{100}$.

- $R_{FS}$ with $w_{FS}=0$ is not affected by price volatility at all, thus incentivizes MEV sandwich attacks 
- $R_{FS}$ with $w_{FS}=1$ is highly sensitive to price volatility, thus maximizing the avoidance of MEV sandwich attacks


# NOTES
Actions to consider:
- Liquidity removal
- Force close existing $mtp$ and associated reward
- Swap
- more...will explore after attack exemplar

## Composite Mechanisms [NOTES]

### Open $mtp$
An agent puts in $\Delta x$ as collateral to perform an Open $mtp$ action with leverage $\eta$. This gives
$x_A = \Delta x$
$x_L = \eta \Delta x$

After a Borrow and Swap, the Open $mtp$ composite resolves to the below $\Delta y$

$$\Delta y =(1-\lambda_l) \frac{(1 + \eta)\Delta x\mathbf{Y}}{(1 + \eta)\Delta x+{\mathbf{X}}} + \lambda_l\frac{(1 + \eta)\Delta x\mathbf{Y}\mathbf{X}}{((1 + \eta)\Delta x+\mathbf{X})^2}$$

### Close $mtp$
$\Delta y$ is swapped to its equivalent amount in X-tokens in the $mtp$, minus the swap fee.

Once $\Delta y$ is taken out of custoday, it is swapped to obtain $\Delta x$ below. Excess Liabilities on the $mtp$ are computed and the $\Delta x$ amount is used to repay to close the $mtp$

The amount of X-tokens $\Delta x$ obtained through swapping $\Delta y$ is: 

$$\Delta x =(1-\lambda_l) \frac{(\Delta y)\mathbf{X}}{(\Delta y)+{\mathbf{Y}}} + \lambda_l\frac{(\Delta y)\mathbf{Y}\mathbf{X}}{((\Delta y)+\mathbf{Y})^2}$$

### Forced settlement by any address

Validators eventually would end up being the $mtp$ keepers, acquiring forced settlement rewards. As they have the privilege of reordering transactions, they are able to have superior performance in race games to trigger forced settlements. This allows them to be the first triggerer of a forced settlement, thus being able to collect the reward $R_{FS}$.

## Scenarios to analyze MEV [NOTES]

The scenarios below help us determine the net effect of performing a given action on the interim state versus perfomring the same action on the next state.

Scenarios have been structured in the following order 

**Both scenarios**
- System state: current state $S$
- User: performs Action 1 on $S$
- System state: interim state $S^{int}$

**Scenario A**
- System state: System resolves to next block $S^+$
- User: performs Action 2 on $S^+$

**Scenario B**
- User: performs Action 2 on $S^{int}$
- System state: System resolves to next block $S^+$

The scenarios below help us determine the net effect of performing a given action on the interim state versus perfomring the same action on the next state.

Consider the exemplar scenarios:
- Scenario A: User performs a swap in current block, and then performs a liquidity remove in the next block
- Scenario B: User performs a liquidity remove, then immediately follows it up with a swap such that they are both processed in the same block

### Scenario A
**Current Block**

User performs a swap of $x$ amount of X-tokens to $y$ amount of Y-tokens.

$$y =(1-\lambda_l) \frac{x\mathbf{Y}}{x+{\mathbf{X}}} + \lambda_l\frac{x\mathbf{Y}\mathbf{X}}{(x+\mathbf{X})^2}$$

This results in a change in the global state variable $\mathbf Y$ as amount $y$ is paid off to the user. The amount of Y-tokens in the liquidity pool in the intermediate state $Y^{int}$ directly following the swap is

$$ Y^{int} = Y - y$$

As no other actions are performed by the user in this block, this block resolves to the next state. No change, thus

$$ Y^+ = Y - y$$

**Next Block**

In the next block, user performs a Forced Settlement by Any Address by calling on an $mtp$ that is in a default health state. 

The following primitives are executed in order to complete the composite Forced Settlement by Any Address mechanism:

1. Excess_Liability_Computation_on_$mtp$

$$x_{L, t}^{E+} = (\beta^{\star}_{T-1} + \ln(t) \cdot \frac{\ln(2)}{\ln(T)}) \cdot (x_{L, T-1}^{P} + x_{L, T-1}^{E})$$

2. $mtp$ health computation
$$h(\mathbf x)^+ = \frac{x_A}{x_A + x_L^{P}+ x_L^{E}}$$

    This must indicate that the $mtp$ is in default i.e $h(\mathbf x)^+ \in (0,b]$ for the force close to take place.

- if $h(\mathbf x)^+ \leq b$
    - check if $x_i \geq x_L$ `# Agent holds $x_L$`
        - if $x_i \geq x_L$, proceed to Repay()
        - $mtp$ can be force closed by any address
    - else if $x_i < x_L$, 
        - $mtp$ needs to be force closed

3. Swap $y_C$ to $\Delta x$

$$\Delta x =(1-\lambda_l) \frac{(y_C)\mathbf{X}}{(y_C)+{\mathbf{Y}}} + \lambda_l\frac{(y_C)\mathbf{Y}\mathbf{X}}{((y_C)+\mathbf{Y})^2}$$

4. Compute the reward and pay it to the force close caller

    $$R_{FS} = R_{FS}(\cdot)x_A$$

    where $R_{FS}(\cdot)$ is a function of $h(\mathbf x)^+$

    *Pay_Caller_Reward()*
    - Subtract $R_{FS}$ from $\Delta x$
        - $\Delta x^+ = \Delta x - R_{FS}$
        - Go to Repay()
    - Pay $R_{FS}$ to caller agent
        - $x_{caller}^+ = x_{caller} + R_{FS}$

:::warning
As $R_{FS}$ is extracted from $\Delta x$, there is no change to $\mathbf X$ or $\mathbf Y$ at this point
:::
        
5. Following through with the *Repay()* from *Pay_Caller_Reward()*,

    *Repay()* 

    - Extract principal liabilites first
        - $mtp$ state update: $x_L^P = x_L^P - \Delta x$ while $\Delta x \leq x_L^P$
    - Extract excess liabilites next
        - $mtp$ state update: $x_L^E = x_L^E - \Delta x$ while $\Delta x \leq x_L^E - x_L^P$
    - If there's still remainder tokens left, this amount goes to the agent
        - Agent state update: $x_i^+ = x_i + (\Delta x - x_L^E - x_L^P)$


    $mtp$ ceases to exist. If $x^{P+}_L$ and $x^{E+}_L$ are 0, then we return the collateral $x_A$


:::warning
This $mtp$ was force closed, which implies that it was in default and 
$$h(\mathbf x)^+ = \frac{x_A}{x_A + x_L^{P}+ x_L^{E}} \in (0,b]$$ 

Threshold $b$ can be determined in a number of ways, set through governance or simply set by the liquidity pool opener based on some risk profile. 

So we use a general heuristic to distinguish default $mtp$'s:

- if $x_L > x_A$, then the $mtp$ is in default and can be force closed

Using this heuristic we can derive that $\Delta x$ would not be sufficient to cover all of $x_L$ i.e. both $x^{P+}_L$ and $x^{E+}_L$. 

The remainder amount to be covered $x^{rem}_L \in \mathbb R^+$ needs to be covered by the pool, thus this amount will be extracted from $\mathbf X$

$$ \mathbf X^+ = \mathbf X - x^{rem}_L$$
:::

> Note: Scenarios shelved for next week. Currently focused on higher priority exploration of MEV attack vectors.


## MEV - Solutions [NOTES]
The candidate solutions expressed below are pure explorations/proposals to consider, documented here to have a comprehensive view of all solutions we generate as a team and all recommended MEV mitigation ideas in the industry. They are currently not at the evaluation stage and we will revisit this section once we determine if MEV needs to accounted for in Sifchain, and if yes, after we choose which MEV attack types are severe enough to devise mitigations for. 

1. Limit dimensionality
    - Impose hard in-protocol constraints on dApp-layer behaviour.
    - This solution has limitations. 
        - It is not possible to predict all pathways of dApp behaviour and its evolution. Thus it is not possible to preclude all possible implementations of adverse user behaviour. 
        - Limiting dimensionality also implies a decrease in the degrees of freedom, thus it can also lead to the protocol being constrained to being non-Turing complete (desirable in specific domains)
2. Make MEV democratic 
    - If all miners/validators extract value equally quickly and efficiently without leaving any MEV on the table, the MEV attack space operates like a democratic and efficient market. This is desirable and allows for situations where MEV-like phenomena are beneficial (eg. in Cryptokitties where MEV incentivized miners to pay for the gas of birthing, in Uniswap where MEV encouraged the creation of arbitrage markets which kept the price up to date)
- Counter attacks are one way in which MEV-ridden systems can exist as an efficient market. These aren't a mitigation of MEV but rather a counter balance to existing attacks

## References
[Cryptoeconomics of Sifchain Margin Trading Paper](https://github.com/Sifchain/margin_trading_cadCAD/blob/main/Sifchain_Margin_Trading_Cryptoeconomics_Paper.md)