Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,15 @@ import profile from './fee-profile.json';
const kit = createTransactionKit({
chain,
provider: window.ethereum,
suggestions: profile, // { deploy?, methods: { place_bet: {...} } }
suggestions: profile, // { chainId, deploy?, methods: { place_bet: {...} } }
});
```

Merge order per estimate: preset (appeal posture) < suggestion (measured allocations)
< caller overrides. `PolicyQuote.source` reports `'developer'` or `'network-default'`,
and the receipt shows the provenance. Profile values are decimal strings, so the JSON
artifact passes through unchanged; methods without an entry fall back to network
defaults.
defaults. A profile must declare the exact numeric `chainId` where it was measured.
Missing, malformed, or mismatched chain provenance falls back to network defaults, as
does a profile whose execution budget is below the live network floor. `network` is an
optional human-readable label and is never used as the security boundary.
74 changes: 66 additions & 8 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ export type SuggestedFees = {

export type FeeSuggestions = {
version?: number;
/** Chain where these allocations were measured. Profiles without an exact
* chain-id match are ignored so measurements cannot cross networks. */
chainId?: bigint | number | string;
/** Human-readable provenance only. Selection is based on `chainId`. */
network?: string;
measuredAt?: string;
deploy?: SuggestedFees;
Expand All @@ -75,7 +79,8 @@ export type PolicyQuote = {
/** Comparison between the quoted fee config hash and the chain's current
* fee policy projected onto the quote. A mismatch means the quote was
* built against stale fee prices and adapters should block signing unless
* explicitly configured otherwise. */
* explicitly configured otherwise. This verifies live price caps, not the
* developer profile's measured allocations. */
verification: PolicyVerification;
breakdown: {
timeUnitFees: bigint;
Expand Down Expand Up @@ -277,13 +282,43 @@ const toPolicyQuote = (
const resolveSuggestion = (
suggestions: FeeSuggestions | undefined,
tx: SubmitInput | undefined,
chainId: number,
): SuggestedFees | undefined => {
if (!suggestions || !tx) return undefined;
if (!suggestions || !tx || !matchesChainId(suggestions.chainId, chainId)) {
return undefined;
}
return tx.kind === 'deploy'
? suggestions.deploy
: suggestions.methods?.[tx.method];
};

const matchesChainId = (
profileChainId: FeeSuggestions['chainId'],
activeChainId: number,
): boolean => {
if (profileChainId === undefined || !Number.isSafeInteger(activeChainId)) {
return false;
}

try {
const normalized = BigInt(profileChainId);
return normalized >= 0n && normalized === BigInt(activeChainId);
} catch {
return false;
}
};

const profileIsBelowExecutionFloor = (
suggestion: SuggestedFees | undefined,
input: PolicyInput,
estimate: TransactionFeeEstimate,
): boolean =>
suggestion?.executionBudgetPerRound !== undefined &&
input.overrides?.executionBudgetPerRound === undefined &&
estimate.policy.enabled &&
estimate.distribution.executionBudgetPerRound <
estimate.policy.executionBudgetFloor;

// Merge order: preset (appeal posture) < developer suggestion (measured
// allocations) < caller overrides. Prices/caps stay unset so the SDK fills
// them from live reads with headroom — never from the profile.
Expand Down Expand Up @@ -573,8 +608,9 @@ export function createTransactionKit(opts: {
account?: `0x${string}`;
allowUnverified?: boolean;
/** Developer fee profile (allocations measured by the contract's test
* suite). When a suggestion matches the transaction, it seeds the
* estimate; the panel never simulates the call live. */
* suite). A profile must declare a `chainId` matching `chain.id`; otherwise
* it is ignored. When a safe suggestion matches the transaction, it seeds
* the estimate; the panel never simulates the call live. */
suggestions?: FeeSuggestions;
}): TransactionKit {
const captured = captureProviderTxHash(opts.provider);
Expand All @@ -591,10 +627,15 @@ export function createTransactionKit(opts: {
tx?: SubmitInput,
): Promise<PolicyQuote> => {
const userValue = input.userValue ?? 0n;
const suggestion = resolveSuggestion(opts.suggestions, tx);
const feeOptions = buildFeeOptions(input, suggestion);
const [sdkEstimate, pendingAhead, currentPolicy] = await Promise.all([
client.estimateTransactionFees(feeOptions),
const candidateSuggestion = resolveSuggestion(
opts.suggestions,
tx,
opts.chain.id,
);
const [candidateEstimate, pendingAhead, currentPolicy] = await Promise.all([
client.estimateTransactionFees(
buildFeeOptions(input, candidateSuggestion),
),
// a deploy targets a fresh address, so its queue is necessarily empty
tx?.kind === 'write'
? readPendingAhead(opts.provider, opts.chain, tx.address, queueCache)
Expand All @@ -603,6 +644,23 @@ export function createTransactionKit(opts: {
Promise.resolve(undefined),
]);

// The SDK estimate already carries the live execution-budget floor. If a
// chain-matched developer profile falls below it, discard the whole
// profile and let the SDK rebuild an internally coherent default quote.
// Re-estimating is limited to this unsafe fallback path; we do not patch
// feeValue locally or invent a fee formula in the kit.
const suggestion = profileIsBelowExecutionFloor(
candidateSuggestion,
input,
candidateEstimate,
)
? undefined
: candidateSuggestion;
const sdkEstimate =
candidateSuggestion && !suggestion
? await client.estimateTransactionFees(buildFeeOptions(input))
: candidateEstimate;

const quote = toPolicyQuote(
sdkEstimate,
userValue,
Expand Down
156 changes: 156 additions & 0 deletions packages/core/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ describe('transaction kit core', () => {
provider: provider(),
account: `0x${'1'.repeat(40)}`,
suggestions: {
chainId: 61999,
methods: {
update_storage: {
leaderTimeunitsAllocation: '1100',
Expand Down Expand Up @@ -219,6 +220,161 @@ describe('transaction kit core', () => {
expect(quote.source).toBe('developer');
});

it('ignores an unscoped developer profile', async () => {
const client = {
estimateTransactionFees: vi.fn(async () => ({
distribution: distribution(),
feeValue: 500n,
policy: feePolicy(),
})),
};
mocks.createClient.mockReturnValue(client);

const { createTransactionKit } = await import('../src/index');
const kit = createTransactionKit({
chain,
provider: provider(),
suggestions: {
network: 'localnet',
methods: {
update_storage: { executionBudgetPerRound: '1' },
},
},
});

const quote = await kit.estimate(
{ preset: 'standard' },
{ kind: 'write', address: `0x${'2'.repeat(40)}`, method: 'update_storage' },
);

expect(client.estimateTransactionFees).toHaveBeenCalledWith({
appealRounds: 3n,
rotations: [0n, 0n, 0n, 0n],
});
expect(quote.source).toBe('network-default');
});

it('ignores a developer profile measured on another chain', async () => {
const client = {
estimateTransactionFees: vi.fn(async () => ({
distribution: distribution(),
feeValue: 500n,
policy: feePolicy(),
})),
};
mocks.createClient.mockReturnValue(client);

const { createTransactionKit } = await import('../src/index');
const kit = createTransactionKit({
chain,
provider: provider(),
suggestions: {
chainId: 61997,
network: 'studio-dev',
methods: {
update_storage: { executionBudgetPerRound: '1' },
},
},
});

const quote = await kit.estimate(
{ preset: 'standard' },
{ kind: 'write', address: `0x${'2'.repeat(40)}`, method: 'update_storage' },
);

expect(client.estimateTransactionFees).toHaveBeenCalledWith({
appealRounds: 3n,
rotations: [0n, 0n, 0n, 0n],
});
expect(quote.source).toBe('network-default');
});

it('ignores malformed chain provenance without failing the estimate', async () => {
const client = {
estimateTransactionFees: vi.fn(async () => ({
distribution: distribution(),
feeValue: 500n,
policy: feePolicy(),
})),
};
mocks.createClient.mockReturnValue(client);

const { createTransactionKit } = await import('../src/index');
const kit = createTransactionKit({
chain,
provider: provider(),
suggestions: {
chainId: 'localnet',
methods: {
update_storage: { executionBudgetPerRound: '1' },
},
},
});

const quote = await kit.estimate(
{ preset: 'standard' },
{ kind: 'write', address: `0x${'2'.repeat(40)}`, method: 'update_storage' },
);

expect(client.estimateTransactionFees).toHaveBeenCalledWith({
appealRounds: 3n,
rotations: [0n, 0n, 0n, 0n],
});
expect(quote.source).toBe('network-default');
});

it('falls back to network defaults when a matched profile is below the live execution floor', async () => {
const client = {
estimateTransactionFees: vi
.fn()
.mockResolvedValueOnce({
distribution: distribution({ executionBudgetPerRound: 100n }),
feeValue: 500n,
policy: feePolicy({ executionBudgetFloor: 700n }),
})
.mockResolvedValueOnce({
distribution: distribution({ executionBudgetPerRound: 700n }),
feeValue: 2_300n,
policy: feePolicy({ executionBudgetFloor: 700n }),
}),
};
mocks.createClient.mockReturnValue(client);

const { createTransactionKit } = await import('../src/index');
const kit = createTransactionKit({
chain,
provider: provider(),
suggestions: {
chainId: '61999',
methods: {
update_storage: {
leaderTimeunitsAllocation: '1100',
executionBudgetPerRound: '100',
},
},
},
});

const quote = await kit.estimate(
{ preset: 'standard' },
{ kind: 'write', address: `0x${'2'.repeat(40)}`, method: 'update_storage' },
);

expect(client.estimateTransactionFees).toHaveBeenNthCalledWith(1, {
appealRounds: 3n,
rotations: [0n, 0n, 0n, 0n],
leaderTimeunitsAllocation: '1100',
executionBudgetPerRound: '100',
});
expect(client.estimateTransactionFees).toHaveBeenNthCalledWith(2, {
appealRounds: 3n,
rotations: [0n, 0n, 0n, 0n],
});
expect(quote.source).toBe('network-default');
expect(quote.distribution.executionBudgetPerRound).toBe(700n);
expect(quote.feeValue).toBe(2_300n);
});

it('marks gasless networks and submits without fee params', async () => {
const client = {
estimateTransactionFees: vi.fn(async () => ({
Expand Down
Loading