Skip to content
Open
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
112 changes: 112 additions & 0 deletions packages/dynamic-instructions/src/display/format-argument-value.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import {
type EnumTypeNode,
isNode,
isScalarEnum,
pascalCase,
resolveNestedTypeNode,
titleCase,
type TypeNode,
} from 'codama';

import { isObjectRecord } from '../shared/util';
import { formatAmountValue, formatDateTimeValue, formatDurationValue, formatStringValue } from './format-value';
import type { DisplayContext } from './types';

/**
* Formats a single decoded value according to the presentation metadata on its type.
*
* Numbers, strings, and enum variants are rendered through their value-display nodes when
* present; `definedTypeLinkNode`s are followed via the context's link resolver so linked
* enums resolve to their variants. Any value without applicable display metadata — and any
* value whose formatter cannot resolve its inputs — falls back to a raw string form.
*/
export async function formatArgumentValue(
type: TypeNode,
value: unknown,
displayContext: DisplayContext,
): Promise<string> {
const resolvedType = resolveDisplayType(type, displayContext);

if (isNode(resolvedType, 'numberTypeNode') && resolvedType.display && isNumeric(value)) {
const formatted = await formatNumber(resolvedType.display, value, displayContext);
if (formatted !== null) return formatted;
}

if (isNode(resolvedType, 'stringTypeNode') && resolvedType.display && typeof value === 'string') {
return formatStringValue(value, resolvedType.display);
}

if (isNode(resolvedType, 'enumTypeNode')) {
return formatEnumValue(resolvedType, value);
}

return rawValue(value);
}

/**
* Resolves nested type wrappers and follows a single `definedTypeLinkNode` to its underlying type.
* Shared by the value formatter and the fallback list so links resolve identically in both.
*/
export function resolveDisplayType(type: TypeNode, displayContext: DisplayContext): TypeNode {
const resolved = resolveNestedTypeNode(type);
if (isNode(resolved, 'definedTypeLinkNode')) {
const definedType = displayContext.resolveDefinedType(resolved);
if (definedType) return resolveNestedTypeNode(definedType.type);
}
return resolved;
}

/** Dispatches a number to the matching number-display formatter. */
async function formatNumber(
display: NonNullable<Extract<TypeNode, { kind: 'numberTypeNode' }>['display']>,
value: bigint | number,
displayContext: DisplayContext,
): Promise<string | null> {
switch (display.kind) {
case 'amountNumberDisplayNode':
return await formatAmountValue(value, display, displayContext);
case 'dateTimeNumberDisplayNode':
return formatDateTimeValue(value, display);
case 'durationNumberDisplayNode':
return formatDurationValue(value, display);
}
}

/**
* Formats an enum value using the matched variant's display label.
* Scalar enums decode to the variant name; data enums decode to `{ __kind: 'PascalVariant', ... }`.
*/
function formatEnumValue(enumType: EnumTypeNode, value: unknown): string {
const decodedName = enumVariantName(value);
if (decodedName === null) return rawValue(value);

// Scalar enums decode to the variant name as-is; data enum `__kind` is the PascalCase form.
const variant = enumType.variants.find(candidate =>
isScalarEnum(enumType) ? candidate.name === decodedName : pascalCase(candidate.name) === decodedName,
);
if (!variant) return rawValue(value);

return variant.display?.label ?? titleCase(variant.name);
}

/** Extracts the variant name from a decoded enum value (scalar name string or data enum `__kind`). */
function enumVariantName(value: unknown): string | null {
if (typeof value === 'string') return value;
if (isObjectRecord(value) && typeof value.__kind === 'string') return value.__kind;
return null;
}

