-
Notifications
You must be signed in to change notification settings - Fork 109
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added trade tracker instead of amm trade tracker, and a readme
- Loading branch information
Showing
6 changed files
with
223 additions
and
511 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Fee token pricer | ||
|
||
When a chain is in AnyTrust mode transaction data is posted to an alternative data availability provider. However when in a chain is in rollup mode, transaction data is posted to the parent chain which the batch poster must pay for. When not using a custom fee token, the cost of posting this batch is relayed to the child chain where the batch poster will be reimbursed from user fees. However when the child chain is using a different fee token to the parent chain the data cost will paid in units of the parent chain fee token, and refunded in units of the child chain fee token. Therefore in order to refund the correct amount an exchange rate between the tokens must be used. This is what the fee token pricer provides. | ||
|
||
## Implementation approach | ||
When the batch poster posts data to the parent chain a batch spending report is produced. This batch spending report contains the gas price paid by the poster, and the amount of data in the batch. In order to reimburse the batch poster the correct amount in child chain fee tokens, the gas price in the batch spending report is scaled by the child to parent chain token price. In order to get this price the SequencerInbox calls `getExchangeRate` function on the fee token pricer at the time of creating a report. The chain owner can update the fee token pricer to a different implementation at any time. | ||
|
||
Although the batch poster is receiving reimbursement in units of the child chain fee token rather than the parent chain units which they used to pay for gas, the value that they are reimbursed should be equal to the value that they paid. | ||
|
||
## Fee token pricer options | ||
A chain can choose different fee token pricer implementations to retrieve the exchange rate. Since the fees are reimbursed in child chain tokens but paid for in the parent chain tokens, there is an exchange rate risk. If the price deviates a lot before the batch poster converts the child chain currency back to parent chain currency, they may end up receiving less or more tokens than they originally paid for in gas. Below are some implementation options for the fee token pricer that have different tradeoffs for the batch poster and chain owner. Since the chain owner can change the fee token pricer at any time, the batch poster must always trust the chain owner not to do this for malicious purpose. | ||
|
||
**Note.** There are some examples of these pricers in this repo, however none of these examples have been audited or properly tested, and are not ready for production use. These are example implementations to give an idea of the different options. Chain owners are expected to implement their own fee token pricer. | ||
|
||
### Option 1 - Chain owner defined oracle | ||
In this option the chain owner simply updated the exchange rate manually. This is the simplest option as it requires no external oracle or complicated implementation. However, unless the chain owner updates the price regularly it may diverge from the real price, causing under or over reimbursement. Additionally, unless a further safe guards are added, the batch poster must completely trust the chain owner to reimburse the correct amount. This option makes the most sense for a new chain, and where the batch poster and chain owner are the same entity or have a trusted relationship. The batch poster must also have an appetite for exchange risk, however this can be mitigated by artificially inflating the price to reduce the chance the batch poster is under reimbursed. | ||
|
||
### Option 2 - External oracle | ||
In this option an external oracle is used to fetch the exchange rate. Here the fee token pricer is responsible for ensuring the price is in the correct format and applying any safe guards that might be relevant. This option is easier to maintain that option 1. since an external party is reponsible for keep an up to date price on chain. However this places trust in the external party to keep the price up to date and to provide the correct price. To that end the pricer may apply some safe guards to avoid the price going too high or too low. This option also carries the same exchange risk as option 1, so a similar mitigation of marking up the price by a small amount might help to avoid under reimbursement | ||
|
||
An example of this approach can be seen in [UniswapV2TwapPricer.sol](./uniswap-v2-twap/UniswapV2TwapPricer.sol). | ||
|
||
### Option 3 - Exchange rate tracking | ||
In this option it is assumed the batch poster has units of the child chain token and needs to trade them for units of the parent chain token to pay for the gas. They can record the exchange rate they used for this original trade in the fee token pricer, which will return that price when the batch poster requests an exchange rate to use. This removes the exchange risk problem, at the expense of a more complex accounting system in the fee token pricer. In this option the batch poster is implicitly a holder of the same number of child chain tokens at all times, they are not guaranteed any number of parent chain tokens. | ||
|
||
The trust model in this approach is not that the batch poster is forced to honestly report the correct price, but instead that the batch poster can be sure that they'll be refunded the correct amount. | ||
|
||
An example of this approach can be seen in [TradeTracker.sol](./trade-tracker/TradeTracker.sol). |
98 changes: 98 additions & 0 deletions
98
test/foundry/fee-token-pricers/trade-tracker/TradeTracker.sol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
// SPDX-License-Identifier: MIT | ||
pragma solidity ^0.8.0; | ||
|
||
import {IFeeTokenPricer} from "../../../../src/bridge/ISequencerInbox.sol"; | ||
import {IGasRefunder} from "../../../../src/libraries/IGasRefunder.sol"; | ||
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; | ||
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; | ||
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; | ||
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; | ||
|
||
abstract contract TradeTracker is IFeeTokenPricer, IGasRefunder { | ||
using SafeERC20 for IERC20; | ||
|
||
uint8 public immutable childTokenDecimals; | ||
uint256 public immutable calldataCost; | ||
address public immutable sequencerInbox; | ||
|
||
uint256 public thisChainTokenReserve; | ||
uint256 public childChainTokenReserve; | ||
|
||
error NotSequencerInbox(address caller); | ||
error InsufficientThisChainTokenReserve(address batchPoster); | ||
error InsufficientChildChainTokenReserve(address batchPoster); | ||
|
||
constructor(uint8 _childTokenDecimals, uint256 _calldataCost, address _sequencerInbox) { | ||
childTokenDecimals = _childTokenDecimals; | ||
calldataCost = _calldataCost; | ||
sequencerInbox = _sequencerInbox; | ||
} | ||
|
||
// @inheritdoc IFeeTokenPricer | ||
function getExchangeRate() public view returns (uint256) { | ||
uint256 thisChainTokens = thisChainTokenReserve; | ||
uint256 childChainTokens = childChainTokenReserve; | ||
// if either of the reserves is empty the spender will receive no reimbursement | ||
if (thisChainTokens == 0 || childChainTokens == 0) { | ||
return 0; | ||
} | ||
|
||
// gas tokens on this chain always have 18 decimals | ||
return (childChainTokens * 1e18) / thisChainTokens; | ||
} | ||
|
||
/// @notice Record that a trade occurred. The sub contract can choose how and when trades can be recorded | ||
/// but it is likely that the batchposter will be trusted to report the correct trade price. | ||
/// @param thisChainTokensPurchased The number of this chain tokens purchased | ||
/// @param childChainTokensPaid The number of child chain tokens purchased | ||
function recordTrade(uint256 thisChainTokensPurchased, uint256 childChainTokensPaid) internal { | ||
thisChainTokenReserve += thisChainTokensPurchased; | ||
childChainTokenReserve += scaleTo18Decimals(childChainTokensPaid); | ||
} | ||
|
||
/// @notice A hook to record when gas is spent by the batch poster | ||
/// Matches the interface used in GasRefundEnable so can be used by the caller as a gas refunder | ||
/// @param batchPoster The address spending the gas | ||
/// @param gasUsed The amount of gas used | ||
/// @param calldataSize The calldata size - will be added to the gas used at some predetermined rate | ||
function onGasSpent( | ||
address payable batchPoster, | ||
uint256 gasUsed, | ||
uint256 calldataSize | ||
) external returns (bool) { | ||
if (msg.sender != sequencerInbox) revert NotSequencerInbox(msg.sender); | ||
|
||
// each time gas is spent we reduce the reserves | ||
// to represent what will have been refunded on the child chain | ||
|
||
gasUsed += calldataSize * calldataCost; | ||
uint256 thisTokenSpent = gasUsed * block.basefee; | ||
uint256 exchangeRateUsed = getExchangeRate(); | ||
uint256 childTokenReceived = exchangeRateUsed * thisTokenSpent / 1e18; | ||
|
||
if (thisTokenSpent > thisChainTokenReserve) { | ||
revert InsufficientThisChainTokenReserve(batchPoster); | ||
} | ||
thisChainTokenReserve -= thisTokenSpent; | ||
|
||
if (childTokenReceived > childChainTokenReserve) { | ||
// it shouldn't be possible to hit this revert if the maths of calculating an exchange rate are correct | ||
revert InsufficientChildChainTokenReserve(batchPoster); | ||
} | ||
childChainTokenReserve -= childTokenReceived; | ||
|
||
return true; | ||
} | ||
|
||
function scaleTo18Decimals( | ||
uint256 amount | ||
) internal view returns (uint256) { | ||
if (childTokenDecimals == 18) { | ||
return amount; | ||
} else if (childTokenDecimals < 18) { | ||
return amount * 10 ** (18 - childTokenDecimals); | ||
} else { | ||
return amount / 10 ** (childTokenDecimals - 18); | ||
} | ||
} | ||
} |
97 changes: 97 additions & 0 deletions
97
test/foundry/fee-token-pricers/trade-tracker/TradeTracker.t.sol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
// SPDX-License-Identifier: MIT | ||
pragma solidity ^0.8.0; | ||
|
||
import "forge-std/Test.sol"; | ||
import {TradeTracker, IERC20} from "./TradeTracker.sol"; | ||
import "../../../../src/bridge/SequencerInbox.sol"; | ||
import {ERC20Bridge} from "../../../../src/bridge/ERC20Bridge.sol"; | ||
import "@openzeppelin/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol"; | ||
|
||
import "../../util/TestUtil.sol"; | ||
|
||
contract SimpleTradeTracker is TradeTracker { | ||
constructor( | ||
address _sequencerInbox | ||
) TradeTracker(6, 16, _sequencerInbox) {} | ||
|
||
function trade(uint256 thisChainTokens, uint256 childChainTokens) public { | ||
recordTrade(thisChainTokens, childChainTokens); | ||
} | ||
} | ||
|
||
contract TrackerTest is Test { | ||
address public batchPoster = makeAddr("batchPoster"); | ||
address public seqInbox = makeAddr("seqInbox"); | ||
|
||
function testExchangeRate() public { | ||
SimpleTradeTracker tradeTracker = new SimpleTradeTracker(seqInbox); | ||
|
||
uint256 thisChainReserve = 10e18; | ||
uint256 childChainReserve = 100e6; | ||
|
||
vm.startPrank(address(this), batchPoster); | ||
assertEq(tradeTracker.getExchangeRate(), 0); | ||
|
||
// do a trade and set the exchange rate | ||
uint256 exRate1 = (childChainReserve * 1e18 / thisChainReserve) * 1e12; | ||
tradeTracker.trade(thisChainReserve, childChainReserve); | ||
assertEq(tradeTracker.getExchangeRate(), exRate1); | ||
|
||
// trade again at the same rate | ||
tradeTracker.trade(thisChainReserve, childChainReserve); | ||
assertEq(tradeTracker.getExchangeRate(), exRate1); | ||
|
||
// trade again at different rate | ||
tradeTracker.trade(thisChainReserve / 2, childChainReserve); | ||
uint256 exRate2 = (childChainReserve * 3 * 1e18 / (thisChainReserve * 5 / 2)) * 1e12; | ||
assertEq(tradeTracker.getExchangeRate(), exRate2); | ||
|
||
vm.stopPrank(); | ||
} | ||
|
||
function testOnGasSpent() public { | ||
vm.fee(1 gwei); | ||
|
||
SimpleTradeTracker tradeTracker = new SimpleTradeTracker(seqInbox); | ||
|
||
uint256 gasUsed = 300_000; | ||
uint256 calldataSize = 10_000; | ||
|
||
vm.startPrank(address(seqInbox), batchPoster); | ||
vm.expectRevert( | ||
abi.encodeWithSelector( | ||
TradeTracker.InsufficientThisChainTokenReserve.selector, batchPoster | ||
) | ||
); | ||
tradeTracker.onGasSpent(payable(batchPoster), gasUsed, calldataSize); | ||
|
||
// trade some, but not enough | ||
tradeTracker.trade( | ||
(gasUsed - 1000 + calldataSize * tradeTracker.calldataCost()) * block.basefee, | ||
10 * 10 ** tradeTracker.childTokenDecimals() | ||
); | ||
vm.expectRevert( | ||
abi.encodeWithSelector( | ||
TradeTracker.InsufficientThisChainTokenReserve.selector, batchPoster | ||
) | ||
); | ||
tradeTracker.onGasSpent(payable(batchPoster), gasUsed, calldataSize); | ||
|
||
// trade some more | ||
tradeTracker.trade(10000 * block.basefee, 10 * 10 ** tradeTracker.childTokenDecimals()); | ||
uint256 exchangeRateBefore = tradeTracker.getExchangeRate(); | ||
tradeTracker.onGasSpent(payable(batchPoster), gasUsed, calldataSize); | ||
|
||
uint256 thisChainTokensUsed = | ||
(gasUsed + calldataSize * tradeTracker.calldataCost()) * block.basefee; | ||
uint256 childChainTokensUsed = thisChainTokensUsed * exchangeRateBefore / 1e18; | ||
uint256 thisChainReserveAfter = ( | ||
(10000 + gasUsed - 1000 + calldataSize * tradeTracker.calldataCost()) * block.basefee | ||
- thisChainTokensUsed | ||
); | ||
uint256 childChainReserveAfter = | ||
(20 * 10 ** tradeTracker.childTokenDecimals() * 1e12) - childChainTokensUsed; | ||
uint256 exchangeRateAfter = childChainReserveAfter * 1e18 / thisChainReserveAfter; | ||
assertEq(tradeTracker.getExchangeRate(), exchangeRateAfter); | ||
} | ||
} |
171 changes: 0 additions & 171 deletions
171
test/foundry/fee-token-pricers/uniswap-v2-trade-tracker/AmmTradeTracker.sol
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.