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
11 changes: 11 additions & 0 deletions .changeset/grumpy-pears-attend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@codama/renderers-js': major
---

Fix instruction builders whose data fields are named like an account and filled in by the builder.

**BREAKING CHANGES**

**Data fields defaulting to a PDA hold its address.** Builders filling in a data field from a PDA assign the address of the derived PDA, e.g. `args.vault = (await findVaultPda(...))[0]`, rather than the `[address, bump]` pair returned by the find function, which did not match the type of the field.

Such fields are only renamed in the input of the builder that requires them, e.g. `vaultArg` in the synchronous builder, so asynchronous builders filling them in no longer read an input property that does not exist, and they leave the account of the same name out of the arguments they fill in.
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ Page builders mostly compose subfragments rather than embedding all logic inline
- `packageJson.ts`: derive dependency requirements from actual imports and sync/create package.json.
- `customData.ts`: support extracting or importing account/instruction data types from elsewhere.
- `linkOverrides.ts`: remap generated/internal import targets.
- `async.ts`: decide whether instructions need async variants, which arguments their builders take as input (`isInputArgument`, `getInstructionFunctionInputFlags`) and compute resolver dependencies.
- `async.ts`: decide whether instructions need async variants, which arguments their builders take as input (`isInputArgument`, `getInstructionFunctionInputFlags`), how arguments named like an account are renamed in that input (`getRenamedArgsMap`) and compute resolver dependencies.
- `formatCode.ts`: Prettier integration.
- `typeManifest.ts`: helpers for building and merging type manifests, and the node kinds the type manifest visitor accepts.
- `generatedModules.ts`: decide the module a generated node is imported from, i.e. its folder barrel, or its own file for nodes listed in `internalNodes`, which barrels leave out. Use it wherever a generated node is imported instead of hardcoding a `generated*` module.
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ Page builders mostly compose subfragments rather than embedding all logic inline
- `packageJson.ts`: derive dependency requirements from actual imports and sync/create package.json.
- `customData.ts`: support extracting or importing account/instruction data types from elsewhere.
- `linkOverrides.ts`: remap generated/internal import targets.
- `async.ts`: decide whether instructions need async variants, which arguments their builders take as input (`isInputArgument`, `getInstructionFunctionInputFlags`) and compute resolver dependencies.
- `async.ts`: decide whether instructions need async variants, which arguments their builders take as input (`isInputArgument`, `getInstructionFunctionInputFlags`), how arguments named like an account are renamed in that input (`getRenamedArgsMap`) and compute resolver dependencies.
- `formatCode.ts`: Prettier integration.
- `typeManifest.ts`: helpers for building and merging type manifests, and the node kinds the type manifest visitor accepts.
- `generatedModules.ts`: decide the module a generated node is imported from, i.e. its folder barrel, or its own file for nodes listed in `internalNodes`, which barrels leave out. Use it wherever a generated node is imported instead of hardcoding a `generated*` module.
Expand Down
2 changes: 1 addition & 1 deletion src/fragments/constantPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
* Renders program constants as TypeScript value declarations.
*
* @param scope - The rendering scope and constants to render.
* @returns The generated constants page fragment, if constants exist.
* @return The generated constants page fragment, if constants exist.
*/
export function getConstantsPageFragment(
scope: Pick<RenderScope, 'linkables' | 'nameApi' | 'nonScalarEnums' | 'typeManifestVisitor'> & {
Expand Down
6 changes: 3 additions & 3 deletions src/fragments/discriminatorConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ function getConstantDiscriminatorConstantFragment(
const index = discriminatorNodes.filter(isNodeFilter('constantDiscriminatorNode')).indexOf(discriminatorNode);
const name = getConstantDiscriminatorName(prefix, index);
const { type, value } = discriminatorNode.constant;
return getConstantFragment({ ...scope, name, type, value });
return getConstantDeclarationFragment({ ...scope, name, type, value });
}

function getFieldDiscriminatorConstantFragment(
Expand All @@ -94,10 +94,10 @@ function getFieldDiscriminatorConstantFragment(
const { fields, prefix } = scope;
const { defaultValue, field } = getFieldDiscriminatorField(discriminatorNode, fields);
const name = getFieldDiscriminatorName(prefix, field.identifier);
return getConstantFragment({ ...scope, name, type: field.type, value: defaultValue });
return getConstantDeclarationFragment({ ...scope, name, type: field.type, value: defaultValue });
}

function getConstantFragment(
function getConstantDeclarationFragment(
scope: Pick<RenderScope, 'linkables' | 'nameApi' | 'nonScalarEnums' | 'typeManifestVisitor'> & {
name: string;
path: NodePath;
Expand Down
4 changes: 2 additions & 2 deletions src/fragments/enumDeclaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Fragment, fragment, getEnumBody, RenderScope } from '../utils';
* Renders an enum declaration whose variants are numbered sequentially from zero.
*
* @param scope - The exported name, the variant names and the render scope.
* @returns A {@link Fragment} declaring the enum.
* @return A {@link Fragment} declaring the enum.
*
* @see {@link getEnumDeclarationFromBodyFragment}
*/
Expand All @@ -29,7 +29,7 @@ export function getEnumDeclarationFragment(
* value union of a native enum.
*
* @param scope - The exported name, the object body, an optional docblock and the render scope.
* @returns A {@link Fragment} declaring the enum.
* @return A {@link Fragment} declaring the enum.
*
* @example
* ```ts
Expand Down
4 changes: 2 additions & 2 deletions src/fragments/eventPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { getTypeWithCodecFragment } from './typeWithCodec';
* its codec functions and a parse helper validating the event discriminators.
*
* @param scope - The render scope with the path to the {@link EventNode} and its byte size.
* @returns A {@link Fragment} containing the full event page.
* @return A {@link Fragment} containing the full event page.
*/
export function getEventPageFragment(
scope: Pick<RenderScope, 'erasableSyntax' | 'linkables' | 'nameApi' | 'nonScalarEnums' | 'typeManifestVisitor'> & {
Expand Down Expand Up @@ -69,7 +69,7 @@ export function getEventPageFragment(
* discriminators before decoding the provided bytes.
*
* @param scope - The render scope with the event node and its path.
* @returns A {@link Fragment} containing the parse function.
* @return A {@link Fragment} containing the parse function.
*/
function getEventParseFunctionFragment(
scope: Pick<RenderScope, 'linkables' | 'nameApi' | 'typeManifestVisitor'> & {
Expand Down
4 changes: 3 additions & 1 deletion src/fragments/instructionData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ export function getInstructionDataFragment(
): Fragment | undefined {
const { instructionPath, dataArgsManifest, nameApi, customInstructionData } = scope;
const instructionNode = getLastNodeFromPath(instructionPath);
if (!hasInstructionData(instructionNode) || getInstructionDataLink(instructionNode, customInstructionData)) return;
// Linked data is imported rather than rendered.
if (getInstructionDataLink(instructionNode, customInstructionData)) return;
if (!hasInstructionData(instructionNode, customInstructionData)) return;

const instructionDataName = nameApi.instructionDataType(instructionNode.identifier);
return getTypeWithCodecFragment({
Expand Down
50 changes: 37 additions & 13 deletions src/fragments/instructionFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
getInstructionDocs,
getInstructionFunctionInputFlags,
getProgramNodeFromPath,
getRenamedArgsMap,
hasAsyncFunction,
hasInstructionData,
hasRemainingAccountInputs,
Expand Down Expand Up @@ -58,15 +59,15 @@ export function getInstructionFunctionFragment(
dataArgsManifest: TypeManifest;
extraArgsManifest: TypeManifest;
instructionPath: NodePath<InstructionNode>;
renamedArgs: Map<string, string>;
resolvedInputs: ResolvedInstructionInput[];
resolvedInputs: readonly ResolvedInstructionInput[];
useAsync: boolean;
},
): Fragment | undefined {
const { useAsync, instructionPath, resolvedInputs, asyncResolvers, nameApi, customInstructionData } = scope;
const instructionNode = getLastNodeFromPath(instructionPath);
const programNode = getProgramNodeFromPath(instructionPath);
if (useAsync && !hasAsyncFunction(instructionNode, resolvedInputs, asyncResolvers)) return;
const renamedArgs = getRenamedArgsMap(instructionPath, scope);

const hasAccounts = (instructionNode.accounts ?? []).length > 0;
const hasData = hasInstructionData(instructionNode, customInstructionData);
Expand All @@ -91,18 +92,18 @@ export function getInstructionFunctionFragment(
const hasRemainingAccounts = !!remainingAccountsFragment;
const hasByteDeltas = !!byteDeltaFragment;
const hasResolver = resolvedInputFragment.features.has('instruction:resolverScopeVariable');
const instructionTypeFragment = getInstructionTypeFragment(scope);
const instructionTypeFragment = getReturnedInstructionTypeFragment(scope);

const typeParams = getTypeParamsFragment(instructionNode, programAddressConstant);
const returnType = getReturnTypeFragment(instructionTypeFragment, hasByteDeltas, useAsync);
const inputType = getInstructionInputTypeFragment(scope);
const inputType = getInstructionInputTypeFragment({ ...scope, renamedArgs });
const inputArg = mapFragmentContent(getInputTypeCallFragment(scope), c => (hasInput ? `input: ${c}, ` : ''));
const functionBody = mergeFragments(
[
getProgramAddressInitializationFragment(programAddressConstant),
getAccountMetaHelperFragment(instructionNode, hasAccounts || hasRemainingAccountInputs(instructionNode)),
getAccountsInitializationFragment(instructionNode, resolvedInputs),
getArgumentsInitializationFragment({ ...scope, hasAnyArgs, hasInput, omittedArgs }),
getArgumentsInitializationFragment({ ...scope, hasAnyArgs, hasInput, omittedArgs, renamedArgs }),
getResolverScopeInitializationFragment(hasResolver, hasAccounts, hasAnyArgs),
resolvedInputFragment,
getReturnStatementFragment({
Expand Down Expand Up @@ -146,7 +147,7 @@ const getAccountMeta = ${use('getAccountMetaFactory', 'solanaProgramClientCore')

function getAccountsInitializationFragment(
instructionNode: InstructionNode,
resolvedInputs: ResolvedInstructionInput[],
resolvedInputs: readonly ResolvedInstructionInput[],
): Fragment | undefined {
if ((instructionNode.accounts ?? []).length === 0) return;

Expand Down Expand Up @@ -175,7 +176,10 @@ const accounts = originalAccounts as Record<keyof typeof originalAccounts, ${use
* never upgraded, even when it defaults to a signer account, so that any signer provided for
* it merely carries its address.
*/
function getRuntimeIsSignerFlag(account: InstructionAccountNode, resolvedInputs: ResolvedInstructionInput[]): string {
function getRuntimeIsSignerFlag(
account: InstructionAccountNode,
resolvedInputs: readonly ResolvedInstructionInput[],
): string {
if (account.isSigner === false) return 'false';
const resolvedAccount = findResolvedAccount(resolvedInputs, account);
const resolvedIsSigner = resolvedAccount?.resolvedIsSigner ?? account.isSigner;
Expand All @@ -186,13 +190,14 @@ function getArgumentsInitializationFragment(
scope: Pick<RenderScope, 'typeManifestVisitor'> & {
hasAnyArgs: boolean;
hasInput: boolean;
instructionPath: NodePath<InstructionNode>;
omittedArgs: ResolvedInstructionDataField[];
renamedArgs: Map<string, string>;
},
): Fragment | undefined {
const { hasAnyArgs, hasInput, omittedArgs, renamedArgs, typeManifestVisitor } = scope;
const { hasAnyArgs, hasInput, instructionPath, omittedArgs, renamedArgs, typeManifestVisitor } = scope;
if (!hasAnyArgs) return;
const renamedArgsText = [...renamedArgs.entries()].map(([k, v]) => `${k}: input.${v}`).join(', ');
const instructionNode = getLastNodeFromPath(instructionPath);

// Arguments omitted from the input but filled in by the builder are declared on `args`.
const omittedArgsType = mergeFragments(
Expand All @@ -208,13 +213,29 @@ function getArgumentsInitializationFragment(
const args: ${omittedArgsType} = {};
`;
}

// Arguments renamed in the input, since they are named like an account, are mapped back.
const renamedArgsText = [...renamedArgs.entries()].map(([k, v]) => `${k}: input.${v}`).join(', ');
const inputArgs = `{ ...input, ${renamedArgsText} }`;

// Omitted arguments named like an account would otherwise read the account from the input.
const accountNames = new Set((instructionNode.accounts ?? []).map(account => camelCase(account.identifier)));
const shadowedArgsText = omittedArgs
.map(input => camelCase(input.node.identifier))
.filter(name => accountNames.has(name))
.map(name => `${name}: _${name}, `)
.join('');
const originalArgs = shadowedArgsText
? `{ ${shadowedArgsText}...originalArgs } = ${inputArgs}`
: `originalArgs = ${inputArgs}`;

if (omittedArgs.length === 0) {
return fragment`// Original args.
const args = { ...input, ${renamedArgsText} };
const args = ${inputArgs};
`;
}
return fragment`// Original args.
const originalArgs = { ...input, ${renamedArgsText} };
const ${originalArgs};
const args: typeof originalArgs & ${omittedArgsType} = originalArgs;
`;
}
Expand Down Expand Up @@ -303,7 +324,7 @@ function getReturnTypeFragment(instructionTypeFragment: Fragment, hasByteDeltas:
/**
* Instruction builders declare one type parameter per account, holding the input value
* provided for that account, so that the account metas of the returned instruction can be
* derived from the exact values provided (see {@link getInstructionTypeFragment}). Since the
* derived from the exact values provided (see {@link getReturnedInstructionTypeFragment}). Since the
* `input` parameter remains a concrete object type once these are inferred, TypeScript keeps
* performing excess property checks on it — e.g. a misspelled optional account is a compile
* error rather than silently falling back to its default value.
Expand All @@ -329,7 +350,10 @@ function getTypeParamsFragment(instructionNode: InstructionNode, programAddressC
* account's address type parameter — which the instruction type then maps to the account
* meta declared by the program's IDL.
*/
function getInstructionTypeFragment(scope: { instructionPath: NodePath<InstructionNode>; nameApi: NameApi }): Fragment {
function getReturnedInstructionTypeFragment(scope: {
instructionPath: NodePath<InstructionNode>;
nameApi: NameApi;
}): Fragment {
const { instructionPath, nameApi } = scope;
const instructionNode = getLastNodeFromPath(instructionPath);
const instructionTypeName = nameApi.instructionType(instructionNode.identifier);
Expand Down
7 changes: 5 additions & 2 deletions src/fragments/instructionInputDefault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,9 @@ export function getInstructionInputDefaultFragment(
);

case 'pdaValueNode':
// Account values accept the derived address with its bump, whilst data fields hold the address.
const pdaDefault = (pda: Fragment) =>
defaultFragment(input.kind === 'account' ? pda : fragment`(${pda})[0]`);
let pdaProgramValue: Fragment | undefined;
if (isNode(defaultValue.programId, 'accountValueNode')) {
const name = camelCase(defaultValue.programId.identifier);
Expand Down Expand Up @@ -195,7 +198,7 @@ export function getInstructionInputDefaultFragment(
const programAddress =
pdaProgram.content === 'programAddress' ? pdaProgram : fragment`programAddress: ${pdaProgram}`;
const seeds = mergeFragments(pdaSeeds, s => s.join(', '));
return defaultFragment(
return pdaDefault(
fragment`await ${getProgramDerivedAddress}({ ${programAddress}, seeds: [${seeds}] })`,
);
}
Expand Down Expand Up @@ -236,7 +239,7 @@ export function getInstructionInputDefaultFragment(
} else if (isPdaDerivedFromInstructionProgram(pdaPath, instructionPath)) {
pdaArgs.push(fragment`{ programAddress }`);
}
return defaultFragment(fragment`await ${pdaFunction}(${mergeFragments(pdaArgs, c => c.join(', '))})`);
return pdaDefault(fragment`await ${pdaFunction}(${mergeFragments(pdaArgs, c => c.join(', '))})`);

case 'publicKeyValueNode':
return defaultFragment(
Expand Down
2 changes: 1 addition & 1 deletion src/fragments/instructionInputResolved.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function getInstructionInputResolvedFragment(
'asyncResolvers' | 'getImportFrom' | 'linkables' | 'nameApi' | 'nonScalarEnums' | 'typeManifestVisitor'
> & {
instructionPath: NodePath<InstructionNode>;
resolvedInputs: ResolvedInstructionInput[];
resolvedInputs: readonly ResolvedInstructionInput[];
useAsync: boolean;
},
): Fragment {
Expand Down
10 changes: 5 additions & 5 deletions src/fragments/instructionInputType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function getInstructionInputTypeFragment(
dataArgsManifest: TypeManifest;
instructionPath: NodePath<InstructionNode>;
renamedArgs: Map<string, string>;
resolvedInputs: ResolvedInstructionInput[];
resolvedInputs: readonly ResolvedInstructionInput[];
useAsync: boolean;
},
): Fragment {
Expand Down Expand Up @@ -94,7 +94,7 @@ export function getInstructionAccountInputConstraintFragment(
function getAccountsFragment(
scope: Pick<RenderScope, 'asyncResolvers' | 'customInstructionData' | 'nameApi'> & {
instructionPath: NodePath<InstructionNode>;
resolvedInputs: ResolvedInstructionInput[];
resolvedInputs: readonly ResolvedInstructionInput[];
useAsync: boolean;
},
): Fragment {
Expand All @@ -119,7 +119,7 @@ function getDataArgumentsFragments(
dataArgsManifest: TypeManifest;
instructionPath: NodePath<InstructionNode>;
renamedArgs: Map<string, string>;
resolvedInputs: ResolvedInstructionInput[];
resolvedInputs: readonly ResolvedInstructionInput[];
useAsync: boolean;
},
): [Fragment | undefined, Fragment] {
Expand Down Expand Up @@ -153,7 +153,7 @@ function getExtraArgumentsFragment(
scope: Pick<RenderScope, 'asyncResolvers' | 'nameApi'> & {
instructionPath: NodePath<InstructionNode>;
renamedArgs: Map<string, string>;
resolvedInputs: ResolvedInstructionInput[];
resolvedInputs: readonly ResolvedInstructionInput[];
useAsync: boolean;
},
): Fragment | undefined {
Expand All @@ -176,7 +176,7 @@ function getArgumentFragment(
argsType: string,
scope: Pick<RenderScope, 'asyncResolvers'> & {
renamedArgs: Map<string, string>;
resolvedInputs: ResolvedInstructionInput[];
resolvedInputs: readonly ResolvedInstructionInput[];
useAsync: boolean;
},
): Fragment | undefined {
Expand Down
Loading