/** Renders a value without any display metadata as a safe, human-readable string. */
function rawValue(value: unknown): string {
if (value === null || value === undefined) return '';
if (typeof value === 'string') return value;
if (typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean') {
return value.toString();
}
if (isObjectRecord(value) && typeof value.__kind === 'string') return titleCase(value.__kind);
return JSON.stringify(value, (_key, v: unknown) => (typeof v === 'bigint' ? v.toString() : v));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just in case, there is safeStringify in shared/util.

However, not sure it will be acceptable in this case to return non-serializable <value_type> instead of throwing and error when JSON.stringify fails.

@mikhd mikhd Jun 26, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think when value: unknown is undefined, then JSON.stringify(undefined) would return undefined instead of desired string.

I guess, this could happen when some key of context data is set to undefined - i.e.
displayContext { data: { decimals: undefined } }

}

function isNumeric(value: unknown): value is bigint | number {
return typeof value === 'bigint' || typeof value === 'number';
}
4 changes: 2 additions & 2 deletions packages/dynamic-instructions/src/display/format-value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
} from 'codama';

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

/**
* Formats an integer as a scaled amount with an optional unit (e.g. `1100000000` → `"1.1 SOL"`).
Expand All @@ -19,7 +19,7 @@ import type { DisplayResolutionContext } from './types';
export async function formatAmountValue(
value: bigint | number,
node: AmountNumberDisplayNode,
context: DisplayResolutionContext,
context: DisplayContext,
): Promise<string | null> {
const decimals = node.decimals ? await resolveInjectedValue(node.decimals, context) : 0;
if (decimals === null || (typeof decimals !== 'bigint' && typeof decimals !== 'number')) {
Expand Down
3 changes: 3 additions & 0 deletions packages/dynamic-instructions/src/display/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export * from './format-argument-value';
export * from './format-value';
export * from './interpolate-intent';
export * from './list-fallback';
export * from './resolve-injected-value';
export * from './types';
54 changes: 54 additions & 0 deletions packages/dynamic-instructions/src/display/interpolate-intent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { getLastNodeFromPath } from 'codama';

import { formatArgumentValue } from './format-argument-value';
import type { DisplayContext } from './types';

/** Matches a `${root.path}` placeholder, capturing the root and the (flat) path after it. */
const PLACEHOLDER_PATTERN = /\$\{\s*(data|accounts)\.([a-zA-Z0-9_]+)\s*\}/g;

/**
* Renders an instruction's `interpolatedIntent` template into a concrete sentence.
*
* Placeholders use the flat form `${data.<argument>}` and `${accounts.<account>}`. Each is
* replaced by the referent's own presentation: arguments through their value-display nodes,
* accounts by their address.
*
* Returns `null` when the instruction has no `interpolatedIntent`, or when any placeholder
* cannot be resolved (an unknown name, or a value whose formatting fails). A `null` result
* signals the caller to fall back to the structured field list.
Comment on lines +16 to +18
*/
export async function interpolateIntent(displayContext: DisplayContext): Promise<string | null> {
const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path);
const template = instruction.display?.interpolatedIntent;
if (template === undefined) return null;

// Resolve each distinct placeholder in parallel, then substitute them back into the template.
const placeholders = [...template.matchAll(PLACEHOLDER_PATTERN)].filter(
([token], index, all) => all.findIndex(([other]) => other === token) === index,
);
const resolved = await Promise.all(
placeholders.map(async ([token, root, name]) => {
return [token, await resolvePlaceholder(root, name, displayContext)] as const;
}),
);

if (resolved.some(([, value]) => value === null)) return null;
const replacements = new Map(resolved);

return template.replace(PLACEHOLDER_PATTERN, match => replacements.get(match) ?? match);
}

