Osmosis
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Base-fee controller RFC **Author: Valardragon** One of the most important things for app-chains to iterate on is their fee market. A clever insight of the EIP-1559 work, is that we can abstract ~all the complexity for the end-user, and have them provide just two terms: `max_fee_amount, tip_amount`. We have the chain determine, via some mechanism, the base fee for a given tx. (The inputs into this algorithm are up to the chain) The user is then charged `base_fee + max_tip_amount`. If `base fee > max_fee_amount`, then no fee is charged and the tx reverts. Otherwise, `min(base_fee + max_tip_amount, max_fee_amount)` will be charged from the user. The key concern is we need this base fee to be easy for wallets to reason about. How do they choose this `max_fee`, and whats a reasonable tip. This RFP proposes an API, and a registry, with the goal that: - Enables easy additions of new fee markets for app-chains - Front-ends can easily determine reasonable max fee amounts ## Fee market candidate ideas We briefly list a few anticipated fee market ideas that we need to support, so we can keep these in mind. Theres a lot to do here, so the list is mostly to point out things that could induce new complexities, and we wish to abstract so wallets don't have to think about it. - direct EIP-1559 - EIP-1559 with features that respond to surges more directly (["AIMD"](https://hackmd.io/VoyaxCIoRoqd01U--NMV3g?both)) - So it becomes a bit harder to reason about the "max" base fee for normal users - multi-variate EIP-1559 for each "high-level" resource - E.g. independent base fees for bandwidth, compute, storage read/writes - Any/All of the above, with increasing fees for repeated access to the same state - So during an NFT mint, all txs to that NFT contract get higher fees, but all other txs remain relatively the same. - Protocol subsidization of certain types of txs - e.g. staking having a lower base fee - e.g. having swap fee count towards tx fee ## (Context) Front-end side needs We start with what information the wallet would need, as it will inform what needs to be exposed from the chain interface. Something thats nice, is that a wallet choosing how to reason about tips is basically independent of all of this. Its relatively easy to scan the chain, and determine what the tip standard price is. This changed how [metamask displayed & reasoned](https://metamask.io/1559/) about it. Screenshots posted below. But the intuition is that "priority" is really just the tip, which doesn't require guessing. You can just read the current market rate, and choose how you pay relative to market rate. So we see the following UX metamask switched to: Pre-eip1559 | Post-1559 :-------------------------:|:-------------------------: ![](https://images.ctfassets.net/9sy2a0egs6zh/7oAiLkDnO7ph6JLmA375r3/5747512f9a2739a2ce9144b9d71a1cbe/Gas_Estimate_Before.png) | ![](https://images.ctfassets.net/9sy2a0egs6zh/6c2nQDZgs8gcDQoCTx3GHM/e1cc7f8333573d82191b7b7112dc6833/Gas_Estimate_After.png) To generate such a UX, they'd have to get a way to: - Determine "market rate" of Tip's, and some quartile distribution of this - Query current base fee that applies to a given tx - Make some prediction around base fee volatility. - Some of this volatility is encompassed with `max_tip` if bidding higher on that. Today Metamask just gets this all by looking at the last block, nothing fancy. We should be designing something with ability to do a bit better than that. We should expose on-chain queries per block for: - 25th, 50th, 75th percentile of fee tip per unit gas in block B - Base fee if this tx was submitted now - Avg base fee for this type of tx in block B And then indexers could take this data, and create this over multiple blocks. ## Typescript library interface Any basefee algorithm in the registry should have an accompanying typescript object satisfying the following interface. ```typescript interface BaseFeeQuerier { // or whatever is the standard for rest is. querier: CosmJsClient; // does some one-time setup work, e.g. if your fee market has some parameters, // query the chain for them and cache them setup: () -> void; // get base fee for this set of []sdk_Msg at this block height. // Note that its up to the library to determine what queries it needs // to do. It should aim to do minimal queries to the chain, and leak // as little info about the msgs as required. // // So if there is nothing msg dependent for this algorithm, don't query // anything including the msgs. basefee: (block_number: number, msgs: sdk_Msg[]) => sdk_decimal; // same as above, but returns a distribution. // up to the algorithm to infer how to define low/p25/p50/p75/max // for message dependent base-fees, w/o many of that message in the last block. // we can work this out in more detail basefee_distribution: (block_number: number, msgs: sdk_Msg[]) => Distribution; // average tip for this "type" of transaction, in this block height. // same as above, the library should leak minimal info about the message, // depending on whats needed. tip: (block_number: number, msgs: sdk_Msg[]) => sdk_decimal; tip_distribution: (block_number: number, msgs: sdk_Msg[]) => Distribution; } interface Distribution { num_samples: number; low: sdk_decimal; // p stands for percentile p25: sdk_decimal; p50: sdk_decimal; p75: sdk_decimal; max: sdk_decimal; } ``` Then the wallet uses these queries. We expect wallets to in practice just query `basefee(last_block, msgs)` and `tip(last_block, msgs)` as is commonly done in Ethereum today. We expect the set `max_base_fee` to be some multiple of the `basefee` of the prior block. We leave these other distribution queries for people wanting more complex aggregations. ### Reasoning about base fee growth We explicitly do not include any queries for generically reasoning about the base fee in subsequent blocks. If wallets wish to do this, they should extrapolate this via generic means from historic base fees, or white-box something for the specific algorithm. As time goes on, and fee market experiments continue, we can maybe learn better generic methods to do this. But the "max" a base fee can grow to in (say) 5 blocks time should be large for surge-resiliency. It only grows larger as we get increasingly multi-dimensional fee markets. The actual max will likely trend to being ludicrously large (and never getting hit), so having this in the default API will likely result in users getting over-quoted prices. ## Data provider interfaces There should ideally be data providers who make a standard service to adapt the queries ran in the front-end, to give the distribution over block ranges. E.g. serving ```typescript interface BatchedBaseFeeQuerier { basefee_distribution: (start_block: number, end_block: number, msgs: sdk_Msg[]) => Distribution; tip_distribution: (start_block: number, end_block: number, msgs: sdk_Msg[]) => Distribution; } ``` ## Chain-side interface The interface the chain exposes really comes from the typescript library. It just has to be able to look at a block, and respond to the queries that the library makes. What we need to standardize on across all chains, is how we format the tx body, the actual queries are abstracted behind the typescript interface. ### Tx interface I'm very amenable to change this entire section, this is just a suggestion from my end. Its a design goal that for most chains, we support both the "old" fee format, and this new fee format of `(max_fee, max_tip)`. For the old fee format, we can interpret their old fee F as `(max_fee=F, max_tip=F)`. With that as context, then we can actually re-use the old tx.proto field for Fee: https://github.com/cosmos/cosmos-sdk/blob/main/proto/cosmos/tx/v1beta1/tx.proto#L207-L209 Ideally, we'd rename `amount` to `max_amount`. Also, we'd ideally add a new field directly into this, called `max_tip` for amount (thats optional), as that would be serialization compatible with old libraries. That would be breaking, so we should eventually go to that upon SDK changes. But in the interrim, we can use the tx "critical extensions", to express `max_tip` amount until then. ### Default stack to make implementation easy #### Goal As we want to allow chains to change a lot of the fee market stack, its too complex to write a software stack easily write _any_ imagined base-fee controller. Instead I propose we make a default interface to ease iteration, for any base-fee controller that is _isolated_. An _isolated_ controller is going to be one where in block N, the base-fees paid by `tx_1` and `tx_2` are fully independent. (So `tx_1` using more of one resource, can't increase the base fee of `tx_2` for the same resource) Importantly, both `tx_1` and `tx_2` will affect base fees in the _next_ block, but not for each other in the same block. This isolation still enables different fee controllers for gas, bandwidth, i/o, and different controllers per message type. It does not enable increase of cost, for repeated access to the same state within a block. It does enable this for repeated access across blocks. #### Proposal ##### Fee deduction side There should be a `base-fee-controller` ante-handler, that has access to a unique portion of state just for it. (e.g. taking a prefix store that only it has access to) The base-fee controller should take in a base-fee algorithm, and recipients for base-fee and tip. Lets define the interface for a base-fee algorithm: ```go type BaseFeeAlgo interface { GetRequiredBaseFee(ctx, tx sdk.Tx) sdk.Coin GetBaseFeeReceiver(ctx) sdk.Addr GetTipReceiver(ctx) sdk.Addr } ``` The `base-fee-controller` ante-handler will then run as follows: ```go func (h handler) DeductFees(ctx, tx) error { feePayer := tx.GetFeePayer() maxFee := tx.GetMaxFee() baseFee := h.GetRequiredBaseFee(ctx, tx) if maxFee < baseFee { return errors.New("insufficient base fee, minimum is %d, got %d", baseFee, maxFee) } maxTip, isLegacy := tx.GetMaxTip() if isLegacy { maxTip = maxFee } remainingFee := maxFee - baseFee tipAmt := min(remainingFee, maxTip) err1 := h.DeductBaseFee(feepayer, baseFee) err2 := h.DeductTip(feepayer, tipAmt) if err1 != nil { return err1 } if err2 != nil { return err2 } } ``` ##### Query serving side We similarly run into a problem where its not obvious how to abstract the queries when different msg types can have different fees. As if your base-fee algorithm is transaction aware, then you need to different queries type-script side to make it sensible. For now we assume there will be one standard implementation people use for base-fee algorithms that don't depend on the type of transactions, and leave simplifying the query interface for tx-type dependent base fees to future work. (Its valuable to get this out as is, and wallet side everything will gracefully work with this change) We don't show the sample implementation in this case, since its pretty simple end block logic. (Scan all txs, read base fee & tip, save the distribution data to state) ### Mempool interface The app-chain is already responsible for making a mempool that interoperates with its fee algorithm. So conceptually nothing changes, if you modify the fee market you should consider modifying the mempool. We suggest two common defaults that should emerge, and then greater complexity becomes app-specific. The choice of general mempool approach (priority vs fifo) should appear in the chain-registry. Then the typescript libraries can ensure that for fifo mempools tip is always near-zero. #### Priority based mempools This one is pretty simple, have a standard ethereum-like mempool, with txs satisfying base-fee requirement sorted by tip. If multiple txs have the same tip, sort FIFO (cref [this being done in geth](https://github.com/ethereum/go-ethereum/issues/21350)) #### FIFO based mempools For chains where sandwitching is an active concern, it seems better to actually standardize around tipless txs, and have all txs sorted by first-in-first-out order. Note that you already have a "time to get on-chain" somewhat guaranteed here -- base fee price keeps going up, pricing out people ahead in queue. So your node maintains a mempool with the main list being txs meeting base-fee, sorted by receipt time. It also maintains a (small) list of txs not meeting base fee, with receipt times still remembered. How we resource bound this is a bit of an open question, but I'd suggest: - reject incoming txs below last base-fee - prune anything from this list after its been there for k minutes - once max `active + inactive` list length is reached, new txs meeting base fee pop off lowest base fee txs from this inactive list. This mempool should also have replace-by-fee semantics. (So if an address submits a higher fee tx w/ the same sequence, replace the old tx but keep that older receipt time) Features can be built off this as the base. ## Registry interface The registry should be a github repo, with a registry listing: - enum id - entry name - npm package name, version, hash - typescript github repo With time, hopefully tooling emerges, that enables a wallet to import a wrapper repo, and just specify the enum_id's it wishes to include at compile time. (Effectively mimicking rust feature flags, with the registry) ## Anticipated questions ### How should we determine registry enums To be honest, I'm very unopinionated here. I'm fine with it literally being PR number to whatever repo this is lol. ### What about Escalator fees? Escalator fees can still be done, thats actually a different layer of abstraction that can be done on top of this. Whats nice is staircase fees can be designed around _any_ base-fee market :) ### Fee distribution This up to the chain to decide as today. They could choose to burn base-fees, follow the distribution we do today in cosmos, etc. This is something that affects the market structure, but is thankfully abstracted to not be the wallets job! ### How will tips play out? This depends on mempool design, and fee distribution design! In Ethereum base fee is burned, but we don't need to do the same. We can distribute across many validators (smoothening), have some collected by community pool, etc. So this depends on details of each app :) ### How do we ensure wallets are truly able to easily extend Inspired a bit by [this post on the extensibility of TLS](https://www.imperialviolet.org/2016/05/16/agility.html), its important to ensure were getting a wallet-side ecosystem that truly lets us move between these mechanisms. I think ensuring as a community that we add more enums to the spec within the first year will help enforce agility of this interface. ### Anticipated initial registry enums - Base EIP-1559 - `setup()` will indicate if the default network mempool is priority or fifo - AIMD

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully