Skip to content

Commit 0399959

Browse files
committed
Add interpolated-intent and fallback-list render modes
This PR adds the two clear-signing render modes on top of the value layer (sRFC 39). interpolateIntent renders an instruction's interpolatedIntent template by substituting flat ${data.<argument>} and ${accounts.<account>} placeholders, returning null when the template is absent or a referenced name cannot be resolved so the caller can fall back. listFallback builds the structured fallback list of labelled fields for the instruction's arguments and accounts, honouring skip strategies (including whenInjected), label overrides, and struct flattening with prefixes. Both consume a new formatArgumentValue bridge that maps a decoded value to its type's display node — dispatching to the amount, date-time, duration, and string formatters, resolving linked enums to their variant labels, and degrading to a raw form when no display metadata applies. Defined-type links are followed through a single shared resolveDisplayType helper, and the whole display layer threads one flat DisplayContext (instruction, decoded data, account addresses, provide/inject graph, account fetching, and link resolution) so every piece stays unit-testable ahead of the orchestration PR. These remain internal building blocks, not yet exported from the package. No changeset is included, consistent with the rest of the 1.7.0 stack.
1 parent 7a799ac commit 0399959

13 files changed

Lines changed: 792 additions & 44 deletions
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import {
2+
type EnumTypeNode,
3+
isNode,
4+
isScalarEnum,
5+
pascalCase,
6+
resolveNestedTypeNode,
7+
titleCase,
8+
type TypeNode,
9+
} from 'codama';
10+
11+
import { isObjectRecord } from '../shared/util';
12+
import { formatAmountValue, formatDateTimeValue, formatDurationValue, formatStringValue } from './format-value';
13+
import type { DisplayContext } from './types';
14+
15+
/**
16+
* Formats a single decoded value according to the presentation metadata on its type.
17+
*
18+
* Numbers, strings, and enum variants are rendered through their value-display nodes when
19+
* present; `definedTypeLinkNode`s are followed via the context's link resolver so linked
20+
* enums resolve to their variants. Any value without applicable display metadata — and any
21+
* value whose formatter cannot resolve its inputs — falls back to a raw string form.
22+
*/
23+
export async function formatArgumentValue(
24+
type: TypeNode,
25+
value: unknown,
26+
displayContext: DisplayContext,
27+
): Promise<string> {
28+
const resolvedType = resolveDisplayType(type, displayContext);
29+
30+
if (isNode(resolvedType, 'numberTypeNode') && resolvedType.display && isNumeric(value)) {
31+
const formatted = await formatNumber(resolvedType.display, value, displayContext);
32+
if (formatted !== null) return formatted;
33+
}
34+
35+
if (isNode(resolvedType, 'stringTypeNode') && resolvedType.display && typeof value === 'string') {
36+
return formatStringValue(value, resolvedType.display);
37+
}
38+
39+
if (isNode(resolvedType, 'enumTypeNode')) {
40+
return formatEnumValue(resolvedType, value);
41+
}
42+
43+
return rawValue(value);
44+
}
45+
46+
/**
47+
* Resolves nested type wrappers and follows a single `definedTypeLinkNode` to its underlying type.
48+
* Shared by the value formatter and the fallback list so links resolve identically in both.
49+
*/
50+
export function resolveDisplayType(type: TypeNode, displayContext: DisplayContext): TypeNode {
51+
const resolved = resolveNestedTypeNode(type);
52+
if (isNode(resolved, 'definedTypeLinkNode')) {
53+
const definedType = displayContext.resolveDefinedType(resolved);
54+
if (definedType) return resolveNestedTypeNode(definedType.type);
55+
}
56+
return resolved;
57+
}
58+
59+
/** Dispatches a number to the matching number-display formatter. */
60+
async function formatNumber(
61+
display: NonNullable<Extract<TypeNode, { kind: 'numberTypeNode' }>['display']>,
62+
value: bigint | number,
63+
displayContext: DisplayContext,
64+
): Promise<string | null> {
65+
switch (display.kind) {
66+
case 'amountNumberDisplayNode':
67+
return await formatAmountValue(value, display, displayContext);
68+
case 'dateTimeNumberDisplayNode':
69+
return formatDateTimeValue(value, display);
70+
case 'durationNumberDisplayNode':
71+
return formatDurationValue(value, display);
72+
}
73+
}
74+
75+
/**
76+
* Formats an enum value using the matched variant's display label.
77+
* Scalar enums decode to the variant name; data enums decode to `{ __kind: 'PascalVariant', ... }`.
78+
*/
79+
function formatEnumValue(enumType: EnumTypeNode, value: unknown): string {
80+
const decodedName = enumVariantName(value);
81+
if (decodedName === null) return rawValue(value);
82+
83+
// Scalar enums decode to the variant name as-is; data enum `__kind` is the PascalCase form.
84+
const variant = enumType.variants.find(candidate =>
85+
isScalarEnum(enumType) ? candidate.name === decodedName : pascalCase(candidate.name) === decodedName,
86+
);
87+
if (!variant) return rawValue(value);
88+
89+
return variant.display?.label ?? titleCase(variant.name);
90+
}
91+
92+
/** Extracts the variant name from a decoded enum value (scalar name string or data enum `__kind`). */
93+
function enumVariantName(value: unknown): string | null {
94+
if (typeof value === 'string') return value;
95+
if (isObjectRecord(value) && typeof value.__kind === 'string') return value.__kind;
96+
return null;
97+
}
98+
99+
/** Renders a value without any display metadata as a safe, human-readable string. */
100+
function rawValue(value: unknown): string {
101+
if (value === null || value === undefined) return '';
102+
if (typeof value === 'string') return value;
103+
if (typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean') {
104+
return value.toString();
105+
}
106+
if (isObjectRecord(value) && typeof value.__kind === 'string') return titleCase(value.__kind);
107+
return JSON.stringify(value, (_key, v: unknown) => (typeof v === 'bigint' ? v.toString() : v));
108+
}
109+
110+
function isNumeric(value: unknown): value is bigint | number {
111+
return typeof value === 'bigint' || typeof value === 'number';
112+
}

