-
Notifications
You must be signed in to change notification settings - Fork 2
Fee selection for Ledger & offline flow #66
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
Open
graikos
wants to merge
3
commits into
main
Choose a base branch
from
fee_selection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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,130 @@ | ||
| // TODO: verify Mesa per-block zkApp command cap; 12 is unconfirmed and | ||
| // taken from a working assumption. Once confirmed against Mesa node config, | ||
| // remove this TODO. | ||
| const TOP_N = 12; | ||
|
|
||
| // Mina spec minimum fee per account update, per mina-signer's | ||
| // getAccountUpdateMinimumFee docstring ("0.001 according to the Mina spec"). | ||
| // 0.001 MINA = 1e6 nanomina. | ||
| export const MIN_FEE_PER_AU = 1e6; | ||
|
|
||
| // The daemon wraps each pooled command in a result object; the raw command | ||
| // JSON (mina-signer wire format, fee in nanomina) lives under `zkappCommand` | ||
| // — same convention as block `zkappCommands` and the sendZkapp response. | ||
| interface PooledZkappCommandResult { | ||
| zkappCommand: { | ||
| feePayer: { body: { fee: string } }; | ||
| accountUpdates: unknown[]; | ||
| }; | ||
| } | ||
|
|
||
| export interface FeeEstimate { | ||
| fee: number; | ||
| feePerAU: number; | ||
| sampleSize: number; | ||
| } | ||
|
|
||
| const QUERY = `{ | ||
| pooledZkappCommands { | ||
| zkappCommand { | ||
| feePayer { body { fee } } | ||
| accountUpdates { body { publicKey } } | ||
| } | ||
| } | ||
| }`; | ||
|
|
||
| function median(sorted: number[]): number { | ||
| const n = sorted.length; | ||
| if (n === 0) throw new Error('median of empty array'); | ||
| const mid = Math.floor(n / 2); | ||
| return n % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]; | ||
| } | ||
|
|
||
| /** | ||
| * Estimate a zkApp tx fee from the node's current mempool. | ||
| * | ||
| * Algorithm: | ||
| * 1. Query pooledZkappCommands for fee + accountUpdates. | ||
| * 2. Compute fee-per-account-update for each entry. | ||
| * 3. Sort descending, take top TOP_N (= 12). | ||
| * 4. Take the median fee-per-AU, floored at MIN_FEE_PER_AU. | ||
| * 5. Multiply by `accountUpdateCount` for the caller's tx. | ||
| * | ||
| * NOTE: median-of-top-N from the mempool reflects what is *waiting*, not what is | ||
| * *clearing*. In a quiet mempool the raw median can be near zero, so the per-AU | ||
| * rate is floored at the spec minimum, the result is always a fee the pool | ||
| * accepts for `accountUpdateCount` AUs. Callers remain responsible for any | ||
| * market-level floor (see resolveZkappFee). | ||
| */ | ||
| export async function estimateZkappFee( | ||
| graphqlEndpoint: string, | ||
| accountUpdateCount: number, | ||
| ): Promise<FeeEstimate> { | ||
| if (accountUpdateCount <= 0) { | ||
| throw new Error(`accountUpdateCount must be positive, got ${accountUpdateCount}`); | ||
| } | ||
|
|
||
| const res = await fetch(graphqlEndpoint, { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ query: QUERY }), | ||
| }); | ||
| if (!res.ok) { | ||
| throw new Error(`mempool query failed: HTTP ${res.status}`); | ||
| } | ||
| const json = await res.json(); | ||
| if (json.errors) { | ||
| throw new Error(`mempool query errors: ${JSON.stringify(json.errors)}`); | ||
| } | ||
| const pool: PooledZkappCommandResult[] = json.data?.pooledZkappCommands ?? []; | ||
|
|
||
| const feePerAU: number[] = []; | ||
| for (const entry of pool) { | ||
| const cmd = entry.zkappCommand; | ||
| const auCount = cmd?.accountUpdates?.length ?? 0; | ||
| if (auCount === 0) continue; | ||
| const fee = Number(cmd?.feePayer?.body?.fee); | ||
| if (!Number.isFinite(fee) || fee < 0) continue; | ||
| feePerAU.push(fee / auCount); | ||
| } | ||
| if (feePerAU.length === 0) { | ||
| throw new Error('mempool empty or no usable entries'); | ||
| } | ||
|
|
||
| feePerAU.sort((a, b) => b - a); | ||
| const top = feePerAU.slice(0, TOP_N); | ||
| const medianPerAU = median([...top].sort((a, b) => a - b)); | ||
| const flooredPerAU = Math.max(medianPerAU, MIN_FEE_PER_AU); | ||
|
|
||
| return { | ||
| fee: Math.ceil(flooredPerAU * accountUpdateCount), | ||
| feePerAU: flooredPerAU, | ||
| sampleSize: top.length, | ||
| }; | ||
| } | ||
|
|
||
| // Flat fallback when the mempool is empty or the query fails, and the floor | ||
| // under any mempool-derived estimate. 0.01 MINA covers 10 AUs at the spec | ||
| // minimum. The floor deliberately assumes 10 AUs rather than | ||
| // DEFAULT_AU_ESTIMATE: the estimate multiplies by an *assumed* AU count, but | ||
| // the built tx can carry more (per-row receivers, fundNewAccount, child | ||
| // setup) — flooring at 4 AUs could yield a sub-minimum fee the pool rejects. | ||
| // TODO: revisit if a multisig tx ever exceeds 10 AUs. | ||
| export const EMPTY_MEMPOOL_FALLBACK_FEE = 1e7; | ||
|
|
||
| // AU count to assume when estimating fees for multisig flows where the actual | ||
| // count isn't known until after Mina.transaction() builds the tx. | ||
| export const DEFAULT_AU_ESTIMATE = 4; | ||
|
|
||
| /** High-level wrapper around estimateZkappFee for callers that just want a | ||
| * ready-to-use fee value: returns the mempool-derived estimate floored at | ||
| * EMPTY_MEMPOOL_FALLBACK_FEE, which is also returned on any failure. | ||
| * Does not log; callers add their own logging if they want. */ | ||
| export async function resolveZkappFee(graphqlEndpoint: string): Promise<number> { | ||
| try { | ||
| const estimate = await estimateZkappFee(graphqlEndpoint, DEFAULT_AU_ESTIMATE); | ||
| return Math.max(estimate.fee, EMPTY_MEMPOOL_FALLBACK_FEE); | ||
| } catch { | ||
| return EMPTY_MEMPOOL_FALLBACK_FEE; | ||
| } | ||
| } |
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.