---
title: Autotask Uniwap v2 Rebase Sync
description: <Description is one full (short) sentence>
author: <a comma separated list of the author's or authors' name + GitHub username (in parenthesis), or name and email (in angle brackets). Example, FirstName LastName (@GitHubUsername), FirstName LastName <foo@bar.com>, FirstName (@GitHubUsername) and GitHubUsername (@GitHubUsername)>
discussions-to: <URL>
status: Draft
type: <Standards Track, Meta, or Informational>
category: <Core, Networking, Interface, or ERC> # Only required for Standards Track. Otherwise, remove this field.
created: <date created on, in ISO 8601 (yyyy-mm-dd) format>
requires: <EIP number(s)> # Only required when you reference an EIP in the `Specification` section. Otherwise, remove this field.
---
<!--
READ EIP-1 (https://eips.ethereum.org/EIPS/eip-1) BEFORE USING THIS TEMPLATE!
This is the suggested template for new EIPs. After you have filled in the requisite fields, please delete these comments.
Note that an EIP number will be assigned by an editor. When opening a pull request to submit your EIP, please use an abbreviated title in the filename, `eip-draft_title_abbrev.md`.
The title should be 44 characters or less. It should not repeat the EIP number in title, irrespective of the category.
TODO: Remove this comment before submitting
-->
## Autotask Uniswap v2 Sync Resolver
Uniswap remains a critical driving force in decentralized finance. Uniswap v3 is the leading decentralized exchange, but uniswap v2 poses substantial documented risks for liquidity providers and token bridge users alike. This proposal seeks to integrate OpenZeppelin Defender Relayer, AutoTask, and Sentinel with Uniswap exchange contract routers to reduce the impact of rebase tokens and impermanent loss through quick resolution syncing each exchange contract after a rebase or AMM transaction.
## Motivation
Uniswap is the cornerstone of decentralized finance and a critical gateway through which most web3 developers align their visions for the future with the network effect that is rampant innovation. It may seem like there are new attack vectors emerging constantly. However, it's usually new projects taking advantage of old vulnerabilities that have yet to be resolved. Uniswap version two is proof of this. Uniswap v2 still has cross-chain attack points that stem from the difference between Uniswap v2 and v3. The most notable example of how easy it is to drain v2 exchange pools of their liquidity Uniswap v2, under the right conditions, was the Nomad Bridge exploit. Impermanent loss still remains a significant problem for Uniswap v2 LP providers. Uniswap v2 documentation recommends LP providers execute a manual sync call after a token rebase to counteract significant impermanent loss or even exploits that lead to low volume pools going untracked. As the market expands across numerous chains, and layer2 solutions adopt zkRollups, the mass migrations of TVL from Uniswap v2 to v3 and other DEXs on layer 2 blockchains is imminent; more comprehensive monitoring and maintenance of exchange pool exploits will be necessary.
Uniswap creates arbitrage opportunities and pathways to liquidity un for DAOs and token creators across Optimism, Polygon, PolygonzkEVM, Arbitrum and mainnet. Uniswap trading activity also has a signifciant impact on toke econoic distribution altchains also poses As the decentralized exchange landscape becomes more multilayered and expansive, there are new attack vectors to exploit, cross-chain vulnerabilities that stem directly from the difference in how Uniswap v2 protocol reacts to negative rebase tokens, positive rebase tokens, in-pool token burns, Maximum Extracted Value bots (MEV), and Fee on Transfer Tokens, compared to its v3 counterpart. Despite Uniswap v3 holding the leading crypto DEX spot with over $3.14b TVL, and $684m trading volume; currently, Uniswap v2 still retains over $1.17b of liquidity with over $110m daily trading volume and is actually a favored option for developers listing their projects.
## Specification
<!--
The Specification section should describe the syntax and semantics of any new feature. The specification should be detailed enough to allow competing, interoperable implementations for any of the current Ethereum platforms (besu, erigon, ethereumjs, go-ethereum, nethermind, or others).
It is recommended to follow RFC 2119 and RFC 8170. Do not remove the key word definitions if RFC 2119 and RFC 8170 are followed.
TODO: Remove this comment before submitting
-->
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174.
## Scope
The Defender Relay service, OpenZeppelin's Autotask, or Sentinel for contract monitoring, provide the perfect solution to broken exchange contract pools on Uniswap V2. Defender supports a more secure experience for Liquidity providers as more TVL gradually migrates crosschain. We will build a feature-complete application integration hosted as extension atop the uniswap.info dashboard. This resource will utilize OpenZepplin’s Defender and AutoTask, or Sentinel service per the LP providers preference.
Pool “sync” calls, or send alert notifications when the need arises to manually sync a v2 pool. This addeed feature will use a Defender Bot setup or Proxy Contract Deployment for "Inclusive Fee on Transfer" token creators who’ve listed their tokens to Uniswap V2 pools, or DAOs who wish to continue supporting LPs in their communities who have done so, to automatically call on the ```solidity “SupportingFeeOnTransfer”``` function in the Uniswap router contract. Calling ```solidity “SupportingFeeOnTransfer”``` will adjust the ```solidty “amountOutMin”``` parameter prioritizing the recipient amount as opposed to the sending amount during invariant calculation.
## Team
[Simon Alexander Breedon](https://www.linkedin.com/in/simonbreedon/)
## Relevant Work
Alpha Fund AVA DAO (The Autonmous Value Authority)
We have also already begun building this application.
## Milestone
During the first three weeks, we’ll conduct research while simultaneously gathering all the necessary data. After that, we BUIDL, with an expected completion date within 90 days.
## Security Considerations
It is possible for private keys using ActiveTask to be revealed if handled through a browser.
#### Secrets
Autotask secrets are key-value case-sensitive pairs of strings, that can be accessed from any Autotask using the event.secrets object. You can define as many secrets as you need to be used by your Autotasks. Secrets are shared across all your Autotasks, and not specific to a single one.
```solidity
exports.handler = async function(event) {
const { mySecret, anApiKey } = event.secrets;
}
```
Connecting to a relayer to a Relayerinstead to simplify key management and transaction submissions.
Defender Relayers have many benefits, such as poking your contracts to trigger a state transition, the ability to update an on-chain oracle with external data, sending meta-transactions to build a gasless experience, react to sign-ups in an application by airdropping tokens to new users, sweeping funds from protocol contracts to secure wallets, and building bots for interacting with smart contract protocols.
Defender Relay allows you to send transactions via a regular HTTP API, and takes care of private key secure storage, transaction signing, nonce management, gas pricing estimation, and resubmissions. This way you don’t need to worry about securing your private keys in your backend scripts, or by monitoring your transactions to ensure they get mined.
It's also possible to do a netowrk call using Defender Network Relayer.
```javascript
const balance = await relayer.call('eth_getBalance', ['0x6b175474e89094c44da98b954eedeac495271d0f', 'latest']);
```
Security Needs more discussion.
#### Notifications
For LP providers seeking to execute manual `sync' calls after a rebase, OpenZeppelin has a Sentinel for notifications.
#### Sentinel
- The Defender Sentinel service offers three types of Sentinels Contract Sentinels, Forta Sentinels, and Forta Local Mode Sentinels.
- Contract Sentinels monitor transactions to a contract by defining conditions on events, functions, and transaction parameters.
- Forta Sentinels monitor Forta Alerts by defining conditions on Forta Bots, contract addresses, alert IDs, and severity.
- If a Sentinel matches a transaction or a Forta Alert based on defined conditions, it sends notifications via email, Slack, Telegram, Discord, Autotasks, and more.
- Use Sentinels to monitor transactions and Forta Alerts involving your smart contracts, other smart contracts, or Forta Bots.
- Sentinels can monitor sensitive functions, potentially dangerous transactions, and unexpected volumes of transactions or alerts.
## Timing
90 days
## Budget
$65,000 which includes the build-out and all future maintenance and support costs.
Appendix: Uniswap Protocol Spec
---
#### Uniswap v2 TWAP:
The Uniswap v2 protocol, specifically in the `UniswapV2Pair` contract, maintains variables to calculate the Time-Weighted Average Price (TWAP). For each asset `X` in the set `{0, 1}`, the variable `priceXCumulativeLast` after event `n + 1` represents the cumulative sum of:
```solidity
`(reserveY_n / reserveX_n) * timeElapsed_n`
```
Here, `(reserveY / reserveX)` denotes the price of asset `X` in terms of asset `Y`.
The following conditions apply:
- `reserveY_n` represents the reserve of asset `Y` (which is not equal to `X`) after event `n`.
- `reserveX_n` represents the reserve of asset `X` after event `n`.
- `timeElapsed_n` is the difference in block timestamps between events `n` and `n + 1`.
To compute the TWAP of asset `X` between block numbers `k1` and `k2`, the following formula is used:
```solidity
(currentCumulativePrice(k2) - currentCumulativePrice(k1)) / (blockTimestamp(k2) - blockTimestamp(k1))
```
The `currentCumulativePrice` function is defined as:
```solidity
function currentCumulativePrice(uint k) returns (uint) {
uint increment = uint(reserveX(k) / reserveY(k)) * (blockTimestamp(k) - blockTimestampLast(k));
return priceXCumulativeLast(k) + increment;
}
```
In order to validate this calculation in Axiom, the following slots and header fields from the `UniswapV2Pair` contract need to be fetched:
- `reserve0(k1)`, `reserve0(k2)`
- `reserve1(k1)`, `reserve1(k2)`
- `blockTimestampLast(k1)`, `blockTimestampLast(k2)`
- `priceXCumulativeLast(k1)`, `priceXCumulativeLast(k2)`
- `blockTimestamp(k1)`, `blockTimestamp(k2)`
### Uniswap v3 TWAP
A similar approach to the Uniswap v2 TWAP can be applied to compute the Uniswap v3 TWAP for cases where checkpoints have expired from the cache. In such cases, two quantities are computed. The tick is defined as:
```arduino
`t = floor(log(sqrt(1.0001 * sqrt(P))))'
```
And the inverse liquidity is defined as `1/L`. Uniswap v3 stores time-weighted accumulators of `tick * time` and `(1/L) * time`. The tick TWAP provides a geometric mean TWAP of discretized prices, and the TWAP of seconds weighted inverse liquidity can also be computed.
### Uniswap v2 and v3: Arbitrary weighted-time oracles (EMA, etc.)
To calculate oracles that are not supported by explicit accumulators in the Uniswap v2 or v3 protocols, an accumulation function is applied to a per-block function.
- For each block number `k` in the range `[k1, k2)`, the price of Token 0, denoted as `p_k`, is read. This can be obtained from:
- `UniswapV2Pair`: `reserve1(k) / reserve0(k)`
- `UniswapV3Pool`: `slot0(k).sqrtPriceX96 ** 2` (adjusted for fixed point)
Then, an arbitrary oracle function of `p_k` is computed based on the desired calculation:
- For median, the following is computed:
- Median over `k` in the range `[k1, k2)` of `p_k`
- For Exponential Moving Average (EMA) with a parameter `alpha`, the following is computed:
- Sum over `k` in the range `[k1, k2)` of `p_k * alpha^{k2 - k - 1}`
- This computation requires fixed-point arithmetic.
- For an arbitrary weighted-time average with weights `alpha_k`, the following is computed:
- Sum over `k` in the range `[k1, k2)` of `alpha_k * p_k`
- For sample volatility, the following is computed:
- `n/(n-1) * (sum_k p_k^2 - (sum_k p_k)^2 / n^2)`
These calculations require the following:
- Storage proofs for slots containing either `reserve0(k)` and `reserve1(k)` or `slot0(k)`.
- Fixed-point arithmetic for median, EMA, or average computations.
## Copyright
Copyright and related rights waived via [CC0](../LICENSE.md).