packages/dynamic-instructions/src/display/format-value.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type {
66
} from 'codama';
77

88
import { resolveInjectedValue } from './resolve-injected-value';
9-
import type { DisplayResolutionContext } from './types';
9+
import type { DisplayContext } from './types';
1010

1111
/**
1212
* Formats an integer as a scaled amount with an optional unit (e.g. `1100000000` → `"1.1 SOL"`).
@@ -19,7 +19,7 @@ import type { DisplayResolutionContext } from './types';
1919
export async function formatAmountValue(
2020
value: bigint | number,
2121
node: AmountNumberDisplayNode,
22-
context: DisplayResolutionContext,
22+
context: DisplayContext,
2323
): Promise<string | null> {
2424
const decimals = node.decimals ? await resolveInjectedValue(node.decimals, context) : 0;
2525
if (decimals === null || (typeof decimals !== 'bigint' && typeof decimals !== 'number')) {
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
export * from './format-argument-value';
12
export * from './format-value';
3+
export * from './interpolate-intent';
4+
export * from './list-fallback';
25
export * from './resolve-injected-value';
36
export * from './types';
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { getLastNodeFromPath } from 'codama';
2+
3+
import { formatArgumentValue } from './format-argument-value';
4+
import type { DisplayContext } from './types';
5+
6+
/** Matches a `${root.path}` placeholder, capturing the root and the (flat) path after it. */
7+
const PLACEHOLDER_PATTERN = /\$\{\s*(data|accounts)\.([a-zA-Z0-9_]+)\s*\}/g;
8+
9+
/**
10+
* Renders an instruction's `interpolatedIntent` template into a concrete sentence.
11+
*
12+
* Placeholders use the flat form `${data.<argument>}` and `${accounts.<account>}`. Each is
13+
* replaced by the referent's own presentation: arguments through their value-display nodes,
14+
* accounts by their address.
15+
*
16+
* Returns `null` when the instruction has no `interpolatedIntent`, or when any placeholder
17+
* cannot be resolved (an unknown name, or a value whose formatting fails). A `null` result
18+
* signals the caller to fall back to the structured field list.
19+
*/
20+
export async function interpolateIntent(displayContext: DisplayContext): Promise<string | null> {
21+
const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path);
22+
const template = instruction.display?.interpolatedIntent;
23+
if (template === undefined) return null;
24+
25+
// Resolve each distinct placeholder in parallel, then substitute them back into the template.
26+
const placeholders = [...template.matchAll(PLACEHOLDER_PATTERN)].filter(
27+
([token], index, all) => all.findIndex(([other]) => other === token) === index,
28+
);
29+
const resolved = await Promise.all(
30+
placeholders.map(async ([token, root, name]) => {
31+
return [token, await resolvePlaceholder(root, name, displayContext)] as const;
32+
}),
33+
);
34+
35+
if (resolved.some(([, value]) => value === null)) return null;
36+
const replacements = new Map(resolved);
37+
38+
return template.replace(PLACEHOLDER_PATTERN, match => replacements.get(match) ?? match);
39+
}
40+
41+
/** Resolves a single placeholder to its rendered string, or `null` when it cannot be resolved. */
42+
async function resolvePlaceholder(root: string, name: string, displayContext: DisplayContext): Promise<string | null> {
43+
const { data, path } = displayContext.parsedInstruction;
44+
if (root === 'data') {
45+
const instruction = getLastNodeFromPath(path);
46+
const argument = instruction.arguments.find(arg => arg.name === name);
47+
const decodedData = data as Record<string, unknown>;
48+
if (!argument || !(name in decodedData)) return null;
49+
return await formatArgumentValue(argument.type, decodedData[name], displayContext);
50+
}
51+
52+
// root === 'accounts'
53+
return displayContext.parsedInstruction.accounts.find(account => account.name === name)?.address ?? null;
54+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import {
2+
type DisplaySkip,
3+
getLastNodeFromPath,
4+
type InstructionArgumentNode,
5+
isNode,
6+
type StructTypeNode,
7+
titleCase,
8+
} from 'codama';
9+
10+
import { isObjectRecord } from '../shared/util';
11+
import { formatArgumentValue, resolveDisplayType } from './format-argument-value';
12+
import type { DisplayContext, DisplayField } from './types';
13+
14+
/**
15+
* Builds the fallback display: a flat, ordered list of labelled fields for an instruction's
16+
* arguments and accounts.
17+
*
18+
* Honours each member's display metadata — `skip` (hidden when `'always'`, or when
19+
* `'whenInjected'` and the value was surfaced through the provide/inject graph), `label`
20+
* overrides, and struct `flatten`/`flattenPrefix`. The instruction's intent/title is not
21+
* included here; the caller composes it around this list.
22+
*/
23+
export async function listFallback(displayContext: DisplayContext): Promise<DisplayField[]> {
24+
const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path);
25+
const argumentFieldGroups = await Promise.all(
26+
instruction.arguments.map(argument => argumentFields(argument, displayContext)),
27+
);
28+
return [...argumentFieldGroups.flat(), ...accountFields(displayContext)];
29+
}
30+
31+
/** Produces the display fields for a single instruction argument (one field, or many when flattened). */
32+
async function argumentFields(
33+
argument: InstructionArgumentNode,
34+
displayContext: DisplayContext,
35+
): Promise<DisplayField[]> {
36+
if (isSkipped(argument.display?.skip, argument.name, displayContext)) return [];
37+
38+
const value = (displayContext.parsedInstruction.data as Record<string, unknown>)[argument.name];
39+
const resolvedType = resolveDisplayType(argument.type, displayContext);
40+
const structType = isNode(resolvedType, 'structTypeNode') ? resolvedType : undefined;
41+
42+
if (argument.display?.flatten && structType && isObjectRecord(value)) {
43+
return await flattenedFields(structType, value, argument.display.flattenPrefix, displayContext);
44+
}
45+
46+
const label = argument.display?.label ?? titleCase(argument.name);
47+
return [{ label, value: await formatArgumentValue(argument.type, value, displayContext) }];
48+
}
49+
50+
/** Lifts a struct's fields into the parent list, prefixing each label and reading nested values. */
51+
async function flattenedFields(
52+
struct: StructTypeNode,
53+
value: Record<string, unknown>,
54+
prefix: string | undefined,
55+
displayContext: DisplayContext,
56+
): Promise<DisplayField[]> {
57+
const visibleFields = struct.fields.filter(field => !isSkipped(field.display?.skip, field.name, displayContext));
58+
return await Promise.all(
59+
visibleFields.map(async field => {
60+
const label = `${prefix ?? ''}${field.display?.label ?? titleCase(field.name)}`;
61+
const formatted = await formatArgumentValue(field.type, value[field.name], displayContext);
62+
return { label, value: formatted };
63+
}),
64+
);
65+
}
66+
67+
/** Produces the display fields for the instruction's accounts. */
68+
function accountFields(displayContext: DisplayContext): DisplayField[] {
69+
const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path);
70+
return instruction.accounts.flatMap(account => {
71+
if (isSkipped(account.display?.skip, account.name, displayContext)) return [];
72+
const address = displayContext.parsedInstruction.accounts.find(a => a.name === account.name)?.address;
73+
if (!address) return [];
74+
const label = account.display?.label ?? titleCase(account.name);
75+
return [{ label, value: address }];
76+
});
77+
}
78+
79+
/**
80+
* Determines whether a member is hidden from the fallback list given its `skip` strategy.
81+
* `'always'` always hides; `'whenInjected'` hides when a provider exposes the member's name
82+
* (its value is surfaced elsewhere through the provide/inject graph); `'never'`/absent shows.
83+
*/
84+
function isSkipped(skip: DisplaySkip | undefined, name: string, displayContext: DisplayContext): boolean {
85+
if (skip === 'always') return true;
86+
if (skip === 'whenInjected') return displayContext.provides.has(name);
87+
return false;
88+
}