/** Resolves a single placeholder to its rendered string, or `null` when it cannot be resolved. */
async function resolvePlaceholder(root: string, name: string, displayContext: DisplayContext): Promise<string | null> {
const { data, path } = displayContext.parsedInstruction;
if (root === 'data') {
const instruction = getLastNodeFromPath(path);
const argument = instruction.arguments.find(arg => arg.name === name);
const decodedData = data as Record<string, unknown>;
if (!argument || !(name in decodedData)) return null;
return await formatArgumentValue(argument.type, decodedData[name], displayContext);
}

// root === 'accounts'
return displayContext.parsedInstruction.accounts.find(account => account.name === name)?.address ?? null;
}
88 changes: 88 additions & 0 deletions packages/dynamic-instructions/src/display/list-fallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import {
type DisplaySkip,
getLastNodeFromPath,
type InstructionArgumentNode,
isNode,
type StructTypeNode,
titleCase,
} from 'codama';

import { isObjectRecord } from '../shared/util';
import { formatArgumentValue, resolveDisplayType } from './format-argument-value';
import type { DisplayContext, DisplayField } from './types';

/**
* Builds the fallback display: a flat, ordered list of labelled fields for an instruction's
* arguments and accounts.
*
* Honours each member's display metadata — `skip` (hidden when `'always'`, or when
* `'whenInjected'` and the value was surfaced through the provide/inject graph), `label`
* overrides, and struct `flatten`/`flattenPrefix`. The instruction's intent/title is not
* included here; the caller composes it around this list.
*/
export async function listFallback(displayContext: DisplayContext): Promise<DisplayField[]> {
const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path);
const argumentFieldGroups = await Promise.all(
instruction.arguments.map(argument => argumentFields(argument, displayContext)),
);
return [...argumentFieldGroups.flat(), ...accountFields(displayContext)];
}

/** Produces the display fields for a single instruction argument (one field, or many when flattened). */
async function argumentFields(
argument: InstructionArgumentNode,
displayContext: DisplayContext,
): Promise<DisplayField[]> {
if (isSkipped(argument.display?.skip, argument.name, displayContext)) return [];

const value = (displayContext.parsedInstruction.data as Record<string, unknown>)[argument.name];
const resolvedType = resolveDisplayType(argument.type, displayContext);
const structType = isNode(resolvedType, 'structTypeNode') ? resolvedType : undefined;

if (argument.display?.flatten && structType && isObjectRecord(value)) {
return await flattenedFields(structType, value, argument.display.flattenPrefix, displayContext);
}

const label = argument.display?.label ?? titleCase(argument.name);
return [{ label, value: await formatArgumentValue(argument.type, value, displayContext) }];
}

/** Lifts a struct's fields into the parent list, prefixing each label and reading nested values. */
async function flattenedFields(
struct: StructTypeNode,
value: Record<string, unknown>,
prefix: string | undefined,
displayContext: DisplayContext,
): Promise<DisplayField[]> {
const visibleFields = struct.fields.filter(field => !isSkipped(field.display?.skip, field.name, displayContext));
return await Promise.all(
visibleFields.map(async field => {
const label = `${prefix ?? ''}${field.display?.label ?? titleCase(field.name)}`;
const formatted = await formatArgumentValue(field.type, value[field.name], displayContext);
return { label, value: formatted };
}),
);
}

/** Produces the display fields for the instruction's accounts. */
function accountFields(displayContext: DisplayContext): DisplayField[] {
const instruction = getLastNodeFromPath(displayContext.parsedInstruction.path);
return instruction.accounts.flatMap(account => {
if (isSkipped(account.display?.skip, account.name, displayContext)) return [];
const address = displayContext.parsedInstruction.accounts.find(a => a.name === account.name)?.address;
if (!address) return [];
const label = account.display?.label ?? titleCase(account.name);
return [{ label, value: address }];
});
}

/**
* Determines whether a member is hidden from the fallback list given its `skip` strategy.
* `'always'` always hides; `'whenInjected'` hides when a provider exposes the member's name
* (its value is surfaced elsewhere through the provide/inject graph); `'never'`/absent shows.
*/
function isSkipped(skip: DisplaySkip | undefined, name: string, displayContext: DisplayContext): boolean {
if (skip === 'always') return true;
if (skip === 'whenInjected') return displayContext.provides.has(name);
return false;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Address } from '@solana/addresses';
import { isNode, type Node } from 'codama';

