Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fee token pricers #281

Open
wants to merge 39 commits into
base: custom-fee-rollup
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
960d7da
Add ConstantExchangeRatePricer
gvladika Sep 30, 2024
e3cf8ed
Add OwnerAdjustableExchangeRatePricer
gvladika Sep 30, 2024
d0d31d3
Add uniswap v2 dependency
gvladika Sep 30, 2024
fcd2938
Add uniswap lib
gvladika Sep 30, 2024
0513e38
Uniswap v2 twap draft
gvladika Oct 1, 2024
cf9a962
Use local math files
gvladika Oct 2, 2024
0cb90fd
Return exchange rate
gvladika Oct 2, 2024
640a497
AMM trade tracker draft
gvladika Oct 2, 2024
93df126
Return exchange rate
gvladika Oct 2, 2024
d29724e
Add comments
gvladika Oct 2, 2024
3ce93dd
Fetch tokens
gvladika Oct 2, 2024
e0c7b7e
Add gas reporting hook
gvladika Oct 2, 2024
112c947
Update internal state
gvladika Oct 3, 2024
35aa8ac
Track exchange rate per spender
gvladika Oct 4, 2024
a90cc14
No need for ownable
gvladika Oct 4, 2024
85799f7
Avoid underflow
gvladika Oct 4, 2024
6ecce41
Owner sets deafult exchange rate
gvladika Oct 7, 2024
fc92cd2
Prvoide min amount of eth received to protect from slippage
gvladika Oct 7, 2024
a026be3
Scale to 18 decimals
gvladika Oct 7, 2024
db28e56
Use safe erc20
gvladika Oct 8, 2024
84090aa
Test swapTokenToEth
gvladika Oct 8, 2024
c003251
Test getExchangeRate
gvladika Oct 8, 2024
93fba73
Fix >18 decimals scaling
gvladika Oct 9, 2024
8475b0a
Simplify token spending calculation
gvladika Oct 9, 2024
2e5b248
Test state updates after batch is posted
gvladika Oct 9, 2024
a76a104
Make calldata cost adjustable
gvladika Oct 9, 2024
635cb84
No updates if ethAcc is 0
gvladika Oct 9, 2024
382b7f5
Control who can call gas hook and update internal state
gvladika Oct 9, 2024
58ca937
Add events and custom error
gvladika Oct 9, 2024
5ba5abc
Provide trade deadline from outside
gvladika Oct 23, 2024
95a693e
Move fork tests to separate file
gvladika Oct 24, 2024
9193c21
Merge branch 'custom-fee-rollup' into fee-token-pricers
gvladika Oct 24, 2024
049c5b2
Merge from custom-fee-rollup
yahgwai Nov 29, 2024
d7d3d1a
Toml update
yahgwai Nov 29, 2024
89542c1
Formatting and uniswap install
yahgwai Nov 29, 2024
9f56d06
Added trade tracker instead of amm trade tracker, and a readme
yahgwai Dec 13, 2024
b7a86ac
Updated readme and comments
yahgwai Dec 20, 2024
0858206
Merge branch 'custom-fee-rollup' into fee-token-pricers
yahgwai Dec 20, 2024
b757f17
Formatting
yahgwai Dec 20, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
src = 'src'
out = 'out'
libs = ['node_modules', 'lib']
cache_path = 'forge-cache/sol'
test = 'test/foundry'
cache_path = 'forge-cache/sol'
optimizer = true
optimizer_runs = 2000
via_ir = false
Expand All @@ -11,14 +12,16 @@ remappings = ['ds-test/=lib/forge-std/lib/ds-test/src/',
'forge-std/=lib/forge-std/src/',
'@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/',
'@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/',
'@offchainlabs/upgrade-executor/=node_modules/@offchainlabs/upgrade-executor/']
'@offchainlabs/upgrade-executor/=node_modules/@offchainlabs/upgrade-executor/',
'@uniswap/v2-core/=node_modules/@uniswap/v2-core/contracts',
'@uniswap/lib/=node_modules/@uniswap/lib/contracts']
fs_permissions = [{ access = "read", path = "./"}]