packages/dynamic-instructions/src/display/resolve-injected-value.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { Address } from '@solana/addresses';
22
import { isNode, type Node } from 'codama';
33

4-
import type { DisplayResolutionContext } from './types';
4+
import type { DisplayContext } from './types';
55

66
/**
77
* A value resolved from the provide/inject graph for display purposes.
@@ -13,7 +13,7 @@ import type { DisplayResolutionContext } from './types';
1313
export type ResolvedDisplayValue = Address | bigint | number | string | null;
1414

1515
/**
16-
* Resolves a node to a concrete display value within a {@link DisplayResolutionContext}.
16+
* Resolves a node to a concrete display value within a {@link DisplayContext}.
1717
*
1818
* Handles the value/contextual nodes the display layer relies on:
1919
* - `numberValueNode` / `stringValueNode`: the literal value.
@@ -27,10 +27,7 @@ export type ResolvedDisplayValue = Address | bigint | number | string | null;
2727
*
2828
* Returns `null` when the value cannot be resolved so callers can fall back safely.
2929
*/
30-
export async function resolveInjectedValue(
31-
node: Node,
32-
context: DisplayResolutionContext,
33-
): Promise<ResolvedDisplayValue> {
30+
export async function resolveInjectedValue(node: Node, context: DisplayContext): Promise<ResolvedDisplayValue> {
3431
if (isNode(node, 'numberValueNode')) {
3532
return node.number;
3633
}
@@ -72,7 +69,7 @@ export async function resolveInjectedValue(
7269
}
7370

7471
/** Finds the concrete address of a named account of the surrounding instruction, or `null`. */
75-
function findAccountAddress(context: DisplayResolutionContext, name: string): Address | null {
72+
function findAccountAddress(context: DisplayContext, name: string): Address | null {
7673
return context.parsedInstruction.accounts.find(account => account.name === name)?.address ?? null;
7774
}
7875

packages/dynamic-instructions/src/display/types.ts

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { ParsedInstruction } from '@codama/dynamic-parsers';
22
import type { MaybeEncodedAccount } from '@solana/accounts';
33
import type { Address } from '@solana/addresses';
44
import type { ReadonlyUint8Array } from '@solana/codecs';
5-
import type { ProvidedNode } from 'codama';
5+
import type { DefinedTypeLinkNode, DefinedTypeNode, ProvidedNode } from 'codama';
66

77
/**
88
* Fetches the on-chain account at a given address, returning Kit's `MaybeEncodedAccount` — an
@@ -30,17 +30,34 @@ export type FetchAccountFn = (address: Address) => Promise<MaybeEncodedAccount>;
3030
export type ResolveAccountDataFn = (accountName: string, bytes: ReadonlyUint8Array) => Record<string, unknown> | null;
3131

3232
/**
33-
* The contextual environment in which display values are resolved.
33+
* Resolves a `definedTypeLinkNode` to its underlying `DefinedTypeNode`, or `undefined` when
34+
* the link cannot be resolved.
3435
*
35-
* Mirrors the provide/inject pattern: an instruction (or other host) exposes named values
36-
* through `provides`, and reusable types pull them by key via `injectedValueNode`. Resolving
37-
* those keys reads from the surrounding `parsedInstruction` (its decoded arguments and account
38-
* addresses) and, for account state, the `fetchAccount` hook plus `resolveAccountData` decoder.
36+
* Lets the display layer follow links (e.g. an argument typed as a linked enum) without
37+
* depending on `NodePath` construction. The orchestrator backs this with a `LinkableDictionary`
38+
* populated from the root; tests can supply a simple map-backed resolver.
39+
*/
40+
export type ResolveDefinedTypeFn = (link: DefinedTypeLinkNode) => DefinedTypeNode | undefined;
41+
42+
/** A single labelled field of the fallback display list (e.g. `{ label: 'Amount', value: '1.5 USDC' }`). */
43+
export type DisplayField = {
44+
/** The human-readable label for the field. */
45+
readonly label: string;
46+
/** The formatted value for the field. */
47+
readonly value: string;
48+
};
49+
50+
/**
51+
* Everything needed to present one concrete instruction.
52+
*
53+
* A single context threaded through the whole display layer: the parsed instruction (its decoded
54+
* arguments, node path, and account metas), the provide/inject graph, account fetching + decoding,
55+
* and link resolution. Lower-level helpers read only the parts they need.
3956
*
40-
* The orchestrator assembles this from a parsed instruction; it is kept explicit here so the
41-
* resolution and formatting layers can be exercised in isolation.
57+
* The orchestrator assembles this from a parsed instruction; it is kept explicit so every
58+
* layer can be exercised in isolation.
4259
*/
43-
export type DisplayResolutionContext = {
60+
export type DisplayContext = {
4461
/** Fetches the on-chain account at an address; absent when running fully offline. */
4562
readonly fetchAccount?: FetchAccountFn;
4663
/** The parsed instruction being presented: its decoded arguments, node path, and account metas. */
@@ -49,4 +66,6 @@ export type DisplayResolutionContext = {
4966
readonly provides: ReadonlyMap<string, ProvidedNode>;
5067
/** Decodes a named account's raw bytes against its `accountLink` layout. */
5168
readonly resolveAccountData: ResolveAccountDataFn;
69+
/** Resolves any `definedTypeLinkNode` reached while following an argument's type. */
70+
readonly resolveDefinedType: ResolveDefinedTypeFn;
5271
};

0 commit comments

Comments
 (0)