Skip to content

Commit 10776b0

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 7bb6f3f commit 10776b0

13 files changed

Lines changed: 749 additions & 38 deletions
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
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 (typeof value === 'string') return value;
102+
if (typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean') {
103+
return value.toString();
104+
}
105+
if (isObjectRecord(value) && typeof value.__kind === 'string') return titleCase(value.__kind);
106+
return JSON.stringify(value, (_key, v: unknown) => (typeof v === 'bigint' ? v.toString() : v));
107+
}
108+
109+
function isNumeric(value: unknown): value is bigint | number {
110+
return typeof value === 'bigint' || typeof value === 'number';
111+
}

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

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

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

55
import { isObjectRecord } from '../shared/util';
6-
import type { DisplayResolutionContext } from './types';
6+
import type { DisplayContext } from './types';
77

88
/**
99
* A value resolved from the provide/inject graph for display purposes.
@@ -15,7 +15,7 @@ import type { DisplayResolutionContext } from './types';
1515
export type ResolvedDisplayValue = Address | bigint | number | string | null;
1616

1717
/**
18-
* Resolves a node to a concrete display value within a {@link DisplayResolutionContext}.
18+
* Resolves a node to a concrete display value within a {@link DisplayContext}.
1919
*
2020
* Handles the value/contextual nodes the display layer relies on:
2121
* - `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
}
Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Account } from '@solana/accounts';
22
import type { Address } from '@solana/addresses';
3-
import type { ProvidedNode } from 'codama';
3+
import type { DefinedTypeLinkNode, DefinedTypeNode, InstructionNode, ProvidedNode } from 'codama';
44

55
/**
66
* Fetches and decodes the account at a given address, returning Kit's decoded `Account`
@@ -17,21 +17,46 @@ import type { ProvidedNode } from 'codama';
1717
export type FetchAccountDataFn = (address: Address) => Promise<Account<object> | null>;
1818

1919
/**
20-
* The contextual environment in which display values are resolved.
20+
* Resolves a `definedTypeLinkNode` to its underlying `DefinedTypeNode`, or `undefined` when
21+
* the link cannot be resolved.
2122
*
22-
* Mirrors the provide/inject pattern: an instruction (or other host) exposes named values
23-
* through `provides`, and reusable types pull them by key via `injectedValueNode`. Resolving
24-
* those keys may also require reading account state, so the context carries the addresses of
25-
* the surrounding instruction's accounts plus the `fetchAccountData` hook.
23+
* Lets the display layer follow links (e.g. an argument typed as a linked enum) without
24+
* depending on `NodePath` construction. The orchestrator backs this with a `LinkableDictionary`
25+
* populated from the root; tests can supply a simple map-backed resolver.
26+
*/
27+
export type ResolveDefinedTypeFn = (link: DefinedTypeLinkNode) => DefinedTypeNode | undefined;
28+
29+
/** A single labelled field of the fallback display list (e.g. `{ label: 'Amount', value: '1.5 USDC' }`). */
30+
export type DisplayField = {
31+
/** The human-readable label for the field. */
32+
readonly label: string;
33+
/** The formatted value for the field. */
34+
readonly value: string;
35+
};
36+
37+
/**
38+
* Everything needed to present one concrete instruction.
39+
*
40+
* A single context threaded through the whole display layer: the static `instruction`
41+
* definition, its decoded argument `data` (a flat record keyed by argument name), the
42+
* concrete account addresses (keyed by account name; the instruction supplies their order),
43+
* the provide/inject graph, account fetching, and link resolution. Lower-level helpers read
44+
* only the parts they need.
2645
*
27-
* The orchestrator assembles this from a parsed instruction; it is kept explicit here so the
28-
* resolution and formatting layers can be exercised in isolation.
46+
* The orchestrator assembles this from a parsed instruction; it is kept explicit so every
47+
* layer can be exercised in isolation.
2948
*/
30-
export type DisplayResolutionContext = {
31-
/** Addresses of the surrounding instruction's accounts, keyed by account name. */
49+
export type DisplayContext = {
50+
/** Concrete account addresses, keyed by account name. */
3251
readonly accountAddresses: ReadonlyMap<string, Address>;
52+
/** The decoded argument values, keyed by argument name. */
53+
readonly data: Record<string, unknown>;
3354
/** Fetches and decodes account data; absent when running fully offline. */
3455
readonly fetchAccountData?: FetchAccountDataFn;
56+
/** The static instruction definition being presented. */
57+
readonly instruction: InstructionNode;
3558
/** Values exposed by the surrounding host, keyed by the name they are provided under. */
3659
readonly provides: ReadonlyMap<string, ProvidedNode>;
60+
/** Resolves any `definedTypeLinkNode` reached while following an argument's type. */
61+
readonly resolveDefinedType: ResolveDefinedTypeFn;
3762
};

0 commit comments

Comments
 (0)