[profile.yul]
src = 'yul'
out = 'out/yul'
libs = ['node_modules', 'lib']
cache_path = 'forge-cache/yul'
cache_path = 'forge-cache/yul'
remappings = []
auto_detect_remappings = false

Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@
"@typescript-eslint/eslint-plugin": "^5.14.0",
"@typescript-eslint/eslint-plugin-tslint": "^5.27.1",
"@typescript-eslint/parser": "^5.14.0",
"@uniswap/lib": "^4.0.1-alpha",
"@uniswap/v2-core": "^1.0.1",
"audit-ci": "^6.6.1",
"chai": "^4.3.4",
"dotenv": "^16.3.1",
Expand Down
23 changes: 23 additions & 0 deletions test/foundry/fee-token-pricers/ConstantExchangeRatePricer.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IFeeTokenPricer} from "../../../src/bridge/ISequencerInbox.sol";

// NOTICE: This contract has not been audited or properly tested. It is for example purposes only

/// @title A constant price fee token pricer
/// @notice The most simple kind of fee token pricer, does not account for any change in exchange rate
contract ConstantExchangeRatePricer is IFeeTokenPricer {
uint256 immutable exchangeRate;

constructor(
uint256 _exchangeRate
) {
exchangeRate = _exchangeRate;
}

// @inheritdoc IFeeTokenPricer
function getExchangeRate() external view returns (uint256) {
return exchangeRate;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IFeeTokenPricer} from "../../../src/bridge/ISequencerInbox.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

/// @title A uniswap twap pricer
/// @notice An example of a type 1 fee token pricer. The owner can adjust the exchange rate at any time
/// to ensure the batch poster is reimbursed an appropriate amount on the child chain
contract OwnerAdjustableExchangeRatePricer is IFeeTokenPricer, Ownable {
uint256 public exchangeRate;

event ExchangeRateSet(uint256 newExchangeRate);

constructor(
uint256 initialExchangeRate
) Ownable() {
exchangeRate = initialExchangeRate;
emit ExchangeRateSet(initialExchangeRate);
}

function setExchangeRate(
uint256 _exchangeRate
) external onlyOwner {
exchangeRate = _exchangeRate;
emit ExchangeRateSet(_exchangeRate);
}

// @inheritdoc IFeeTokenPricer
function getExchangeRate() external view returns (uint256) {
return exchangeRate;
}
}
41 changes: 41 additions & 0 deletions test/foundry/fee-token-pricers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# 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 types

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 types 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.

### Type 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.

### Type 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).

### Type 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 not 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).

## Fee token pricer implementation considerations

When implementing a fee token pricer the trust assumptions of each of the involved parties must be considered.

- **Chain owner** - the chain owner is always trusted as they can change the fee token pricer at any time
- **Batch poster** - the batch poster is already trusted to provide valid batches that don't inflate data costs for users. In a type 3 fee token pricer they are additionally trusted to report the correct trade price
- **External parties** - in a type 2 fee token pricer an external party is trusted to provide up to date price information. If the price provided is too low the batch poster will be under-refunded, if the price provided is too high the batch poster will be over-refunded. To that end implementers should consider including price guards in their pricer to ensure the external can't provide values too far from the correct price. As an example, if the external party chose to set the price to max(uint) it would drain the child chain's gas pool, and dramatically raise the price for users. The chain owner would need to call admin functions to reset the sytem. This could be avoided by putting logic in the pricer to prevent extreme values.
98 changes: 98 additions & 0 deletions test/foundry/fee-token-pricers/trade-tracker/TradeTracker.sol
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 test/foundry/fee-token-pricers/trade-tracker/TradeTracker.t.sol
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);
}
}
Loading
Loading