import type { DisplayResolutionContext } from './types';
import type { DisplayContext } from './types';

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

/**
* Resolves a node to a concrete display value within a {@link DisplayResolutionContext}.
* Resolves a node to a concrete display value within a {@link DisplayContext}.
*
* Handles the value/contextual nodes the display layer relies on:
* - `numberValueNode` / `stringValueNode`: the literal value.
Expand All @@ -27,10 +27,7 @@ export type ResolvedDisplayValue = Address | bigint | number | string | null;
*
* Returns `null` when the value cannot be resolved so callers can fall back safely.
*/
export async function resolveInjectedValue(
node: Node,
context: DisplayResolutionContext,
): Promise<ResolvedDisplayValue> {
export async function resolveInjectedValue(node: Node, context: DisplayContext): Promise<ResolvedDisplayValue> {
if (isNode(node, 'numberValueNode')) {
return node.number;
}
Expand Down Expand Up @@ -72,7 +69,7 @@ export async function resolveInjectedValue(
}

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

Expand Down
37 changes: 28 additions & 9 deletions packages/dynamic-instructions/src/display/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ParsedInstruction } from '@codama/dynamic-parsers';
import type { MaybeEncodedAccount } from '@solana/accounts';
import type { Address } from '@solana/addresses';
import type { ReadonlyUint8Array } from '@solana/codecs';
import type { ProvidedNode } from 'codama';
import type { DefinedTypeLinkNode, DefinedTypeNode, ProvidedNode } from 'codama';

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

/**
* The contextual environment in which display values are resolved.
* Resolves a `definedTypeLinkNode` to its underlying `DefinedTypeNode`, or `undefined` when
* the link cannot be resolved.
*
* Mirrors the provide/inject pattern: an instruction (or other host) exposes named values
* through `provides`, and reusable types pull them by key via `injectedValueNode`. Resolving
* those keys reads from the surrounding `parsedInstruction` (its decoded arguments and account
* addresses) and, for account state, the `fetchAccount` hook plus `resolveAccountData` decoder.
* Lets the display layer follow links (e.g. an argument typed as a linked enum) without
* depending on `NodePath` construction. The orchestrator backs this with a `LinkableDictionary`
* populated from the root; tests can supply a simple map-backed resolver.
*/
export type ResolveDefinedTypeFn = (link: DefinedTypeLinkNode) => DefinedTypeNode | undefined;

/** A single labelled field of the fallback display list (e.g. `{ label: 'Amount', value: '1.5 USDC' }`). */
export type DisplayField = {
/** The human-readable label for the field. */
readonly label: string;
/** The formatted value for the field. */
readonly value: string;
};

/**
* Everything needed to present one concrete instruction.
*
* A single context threaded through the whole display layer: the parsed instruction (its decoded
* arguments, node path, and account metas), the provide/inject graph, account fetching + decoding,
* and link resolution. Lower-level helpers read only the parts they need.
*
* The orchestrator assembles this from a parsed instruction; it is kept explicit here so the
* resolution and formatting layers can be exercised in isolation.
* The orchestrator assembles this from a parsed instruction; it is kept explicit so every
* layer can be exercised in isolation.
*/
export type DisplayResolutionContext = {
export type DisplayContext = {
/** Fetches the on-chain account at an address; absent when running fully offline. */
readonly fetchAccount?: FetchAccountFn;
/** The parsed instruction being presented: its decoded arguments, node path, and account metas. */
Expand All @@ -49,4 +66,6 @@ export type DisplayResolutionContext = {
readonly provides: ReadonlyMap<string, ProvidedNode>;
/** Decodes a named account's raw bytes against its `accountLink` layout. */
readonly resolveAccountData: ResolveAccountDataFn;
/** Resolves any `definedTypeLinkNode` reached while following an argument's type. */
readonly resolveDefinedType: ResolveDefinedTypeFn;
};
Loading
Loading