diff --git a/.changeset/grumpy-pears-attend.md b/.changeset/grumpy-pears-attend.md new file mode 100644 index 0000000..011d7b6 --- /dev/null +++ b/.changeset/grumpy-pears-attend.md @@ -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. diff --git a/AGENTS.md b/AGENTS.md index 24ad090..da46a25 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/CLAUDE.md b/CLAUDE.md index 24ad090..da46a25 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. diff --git a/src/fragments/constantPage.ts b/src/fragments/constantPage.ts index 5d342f0..206ebb0 100644 --- a/src/fragments/constantPage.ts +++ b/src/fragments/constantPage.ts @@ -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 & { diff --git a/src/fragments/discriminatorConstants.ts b/src/fragments/discriminatorConstants.ts index b0e31d7..abb7275 100644 --- a/src/fragments/discriminatorConstants.ts +++ b/src/fragments/discriminatorConstants.ts @@ -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( @@ -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 & { name: string; path: NodePath; diff --git a/src/fragments/enumDeclaration.ts b/src/fragments/enumDeclaration.ts index 33a8ee2..dba74da 100644 --- a/src/fragments/enumDeclaration.ts +++ b/src/fragments/enumDeclaration.ts @@ -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} */ @@ -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 diff --git a/src/fragments/eventPage.ts b/src/fragments/eventPage.ts index 528b144..0258c23 100644 --- a/src/fragments/eventPage.ts +++ b/src/fragments/eventPage.ts @@ -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 & { @@ -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 & { diff --git a/src/fragments/instructionData.ts b/src/fragments/instructionData.ts index 579033b..e0db1d3 100644 --- a/src/fragments/instructionData.ts +++ b/src/fragments/instructionData.ts @@ -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({ diff --git a/src/fragments/instructionFunction.ts b/src/fragments/instructionFunction.ts index 8cdee26..918c0a2 100644 --- a/src/fragments/instructionFunction.ts +++ b/src/fragments/instructionFunction.ts @@ -14,6 +14,7 @@ import { getInstructionDocs, getInstructionFunctionInputFlags, getProgramNodeFromPath, + getRenamedArgsMap, hasAsyncFunction, hasInstructionData, hasRemainingAccountInputs, @@ -58,8 +59,7 @@ export function getInstructionFunctionFragment( dataArgsManifest: TypeManifest; extraArgsManifest: TypeManifest; instructionPath: NodePath; - renamedArgs: Map; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): Fragment | undefined { @@ -67,6 +67,7 @@ export function getInstructionFunctionFragment( 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); @@ -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({ @@ -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; @@ -175,7 +176,10 @@ const accounts = originalAccounts as Record & { hasAnyArgs: boolean; hasInput: boolean; + instructionPath: NodePath; omittedArgs: ResolvedInstructionDataField[]; renamedArgs: Map; }, ): 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( @@ -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; `; } @@ -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. @@ -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; nameApi: NameApi }): Fragment { +function getReturnedInstructionTypeFragment(scope: { + instructionPath: NodePath; + nameApi: NameApi; +}): Fragment { const { instructionPath, nameApi } = scope; const instructionNode = getLastNodeFromPath(instructionPath); const instructionTypeName = nameApi.instructionType(instructionNode.identifier); diff --git a/src/fragments/instructionInputDefault.ts b/src/fragments/instructionInputDefault.ts index 42670e9..7553f2c 100644 --- a/src/fragments/instructionInputDefault.ts +++ b/src/fragments/instructionInputDefault.ts @@ -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); @@ -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}] })`, ); } @@ -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( diff --git a/src/fragments/instructionInputResolved.ts b/src/fragments/instructionInputResolved.ts index 64c3b1e..7ba01ec 100644 --- a/src/fragments/instructionInputResolved.ts +++ b/src/fragments/instructionInputResolved.ts @@ -20,7 +20,7 @@ export function getInstructionInputResolvedFragment( 'asyncResolvers' | 'getImportFrom' | 'linkables' | 'nameApi' | 'nonScalarEnums' | 'typeManifestVisitor' > & { instructionPath: NodePath; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): Fragment { diff --git a/src/fragments/instructionInputType.ts b/src/fragments/instructionInputType.ts index 4323297..a7f6c8a 100644 --- a/src/fragments/instructionInputType.ts +++ b/src/fragments/instructionInputType.ts @@ -39,7 +39,7 @@ export function getInstructionInputTypeFragment( dataArgsManifest: TypeManifest; instructionPath: NodePath; renamedArgs: Map; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): Fragment { @@ -94,7 +94,7 @@ export function getInstructionAccountInputConstraintFragment( function getAccountsFragment( scope: Pick & { instructionPath: NodePath; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): Fragment { @@ -119,7 +119,7 @@ function getDataArgumentsFragments( dataArgsManifest: TypeManifest; instructionPath: NodePath; renamedArgs: Map; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): [Fragment | undefined, Fragment] { @@ -153,7 +153,7 @@ function getExtraArgumentsFragment( scope: Pick & { instructionPath: NodePath; renamedArgs: Map; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): Fragment | undefined { @@ -176,7 +176,7 @@ function getArgumentFragment( argsType: string, scope: Pick & { renamedArgs: Map; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): Fragment | undefined { diff --git a/src/fragments/instructionPage.ts b/src/fragments/instructionPage.ts index 4be6cac..e298c3e 100644 --- a/src/fragments/instructionPage.ts +++ b/src/fragments/instructionPage.ts @@ -9,7 +9,6 @@ import { getProgramNodeFromPath, getRenamedArgsMap, getStructFields, - isInputArgument, mergeFragments, RenderScope, ResolvedInstructionInput, @@ -45,7 +44,7 @@ export function getInstructionPageFragment( | 'typeManifestVisitor' > & { instructionPath: NodePath; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; size: number | null; }, ): Fragment { @@ -63,15 +62,14 @@ export function getInstructionPageFragment( }), scope.typeManifestVisitor, ), - // Synchronous builders accept every input asynchronous ones do, and more. - renamedArgs: getRenamedArgsMap(scope.instructionPath, arg => - isInputArgument(arg, { ...scope, useAsync: false }), - ), }; - if (childScope.renamedArgs.size > 0) { + // Each builder renames the arguments of its own input; the synchronous input, which + // accepts every input the asynchronous one does, lists every renamed argument. + const renamedArgs = getRenamedArgsMap(scope.instructionPath, { ...scope, useAsync: false }); + if (renamedArgs.size > 0) { logWarn( `[JavaScript] Accounts and args of instruction [${node.identifier}] have the following ` + - `conflicting attributes [${[...childScope.renamedArgs.keys()].join(', ')}]. ` + + `conflicting attributes [${[...renamedArgs.keys()].join(', ')}]. ` + `Thus, the arguments have been renamed to avoid conflicts in the input type.`, ); } diff --git a/src/fragments/instructionParseFunction.ts b/src/fragments/instructionParseFunction.ts index 3c08615..5cdca61 100644 --- a/src/fragments/instructionParseFunction.ts +++ b/src/fragments/instructionParseFunction.ts @@ -38,10 +38,12 @@ export function getInstructionParseFunctionFragment( ); const childScope = { ...scope, instructionNode, programAddressConstant }; - return mergeFragments([getTypeFragment(childScope), getFunctionFragment(childScope)], cs => cs.join('\n\n')); + return mergeFragments([getParsedTypeFragment(childScope), getParseFunctionFragment(childScope)], cs => + cs.join('\n\n'), + ); } -function getTypeFragment( +function getParsedTypeFragment( scope: Pick & { dataArgsManifest: TypeManifest; instructionNode: InstructionNode; @@ -82,7 +84,7 @@ function getTypeFragment( return fragment`export type ${instructionParsedType}<${typeParamDeclarations}> = { programAddress: ${use('type Address', 'solanaAddresses')};${accounts}${data} };`; } -function getFunctionFragment( +function getParseFunctionFragment( scope: Pick & { dataArgsManifest: TypeManifest; instructionNode: InstructionNode; diff --git a/src/fragments/pdaFunction.ts b/src/fragments/pdaFunction.ts index c2ac471..c50e6b5 100644 --- a/src/fragments/pdaFunction.ts +++ b/src/fragments/pdaFunction.ts @@ -3,12 +3,13 @@ import { isNode, isNodeFilter, PdaNode, PdaSeedNode } from '@codama/nodes'; import { getLastNodeFromPath, NodePath, visit } from '@codama/visitors-core'; import { - fragment, Fragment, + fragment, getDocblockFragment, getProgramNodeFromPath, getStringLiteral, getTypedValueFragment, + hasVariablePdaSeeds, mergeFragments, RenderScope, use, @@ -29,7 +30,7 @@ export function getPdaFunctionFragment( const pdaNode = getLastNodeFromPath(scope.pdaPath); const seeds = parsePdaSeedNodes(pdaNode.seeds ?? [], scope); - return mergeFragments([getSeedInputTypeFragment(seeds, scope), getFunctionFragment(seeds, scope)], cs => + return mergeFragments([getSeedInputTypeFragment(seeds, scope), getFindPdaFunctionFragment(seeds, scope)], cs => cs.join('\n\n'), ); } @@ -53,7 +54,7 @@ function getSeedInputTypeFragment( return fragment`export type ${seedTypeName} = {\n${seedAttributes}\n};`; } -function getFunctionFragment( +function getFindPdaFunctionFragment( seeds: ParsedPdaSeedNode[], scope: Pick & { pdaPath: NodePath; @@ -71,7 +72,7 @@ function getFunctionFragment( const findPdaFunction = scope.nameApi.pdaFindFunction(pdaNode.identifier); const docs = getDocblockFragment(pdaNode.docs, true); - const hasVariableSeeds = seeds.filter(isNodeFilter('variablePdaSeedNode')).length > 0; + const hasVariableSeeds = hasVariablePdaSeeds(pdaNode); const seedArgument = hasVariableSeeds ? `seeds: ${seedTypeName}, ` : ''; const programAddress = pdaNode.programId ?? programNode.publicKey; const encodedSeeds = mergeFragments( diff --git a/src/fragments/programEvents.ts b/src/fragments/programEvents.ts index da1ff64..e292c24 100644 --- a/src/fragments/programEvents.ts +++ b/src/fragments/programEvents.ts @@ -11,7 +11,7 @@ import { getEnumDeclarationFragment } from './enumDeclaration'; * and a function identifying which event some given data belongs to. * * @param scope - The render scope with the program node. - * @returns A {@link Fragment} with the event helpers, or `undefined` when the program has no events. + * @return A {@link Fragment} with the event helpers, or `undefined` when the program has no events. */ export function getProgramEventsFragment( scope: Pick & { diff --git a/src/fragments/programPlugin.ts b/src/fragments/programPlugin.ts index fabd3f4..b01f1c7 100644 --- a/src/fragments/programPlugin.ts +++ b/src/fragments/programPlugin.ts @@ -3,8 +3,9 @@ import { AccountNode, InstructionNode, isNode, PdaNode, ProgramNode } from '@cod import { getLastNodeFromPath, NodePath } from '@codama/visitors-core'; import { - Fragment, fragment, + Fragment, + GeneratedNodeModuleScope, getDocblockFragment, getGeneratedNodeModule, getInstructionDataFields, @@ -16,7 +17,6 @@ import { getResolvedInstructionInputs, hasAsyncFunction, hasVariablePdaSeeds, - isInputArgument, isPdaDerivedFromProgram, mergeFragments, RenderScope, @@ -125,7 +125,7 @@ function getProgramPluginTypeFragment( } function getProgramPluginAccountsTypeFragment( - scope: ModuleScope & { accounts: AccountNode[]; programNode: ProgramNode }, + scope: GeneratedNodeModuleScope & { accounts: AccountNode[]; programNode: ProgramNode }, ): Fragment | undefined { const { accounts, programNode, nameApi } = scope; if (accounts.length === 0) return; @@ -148,7 +148,7 @@ function getProgramPluginAccountsTypeFragment( } function getProgramPluginInstructionsTypeFragment( - scope: ModuleScope & { instructions: PluginInstruction[]; programNode: ProgramNode }, + scope: GeneratedNodeModuleScope & { instructions: PluginInstruction[]; programNode: ProgramNode }, ): Fragment | undefined { const { instructions, programNode, nameApi } = scope; if (instructions.length === 0) return; @@ -182,7 +182,7 @@ function getProgramPluginInstructionsTypeFragment( } function getProgramPluginPdasTypeFragment( - scope: ModuleScope & { pdas: PdaNode[]; programNode: ProgramNode }, + scope: GeneratedNodeModuleScope & { pdas: PdaNode[]; programNode: ProgramNode }, ): Fragment | undefined { const { pdas, programNode, nameApi } = scope; if (pdas.length === 0) return; @@ -204,7 +204,7 @@ function getProgramPluginPdasTypeFragment( } function getProgramPluginPdasObjectFragment( - scope: ModuleScope & { pdas: PdaNode[]; programNode: ProgramNode }, + scope: GeneratedNodeModuleScope & { pdas: PdaNode[]; programNode: ProgramNode }, ): Fragment | undefined { const { pdas, programNode, nameApi } = scope; if (pdas.length === 0) return; @@ -260,7 +260,7 @@ function getProgramPluginRequirementsTypeFragment( } function getProgramPluginFunctionFragment( - scope: ModuleScope & + scope: GeneratedNodeModuleScope & Pick & { accounts: AccountNode[]; instructions: PluginInstruction[]; @@ -314,7 +314,7 @@ function getProgramPluginFunctionFragment( } function getProgramPluginAccountsObjectFragment( - scope: ModuleScope & { accounts: AccountNode[] }, + scope: GeneratedNodeModuleScope & { accounts: AccountNode[] }, ): Fragment | undefined { const { accounts, nameApi } = scope; if (accounts.length === 0) return; @@ -336,7 +336,7 @@ function getProgramPluginAccountsObjectFragment( } function getProgramPluginInstructionsObjectFragment( - scope: ModuleScope & { instructions: PluginInstruction[] }, + scope: GeneratedNodeModuleScope & { instructions: PluginInstruction[] }, ): Fragment | undefined { const { instructions, nameApi } = scope; if (instructions.length === 0) return; @@ -379,9 +379,6 @@ function getMakeOptionalHelperTypeFragment(scope: { instructions: PluginInstruct return fragment`type MakeOptional = Omit & Partial>;`; } -/** The scope the plugin needs to import generated nodes, from their barrel or their own file. */ -type ModuleScope = Pick; - /** An instruction exposed by the plugin, with what the plugin needs to know about its builders. */ type PluginInstruction = { /** Whether the builder the plugin calls takes an `input` parameter. */ @@ -398,14 +395,11 @@ function getPluginInstruction( scope: Pick, ): PluginInstruction { const node = getLastNodeFromPath(path); - const { asyncResolvers } = scope; const resolvedInputs = getResolvedInstructionInputs(path, scope.linkables); - const isAsync = hasAsyncFunction(node, resolvedInputs, asyncResolvers); - // Synchronous builders accept every input asynchronous ones do, and more. - const renamedArgs = getRenamedArgsMap(path, arg => - isInputArgument(arg, { asyncResolvers, resolvedInputs, useAsync: false }), - ); - const { hasInput } = getInstructionFunctionInputFlags(node, { ...scope, resolvedInputs, useAsync: isAsync }); + const isAsync = hasAsyncFunction(node, resolvedInputs, scope.asyncResolvers); + const builderScope = { ...scope, resolvedInputs, useAsync: isAsync }; + const renamedArgs = getRenamedArgsMap(path, builderScope); + const { hasInput } = getInstructionFunctionInputFlags(node, builderScope); const payerDefaultValues = getPayerDefaultValues(node, resolvedInputs, renamedArgs); return { hasInput, isAsync, node, payerDefaultValues }; } diff --git a/src/utils/async.ts b/src/utils/async.ts index e5ca81c..0af2c58 100644 --- a/src/utils/async.ts +++ b/src/utils/async.ts @@ -1,10 +1,13 @@ +import { CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE, CodamaError } from '@codama/errors'; import { camelCase } from '@codama/fragments/casing'; import { InstructionNode, isNode, isNodeFilter } from '@codama/nodes'; +import { getLastNodeFromPath, NodePath } from '@codama/visitors-core'; import type { ParsedCustomDataOptions } from './customData'; import { deduplicateInstructionDependencies, findResolvedDataField, + getAllInstructionDataFields, getByteDeltaResolver, getDataPathRoot, getDefaultValueDependencies, @@ -42,7 +45,7 @@ export function isAsyncResolver(resolverName: string, asyncResolvers: string[]): */ export function hasAsyncFunction( instructionNode: InstructionNode, - resolvedInputs: ResolvedInstructionInput[], + resolvedInputs: readonly ResolvedInstructionInput[], asyncResolvers: string[], ): boolean { const hasByteDeltasAsync = (instructionNode.byteDeltas ?? []).some(byteDelta => { @@ -57,7 +60,7 @@ export function hasAsyncFunction( return hasAsyncDefaultValues(resolvedInputs, asyncResolvers) || hasByteDeltasAsync || hasRemainingAccountsAsync; } -function hasAsyncDefaultValues(resolvedInputs: ResolvedInstructionInput[], asyncResolvers: string[]): boolean { +function hasAsyncDefaultValues(resolvedInputs: readonly ResolvedInstructionInput[], asyncResolvers: string[]): boolean { return resolvedInputs.some(input => isAsyncInput(input, asyncResolvers)); } @@ -94,7 +97,7 @@ function isAsyncDefaultValue(defaultValue: InstructionInputDefaultValue): boolea */ function getInstructionDependencies( instructionNode: InstructionNode, - resolvedInputs: ResolvedInstructionInput[], + resolvedInputs: readonly ResolvedInstructionInput[], asyncResolvers: string[], useAsync: boolean, ): InstructionDependency[] { @@ -172,6 +175,45 @@ export function isInputArgument( return arg.defaultValueStrategy !== 'omitted' || !isArgumentFilledIn(arg, scope); } +/** + * Maps the camelCase name of each input argument conflicting with an account of the + * instruction to the camelCase name it is renamed to in the input type of a builder, + * e.g. `authority` to `authorityArg`. Arguments left out of that input, e.g. omitted + * arguments the builder fills in, never conflict, so the map depends on the builder: + * the synchronous one accepts every input the asynchronous one does, and more. + * + * Names are compared by their camelCase form since that is how they are emitted. + * + * @param instructionPath - The path of the instruction. + * @param scope - The resolved inputs, the asynchronous resolvers and whether the builder is asynchronous. + * @throws `CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE` with the path of the instruction when two + * of its data fields or extra arguments share a name. + * + * @example + * ```ts + * getRenamedArgsMap(instructionPath, { ...scope, useAsync: false }); // Map { 'authority' => 'authorityArg' } + * ``` + */ +export function getRenamedArgsMap( + instructionPath: NodePath, + scope: { asyncResolvers: string[]; resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean }, +): Map { + const instruction = getLastNodeFromPath(instructionPath); + const args = getAllInstructionDataFields(instruction); + const argNames = args.map(arg => camelCase(arg.identifier)); + // Data fields and extra arguments share the input type, so their names must be unique. + if (new Set(argNames).size !== argNames.length) { + throw new CodamaError(CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE, { path: instructionPath }); + } + + const accountNames = new Set((instruction.accounts ?? []).map(account => camelCase(account.identifier))); + const conflictingNames = args + .filter(arg => isInputArgument(arg, scope)) + .map(arg => camelCase(arg.identifier)) + .filter(name => accountNames.has(name)); + return new Map(conflictingNames.map(name => [name, camelCase(`${name}Arg`)])); +} + /** * Determines which inputs the sync or async builder of an instruction accepts, so that * callers such as the program plugin can invoke it with the same arguments it declares. @@ -188,7 +230,7 @@ export function getInstructionFunctionInputFlags( scope: { asyncResolvers: string[]; customInstructionData: ParsedCustomDataOptions; - resolvedInputs: ResolvedInstructionInput[]; + resolvedInputs: readonly ResolvedInstructionInput[]; useAsync: boolean; }, ): { hasAnyArgs: boolean; hasDataArgs: boolean; hasInput: boolean; omittedArgs: ResolvedInstructionDataField[] } { @@ -204,7 +246,8 @@ export function getInstructionFunctionInputFlags( const argDependencies = instructionDependencies .filter(isNodeFilter('dataValueNode')) .map(node => getDataPathRoot(node.path)); - const argIsNotOmitted = (arg: InstructionDataField) => isInputArgument(arg, scope); + const isInput = (arg: InstructionDataField) => isInputArgument(arg, scope); + const hasInputDataFields = getInstructionDataFields(instructionNode).some(isInput); const argIsDependent = (arg: InstructionDataField) => argDependencies.includes(arg.identifier); const argHasDefaultValue = (arg: InstructionDataField) => { if (!hasInputDefault(arg)) return false; @@ -213,25 +256,17 @@ export function getInstructionFunctionInputFlags( return !resolvedArg || !isAsyncInput(resolvedArg, asyncResolvers); }; const omittedArgs = resolvedInputs.filter( - (input): input is ResolvedInstructionDataField => input.kind === 'data' && !argIsNotOmitted(input.node), + (input): input is ResolvedInstructionDataField => input.kind === 'data' && !isInput(input.node), ); const hasOmittedDataArgs = omittedArgs.some(input => !input.isExtraArgument); - const hasDataArgs = - !!dataLink || - hasOmittedDataArgs || - getInstructionDataFields(instructionNode).filter(argIsNotOmitted).length > 0; - const hasExtraArgs = - getInstructionExtraArguments(instructionNode).filter( - field => argIsNotOmitted(field) && (argIsDependent(field) || argHasDefaultValue(field)), - ).length > 0; + const hasDataArgs = !!dataLink || hasOmittedDataArgs || hasInputDataFields; + const hasExtraArgs = getInstructionExtraArguments(instructionNode).some( + field => isInput(field) && (argIsDependent(field) || argHasDefaultValue(field)), + ); const hasRemainingAccountArgs = (instructionNode.remainingAccounts ?? []).some( remainingAccounts => getRemainingAccountsName(remainingAccounts) !== undefined, ); - const hasInputArgs = - !!dataLink || - getInstructionDataFields(instructionNode).filter(argIsNotOmitted).length > 0 || - hasExtraArgs || - hasRemainingAccountArgs; + const hasInputArgs = !!dataLink || hasInputDataFields || hasExtraArgs || hasRemainingAccountArgs; const hasAnyArgs = hasInputArgs || omittedArgs.length > 0; return { hasAnyArgs, hasDataArgs, hasInput: hasAccounts || hasInputArgs, omittedArgs }; } diff --git a/src/utils/enums.ts b/src/utils/enums.ts index ca4deb9..7c684a6 100644 --- a/src/utils/enums.ts +++ b/src/utils/enums.ts @@ -18,7 +18,7 @@ import { isNodeObject } from './nodePaths'; * otherwise its position in the enum, starting at zero. * * @param variants - The variants of the enum, in declaration order. - * @returns The discriminator value of each variant, in the same order. + * @return The discriminator value of each variant, in the same order. */ export function getEnumVariantDiscriminators(variants: readonly EnumVariantTypeNode[]): number[] { return variants.map((variant, index) => variant.discriminator ?? index); diff --git a/src/utils/erasableSyntax.ts b/src/utils/erasableSyntax.ts index c0ead2a..5e63183 100644 --- a/src/utils/erasableSyntax.ts +++ b/src/utils/erasableSyntax.ts @@ -10,7 +10,7 @@ * @param erasableSyntax - Whether to render the runtime object used for erasable enums. * @param values - The explicit value of each variant, in declaration order. Variants are * numbered from zero when omitted. - * @returns The object body, without the surrounding braces. + * @return The object body, without the surrounding braces. * * @example * ```ts diff --git a/src/utils/generatedModules.ts b/src/utils/generatedModules.ts index 6a47559..f726407 100644 --- a/src/utils/generatedModules.ts +++ b/src/utils/generatedModules.ts @@ -27,6 +27,13 @@ const GENERATED_FOLDERS: Record boolean; +/** The scope needed to import a generated node: whether it is internal, its file name and import paths. */ +export type GeneratedNodeModuleScope = { + getImportPath: GetImportPathFunction; + isInternalNode: IsInternalNodeFunction; + nameApi: NameApi; +}; + /** * Creates the function telling whether a node is listed in the `internalNodes` option, * matching identifiers by their camelCase form. @@ -56,7 +63,7 @@ export function getIsInternalNodeFactory(internalNodes: readonly string[]): IsIn export function getGeneratedNodeModule( kind: GeneratedNodeKind, identifier: string, - scope: { getImportPath: GetImportPathFunction; isInternalNode: IsInternalNodeFunction; nameApi: NameApi }, + scope: GeneratedNodeModuleScope, ): string { const { folder, module } = GENERATED_FOLDERS[kind]; if (!scope.isInternalNode(identifier)) return module; diff --git a/src/utils/instructionInputs.ts b/src/utils/instructionInputs.ts index 2867ff1..c75b118 100644 --- a/src/utils/instructionInputs.ts +++ b/src/utils/instructionInputs.ts @@ -18,15 +18,12 @@ import { } from '@codama/errors'; import { camelCase, pascalCase } from '@codama/fragments/casing'; import { - AccountNode, accountValueNode, AccountValueNode, DataValueNode, dataValueNode, DefaultValueStrategy, DefinedTypeLinkNode, - DefinedTypeNode, - definedTypeNode, IdentifierString, INSTRUCTION_INPUT_VALUE_NODE_KINDS, InstructionAccountNode, @@ -60,7 +57,8 @@ import { resolveTypePath, } from '@codama/visitors-core'; -import { getCustomDataOptions, type ParsedCustomDataOptions } from './customData'; +import type { ParsedCustomDataOptions } from './customData'; +import { getCustomDataOptions } from './customData'; import { isNodeObject } from './nodePaths'; const RESOLVER_PLUGIN = 'codama.resolver'; @@ -141,13 +139,13 @@ export function getAllInstructionDataFields(instruction: InstructionNode): Instr * when the `customInstructionData` option is given, its data is provided by it. * * @param instruction - The instruction. - * @param customInstructionData - The parsed `customInstructionData` option, if any. + * @param customInstructionData - The parsed `customInstructionData` option. */ export function hasInstructionData( instruction: InstructionNode, - customInstructionData?: ParsedCustomDataOptions, + customInstructionData: ParsedCustomDataOptions, ): boolean { - if (customInstructionData && getInstructionDataLink(instruction, customInstructionData)) return true; + if (getInstructionDataLink(instruction, customInstructionData)) return true; const { data } = instruction; return !!data && !(isNode(data, 'structTypeNode') && (data.fields ?? []).length === 0); } @@ -177,35 +175,6 @@ export function getInstructionDataNode(instruction: InstructionNode): DefinedTyp throw new CodamaError(CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE, { path: [instruction, instruction.data] }); } -/** - * The defined types to render for the custom data of accounts or instructions configured with - * `extract: true`, holding the data they would have generated. - * - * @param nodes - The accounts or instructions, e.g. the ones rendered as pages. - * @param parsedCustomDataOptions - The parsed custom data options. - * @return The defined types to render. - */ -export function getDefinedTypeNodesToExtract( - nodes: AccountNode[] | InstructionNode[], - parsedCustomDataOptions: ParsedCustomDataOptions, -): DefinedTypeNode[] { - return nodes.flatMap(node => { - const options = getCustomDataOptions(parsedCustomDataOptions, node); - if (!options || !options.extract) return []; - - if (isNode(node, 'accountNode')) { - return [definedTypeNode({ identifier: options.extractAs, type: { ...node.data } })]; - } - - return [ - definedTypeNode({ - identifier: options.extractAs, - type: getInstructionDataNode(node), - }), - ]; - }); -} - /** * The type describing the extra arguments of the instruction. Only literal default * values are kept, since contextual ones are resolved by instruction builders. @@ -922,46 +891,6 @@ function parseExtraArgumentPlugin(plugin: PluginNode, instruction: InstructionNo }); } -/** - * Maps the camelCase name of each input argument conflicting with an account of the - * instruction to the camelCase name it is renamed to in the instruction input type, - * e.g. `authority` to `authorityArg`. Omitted arguments are not part of the input type, - * so they never conflict. - * - * Names are compared by their camelCase form since that is how they are emitted. - * - * @param instructionPath - The path of the instruction. - * @param isInputArgument - Whether an argument is part of the input of the builders, which - * should be the input of the synchronous builder, since it accepts every input the - * asynchronous one does, and more. - * @throws `CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE` with the path of the instruction when two - * of its data fields or extra arguments share a name. - * - * @example - * ```ts - * getRenamedArgsMap(instructionPath, arg => isInputArgument(arg, scope)); // Map { 'authority' => 'authorityArg' } - * ``` - */ -export function getRenamedArgsMap( - instructionPath: NodePath, - isInputArgument: (arg: InstructionDataField) => boolean, -): Map { - const instruction = getLastNodeFromPath(instructionPath); - const args = getAllInstructionDataFields(instruction); - const argNames = args.map(arg => camelCase(arg.identifier)); - // Data fields and extra arguments share the input type, so their names must be unique. - if (new Set(argNames).size !== argNames.length) { - throw new CodamaError(CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE, { path: instructionPath }); - } - - const accountNames = new Set((instruction.accounts ?? []).map(account => camelCase(account.identifier))); - const conflictingNames = args - .filter(isInputArgument) - .map(arg => camelCase(arg.identifier)) - .filter(name => accountNames.has(name)); - return new Map(conflictingNames.map(name => [name, camelCase(`${name}Arg`)])); -} - /** * The name of the type parameter holding the input of an instruction account in * instruction types and builders, e.g. `TAccountMint` for the `mint` account. diff --git a/src/utils/linkOverrides.ts b/src/utils/linkOverrides.ts index fa4ae1e..8ab354e 100644 --- a/src/utils/linkOverrides.ts +++ b/src/utils/linkOverrides.ts @@ -2,11 +2,11 @@ import { CODAMA_ERROR__UNEXPECTED_NODE_KIND, CodamaError } from '@codama/errors' import { camelCase } from '@codama/fragments/casing'; import { AccountLinkNode, DefinedTypeLinkNode, InstructionLinkNode, PdaLinkNode, ProgramLinkNode } from '@codama/nodes'; -import { ParsedCustomDataOptions } from './customData'; -import { getGeneratedNodeModule, type IsInternalNodeFunction } from './generatedModules'; -import { InstructionResolver, isInstructionResolver } from './instructionInputs'; -import type { NameApi } from './nameTransformers'; -import type { GetImportPathFunction } from './options'; +import type { ParsedCustomDataOptions } from './customData'; +import type { GeneratedNodeModuleScope } from './generatedModules'; +import { getGeneratedNodeModule } from './generatedModules'; +import type { InstructionResolver } from './instructionInputs'; +import { isInstructionResolver } from './instructionInputs'; /** * Maps the names of linked nodes to the module they should be imported from. @@ -44,7 +44,7 @@ export function getImportFromFactory( overrides: LinkOverrides, customAccountData: ParsedCustomDataOptions, customInstructionData: ParsedCustomDataOptions, - scope: { getImportPath: GetImportPathFunction; isInternalNode: IsInternalNodeFunction; nameApi: NameApi }, + scope: GeneratedNodeModuleScope, ): GetImportFromFunction { const customDataOverrides = Object.fromEntries( [...customAccountData.values(), ...customInstructionData.values()].map(({ importFrom, importAs }) => [ diff --git a/src/utils/pdas.ts b/src/utils/pdas.ts index 649c012..70f5e9f 100644 --- a/src/utils/pdas.ts +++ b/src/utils/pdas.ts @@ -1,4 +1,5 @@ -import { isNodeFilter, type PdaNode, type ProgramNode } from '@codama/nodes'; +import type { PdaNode, ProgramNode } from '@codama/nodes'; +import { isNodeFilter } from '@codama/nodes'; /** * Whether a PDA takes variable seeds, so that its find function takes a `seeds` argument. diff --git a/src/utils/renderedAttributes.ts b/src/utils/renderedAttributes.ts index db2528a..76a5a1a 100644 --- a/src/utils/renderedAttributes.ts +++ b/src/utils/renderedAttributes.ts @@ -5,7 +5,8 @@ */ import { CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE, CodamaError } from '@codama/errors'; -import { decimalString, integerString, isNode, type Node, type NodeKind } from '@codama/nodes'; +import type { Node, NodeKind } from '@codama/nodes'; +import { decimalString, integerString, isNode } from '@codama/nodes'; import type { NodePath } from '@codama/visitors-core'; import { EXTRA_ARGUMENT_PLUGIN } from './instructionInputs'; diff --git a/src/visitors/getRenderMapVisitor.ts b/src/visitors/getRenderMapVisitor.ts index a085c35..85336bf 100644 --- a/src/visitors/getRenderMapVisitor.ts +++ b/src/visitors/getRenderMapVisitor.ts @@ -2,13 +2,17 @@ import { CODAMA_ERROR__VERSION_MISMATCH, CodamaError } from '@codama/errors'; import { createRenderMap, mergeRenderMaps, RenderMap } from '@codama/fragments'; import { camelCase } from '@codama/fragments/casing'; import { + AccountNode, CODAMA_VERSION, + definedTypeNode, + DefinedTypeNode, getAllAccounts, getAllDefinedTypes, getAllEvents, getAllPdas, getAllPrograms, getCodamaVersionMajor, + InstructionNode, isNode, } from '@codama/nodes'; import { @@ -42,18 +46,20 @@ import { DEFAULT_KIT_IMPORT_STRATEGY, DEFAULT_NAME_TRANSFORMERS, Fragment, - getDefinedTypeNodesToExtract, + getCustomDataOptions, getImportFromFactory, getImportPathFactory, + getInstructionDataNode, getIsInternalNodeFactory, getNameApi, getPageFragment, getRenderedInstructions, - getResolvedInstructionInputs, GetRenderMapOptions, + getResolvedInstructionInputs, isArchivedInstruction, isRenderedInstruction, parseCustomDataOptions, + ParsedCustomDataOptions, RenderScope, } from '../utils'; import { getTypeManifestVisitor } from './getTypeManifestVisitor'; @@ -85,7 +91,7 @@ export function getRenderMapVisitor( const getImportPath = getImportPathFactory(options.importExtension); const isInternalNode = getIsInternalNodeFactory(options.internalNodes ?? []); const nameApi = getNameApi({ ...DEFAULT_NAME_TRANSFORMERS, ...options.nameTransformers }); - const renderScopeWithTypeManifestVisitor: Omit = { + const renderScopeWithoutTypeManifestVisitor: Omit = { asyncResolvers: (options.asyncResolvers ?? []).map(camelCase), customAccountData, customInstructionData, @@ -106,8 +112,8 @@ export function getRenderMapVisitor( renderParentInstructions: options.renderParentInstructions ?? false, }; - const typeManifestVisitor = getTypeManifestVisitor({ ...renderScopeWithTypeManifestVisitor, stack }); - const renderScope: RenderScope = { ...renderScopeWithTypeManifestVisitor, typeManifestVisitor }; + const typeManifestVisitor = getTypeManifestVisitor({ ...renderScopeWithoutTypeManifestVisitor, stack }); + const renderScope: RenderScope = { ...renderScopeWithoutTypeManifestVisitor, typeManifestVisitor }; const isNotInternal = (node: { identifier: string }) => !isInternalNode(node.identifier); const byteSizeVisitor = getByteSizeVisitor(linkables, { stack }); @@ -320,3 +326,32 @@ export function getRenderMapVisitor( }), ); } + +/** + * The defined types to render for the custom data of accounts or instructions configured with + * `extract: true`, holding the data they would have generated. + * + * @param nodes - The accounts or instructions, e.g. the ones rendered as pages. + * @param parsedCustomDataOptions - The parsed custom data options. + * @return The defined types to render. + */ +function getDefinedTypeNodesToExtract( + nodes: AccountNode[] | InstructionNode[], + parsedCustomDataOptions: ParsedCustomDataOptions, +): DefinedTypeNode[] { + return nodes.flatMap(node => { + const options = getCustomDataOptions(parsedCustomDataOptions, node); + if (!options || !options.extract) return []; + + if (isNode(node, 'accountNode')) { + return [definedTypeNode({ identifier: options.extractAs, type: { ...node.data } })]; + } + + return [ + definedTypeNode({ + identifier: options.extractAs, + type: getInstructionDataNode(node), + }), + ]; + }); +} diff --git a/test/_setup.ts b/test/_setup.ts index 242f7c7..2269ac9 100644 --- a/test/_setup.ts +++ b/test/_setup.ts @@ -1,3 +1,4 @@ +import { CodamaError, CodamaErrorCode, isCodamaError } from '@codama/errors'; import { getFromRenderMap, RenderMap } from '@codama/fragments'; import { LinkableDictionary } from '@codama/visitors-core'; import { Plugin } from 'prettier'; @@ -257,3 +258,14 @@ async function inlineCode(code: string) { function escapeRegex(stringAsRegex: string) { return stringAsRegex.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); } + +/** The Codama error thrown by the given function, failing if it does not throw one with that code. */ +export function getCodamaError(code: TCode, fn: () => unknown): CodamaError { + try { + fn(); + } catch (error) { + if (isCodamaError(error, code)) return error; + throw error; + } + throw new Error(`Expected a Codama error with code ${code} to be thrown.`); +} diff --git a/test/accountsPage.test.ts b/test/accountsPage.test.ts index c048714..f1db3a6 100644 --- a/test/accountsPage.test.ts +++ b/test/accountsPage.test.ts @@ -268,8 +268,8 @@ test('it can extracts account data and import it from another source', async () // And we expect the existing account data to be extracted into a new type // so it can be imported from the hooked directory. await renderMapContains(renderMap, 'types/counter-account-data.ts', [ - 'export type CounterAccountData', - 'export type CounterAccountDataArgs', + 'export type CounterAccountData = { value: number };', + 'export type CounterAccountDataArgs = CounterAccountData;', 'export function getCounterAccountDataEncoder', 'export function getCounterAccountDataDecoder', 'export function getCounterAccountDataCodec', diff --git a/test/constantsPage.test.ts b/test/constantsPage.test.ts index aa9a015..233c1a4 100644 --- a/test/constantsPage.test.ts +++ b/test/constantsPage.test.ts @@ -52,7 +52,6 @@ test('it renders program constants in a program-specific constants page', async await renderMapContains(renderMap, 'constants/index.ts', "export * from './governance';"); expect(renderMap.has('constants.ts')).toBe(false); - expect(renderMap.size).toBeGreaterThan(0); }); test('it renders one constants file per program', async () => { diff --git a/test/e2e/instructions/idl.json b/test/e2e/instructions/idl.json index 00b65cb..65d93ab 100644 --- a/test/e2e/instructions/idl.json +++ b/test/e2e/instructions/idl.json @@ -5,7 +5,7 @@ "program": { "kind": "programNode", "identifier": "instructions", - "publicKey": "Instructions1111111111111111111111111111111", + "publicKey": "86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P", "version": "1.0.0", "accounts": [ { @@ -858,6 +858,88 @@ } ] }, + { + "kind": "instructionNode", + "identifier": "linkVault", + "optionalAccountStrategy": "programId", + "accounts": [ + { + "kind": "instructionAccountNode", + "identifier": "owner", + "isWritable": false, + "isSigner": true, + "isOptional": false + }, + { + "kind": "instructionAccountNode", + "identifier": "vault", + "isWritable": true, + "isSigner": false, + "isOptional": false + } + ], + "data": { + "kind": "structTypeNode", + "fields": [ + { + "kind": "structFieldTypeNode", + "identifier": "discriminator", + "defaultValueStrategy": "omitted", + "type": { + "kind": "integerTypeNode", + "format": "u8", + "endian": "le" + }, + "defaultValue": { + "kind": "integerValueNode", + "value": "17" + } + }, + { + "kind": "structFieldTypeNode", + "identifier": "vault", + "defaultValueStrategy": "omitted", + "type": { + "kind": "publicKeyTypeNode" + }, + "defaultValue": { + "kind": "injectedValueNode", + "key": "vault" + } + } + ] + }, + "discriminators": [ + { + "kind": "fieldDiscriminatorNode", + "path": "discriminator", + "offset": 0 + } + ], + "provides": [ + { + "kind": "providedNode", + "identifier": "vault", + "node": { + "kind": "pdaValueNode", + "pda": { + "kind": "pdaLinkNode", + "identifier": "secretCounter" + }, + "seeds": [ + { + "kind": "pdaSeedValueNode", + "identifier": "owner", + "value": { + "kind": "accountValueNode", + "identifier": "owner" + } + } + ] + } + } + ] + }, { "kind": "instructionNode", "identifier": "configure", @@ -1157,7 +1239,7 @@ { "kind": "pdaNode", "identifier": "settings", - "programId": "Instructions1111111111111111111111111111111", + "programId": "86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P", "seeds": [ { "kind": "constantPdaSeedNode", diff --git a/test/e2e/instructions/src/generated/instructions/index.ts b/test/e2e/instructions/src/generated/instructions/index.ts index c89a43a..34b4a2d 100644 --- a/test/e2e/instructions/src/generated/instructions/index.ts +++ b/test/e2e/instructions/src/generated/instructions/index.ts @@ -14,6 +14,7 @@ export * from './configure'; export * from './contextual-data'; export * from './get-balance'; export * from './get-stats'; +export * from './link-vault'; export * from './new-transfer'; export * from './old-transfer'; export * from './resolved-extras'; diff --git a/test/e2e/instructions/src/generated/instructions/link-vault.ts b/test/e2e/instructions/src/generated/instructions/link-vault.ts new file mode 100644 index 0000000..7368d6e --- /dev/null +++ b/test/e2e/instructions/src/generated/instructions/link-vault.ts @@ -0,0 +1,241 @@ +/** + * This code was AUTOGENERATED using the Codama library. + * Please DO NOT EDIT THIS FILE, instead use visitors + * to add features, then rerun Codama to update it. + * + * @see https://github.com/codama-idl/codama + */ + +import { + combineCodec, + getAddressDecoder, + getAddressEncoder, + getStructDecoder, + getStructEncoder, + getU8Decoder, + getU8Encoder, + SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, + SolanaError, + transformEncoder, + type AccountMeta, + type AccountSignerMeta, + type Address, + type FixedSizeCodec, + type FixedSizeDecoder, + type FixedSizeEncoder, + type HasAddress, + type Instruction, + type InstructionWithAccounts, + type InstructionWithData, + type ReadonlySignerAccount, + type ReadonlyUint8Array, + type WritableAccount, +} from '@solana/kit'; +import { + getAccountMetaFactory, + getAddressFromResolvedInstructionAccount, + type InstructionAccountInput, + type InstructionAccountInputAddress, + type InstructionSignerInput, + type ResolvedInstructionAccount, + type ResolvedInstructionAccountMeta, +} from '@solana/kit/program-client-core'; +import { findSecretCounterPda } from '../pdas/secret-counter'; +import { INSTRUCTIONS_PROGRAM_ADDRESS } from '../programs'; + +export const LINK_VAULT_DISCRIMINATOR = 17; + +export function getLinkVaultDiscriminatorBytes(): ReadonlyUint8Array { + return getU8Encoder().encode(LINK_VAULT_DISCRIMINATOR); +} + +export type LinkVaultInstruction< + TProgram extends string = typeof INSTRUCTIONS_PROGRAM_ADDRESS, + TAccountOwner extends string | AccountMeta = string, + TAccountVault extends string | AccountMeta = string, + TRemainingAccounts extends readonly AccountMeta[] = [], +> = Instruction & + InstructionWithData & + InstructionWithAccounts< + [ + TAccountOwner extends string + ? ReadonlySignerAccount & AccountSignerMeta + : TAccountOwner, + TAccountVault extends string ? WritableAccount : TAccountVault, + ...TRemainingAccounts, + ] + >; + +export type LinkVaultInstructionData = { discriminator: number; vault: Address }; + +export type LinkVaultInstructionDataArgs = { vault: Address | HasAddress }; + +export function getLinkVaultInstructionDataEncoder(): FixedSizeEncoder { + return transformEncoder( + getStructEncoder([ + ['discriminator', getU8Encoder()], + ['vault', getAddressEncoder()], + ]), + value => ({ ...value, discriminator: LINK_VAULT_DISCRIMINATOR }), + ); +} + +export function getLinkVaultInstructionDataDecoder(): FixedSizeDecoder { + return getStructDecoder([ + ['discriminator', getU8Decoder()], + ['vault', getAddressDecoder()], + ]); +} + +export function getLinkVaultInstructionDataCodec(): FixedSizeCodec< + LinkVaultInstructionDataArgs, + LinkVaultInstructionData +> { + return combineCodec(getLinkVaultInstructionDataEncoder(), getLinkVaultInstructionDataDecoder()); +} + +export type LinkVaultAsyncInput< + TAccountOwner extends InstructionSignerInput = InstructionSignerInput, + TAccountVault extends InstructionAccountInput = InstructionAccountInput, +> = { + owner: TAccountOwner; + vault: TAccountVault; +}; + +export async function getLinkVaultInstructionAsync< + TAccountOwner extends InstructionSignerInput, + TAccountVault extends InstructionAccountInput, + TProgramAddress extends Address = typeof INSTRUCTIONS_PROGRAM_ADDRESS, +>( + input: LinkVaultAsyncInput, + config?: { programAddress?: TProgramAddress | { readonly address: TProgramAddress } }, +): Promise< + LinkVaultInstruction< + TProgramAddress, + ResolvedInstructionAccountMeta>, + ResolvedInstructionAccountMeta> + > +> { + // Program address. + const programAddressInput = config?.programAddress ?? INSTRUCTIONS_PROGRAM_ADDRESS; + const programAddress = typeof programAddressInput === 'string' ? programAddressInput : programAddressInput.address; + + // Account meta helper. + const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + + // Original accounts. + const originalAccounts = { + owner: { value: input.owner ?? null, isSigner: true, isWritable: false }, + vault: { value: input.vault ?? null, isSigner: false, isWritable: true }, + }; + const accounts = originalAccounts as Record; + + // Original args. + const { vault: _vault, ...originalArgs } = { ...input }; + const args: typeof originalArgs & { vault?: Address | HasAddress } = originalArgs; + + // Resolve default values. + if (args.vault === undefined) { + args.vault = ( + await findSecretCounterPda( + { owner: getAddressFromResolvedInstructionAccount('owner', accounts.owner.value) }, + { programAddress }, + ) + )[0]; + } + + return Object.freeze({ + accounts: [getAccountMeta('owner', accounts.owner), getAccountMeta('vault', accounts.vault)], + data: getLinkVaultInstructionDataEncoder().encode(args as LinkVaultInstructionDataArgs), + programAddress, + } as LinkVaultInstruction< + TProgramAddress, + ResolvedInstructionAccountMeta>, + ResolvedInstructionAccountMeta> + >); +} + +export type LinkVaultInput< + TAccountOwner extends InstructionSignerInput = InstructionSignerInput, + TAccountVault extends InstructionAccountInput = InstructionAccountInput, +> = { + owner: TAccountOwner; + vault: TAccountVault; + vaultArg: LinkVaultInstructionDataArgs['vault']; +}; + +export function getLinkVaultInstruction< + TAccountOwner extends InstructionSignerInput, + TAccountVault extends InstructionAccountInput, + TProgramAddress extends Address = typeof INSTRUCTIONS_PROGRAM_ADDRESS, +>( + input: LinkVaultInput, + config?: { programAddress?: TProgramAddress | { readonly address: TProgramAddress } }, +): LinkVaultInstruction< + TProgramAddress, + ResolvedInstructionAccountMeta>, + ResolvedInstructionAccountMeta> +> { + // Program address. + const programAddressInput = config?.programAddress ?? INSTRUCTIONS_PROGRAM_ADDRESS; + const programAddress = typeof programAddressInput === 'string' ? programAddressInput : programAddressInput.address; + + // Account meta helper. + const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + + // Original accounts. + const originalAccounts = { + owner: { value: input.owner ?? null, isSigner: true, isWritable: false }, + vault: { value: input.vault ?? null, isSigner: false, isWritable: true }, + }; + const accounts = originalAccounts as Record; + + // Original args. + const args = { ...input, vault: input.vaultArg }; + + return Object.freeze({ + accounts: [getAccountMeta('owner', accounts.owner), getAccountMeta('vault', accounts.vault)], + data: getLinkVaultInstructionDataEncoder().encode(args as LinkVaultInstructionDataArgs), + programAddress, + } as LinkVaultInstruction< + TProgramAddress, + ResolvedInstructionAccountMeta>, + ResolvedInstructionAccountMeta> + >); +} + +export type ParsedLinkVaultInstruction< + TProgram extends string = typeof INSTRUCTIONS_PROGRAM_ADDRESS, + TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[], +> = { + programAddress: Address; + accounts: { + owner: TAccountMetas[0]; + vault: TAccountMetas[1]; + }; + data: LinkVaultInstructionData; +}; + +export function parseLinkVaultInstruction( + instruction: Instruction & + InstructionWithAccounts & + InstructionWithData, +): ParsedLinkVaultInstruction { + if (instruction.accounts.length < 2) { + throw new SolanaError(SOLANA_ERROR__PROGRAM_CLIENTS__INSUFFICIENT_ACCOUNT_METAS, { + actualAccountMetas: instruction.accounts.length, + expectedAccountMetas: 2, + }); + } + let accountIndex = 0; + const getNextAccount = () => { + const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!; + accountIndex += 1; + return accountMeta; + }; + return { + programAddress: instruction.programAddress, + accounts: { owner: getNextAccount(), vault: getNextAccount() }, + data: getLinkVaultInstructionDataDecoder().decode(instruction.data), + }; +} diff --git a/test/e2e/instructions/src/generated/pdas/secret-counter.ts b/test/e2e/instructions/src/generated/pdas/secret-counter.ts index 6744b34..1cd5389 100644 --- a/test/e2e/instructions/src/generated/pdas/secret-counter.ts +++ b/test/e2e/instructions/src/generated/pdas/secret-counter.ts @@ -24,7 +24,7 @@ export async function findSecretCounterPda( ): Promise { const { programAddress: - programAddressInput = 'Instructions1111111111111111111111111111111' as Address<'Instructions1111111111111111111111111111111'>, + programAddressInput = '86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P' as Address<'86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P'>, } = config; const programAddress = typeof programAddressInput === 'string' ? programAddressInput : programAddressInput.address; return await getProgramDerivedAddress({ programAddress, seeds: [getAddressEncoder().encode(seeds.owner)] }); diff --git a/test/e2e/instructions/src/generated/pdas/settings.ts b/test/e2e/instructions/src/generated/pdas/settings.ts index 5bf44f7..95ad466 100644 --- a/test/e2e/instructions/src/generated/pdas/settings.ts +++ b/test/e2e/instructions/src/generated/pdas/settings.ts @@ -19,7 +19,7 @@ export async function findSettingsPda( ): Promise { const { programAddress: - programAddressInput = 'Instructions1111111111111111111111111111111' as Address<'Instructions1111111111111111111111111111111'>, + programAddressInput = '86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P' as Address<'86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P'>, } = config; const programAddress = typeof programAddressInput === 'string' ? programAddressInput : programAddressInput.address; return await getProgramDerivedAddress({ programAddress, seeds: [getUtf8Encoder().encode('settings')] }); diff --git a/test/e2e/instructions/src/generated/programs/instructions.ts b/test/e2e/instructions/src/generated/programs/instructions.ts index 86bd988..6a65230 100644 --- a/test/e2e/instructions/src/generated/programs/instructions.ts +++ b/test/e2e/instructions/src/generated/programs/instructions.ts @@ -43,6 +43,7 @@ import { getContextualDataInstruction, getGetBalanceInstruction, getGetStatsInstruction, + getLinkVaultInstructionAsync, getNewTransferInstruction, getOldTransferInstruction, getResolvedExtrasInstruction, @@ -58,6 +59,7 @@ import { parseContextualDataInstruction, parseGetBalanceInstruction, parseGetStatsInstruction, + parseLinkVaultInstruction, parseNewTransferInstruction, parseOldTransferInstruction, parseResolvedExtrasInstruction, @@ -73,6 +75,7 @@ import { type ContextualDataInput, type GetBalanceInput, type GetStatsInput, + type LinkVaultAsyncInput, type NewTransferInput, type OldTransferInput, type ParsedAllOmittedInstruction, @@ -83,6 +86,7 @@ import { type ParsedContextualDataInstruction, type ParsedGetBalanceInstruction, type ParsedGetStatsInstruction, + type ParsedLinkVaultInstruction, type ParsedNewTransferInstruction, type ParsedOldTransferInstruction, type ParsedResolvedExtrasInstruction, @@ -100,7 +104,7 @@ import { parseSecretResetInstruction, type ParsedSecretResetInstruction } from ' import { findSettingsPda } from '../pdas'; export const INSTRUCTIONS_PROGRAM_ADDRESS = - 'Instructions1111111111111111111111111111111' as Address<'Instructions1111111111111111111111111111111'>; + '86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P' as Address<'86ZVX2iJXaMkKSJHacQcH2dJ9kGMudi1iZovGpPS9y2P'>; export enum InstructionsAccount { Counter, @@ -120,6 +124,7 @@ export enum InstructionsInstruction { SyncLimits, ClaimOwnership, SetDelegate, + LinkVault, Configure, UseSecret, SecretReset, @@ -166,6 +171,9 @@ export function identifyInstructionsInstruction( if (containsBytes(data, getU8Encoder().encode(15), 0)) { return InstructionsInstruction.SetDelegate; } + if (containsBytes(data, getU8Encoder().encode(17), 0)) { + return InstructionsInstruction.LinkVault; + } if (containsBytes(data, getU8Encoder().encode(16), 0)) { return InstructionsInstruction.Configure; } @@ -184,7 +192,7 @@ export function identifyInstructionsInstruction( }); } -export type ParsedInstructionsInstruction = +export type ParsedInstructionsInstruction = | ({ instructionType: InstructionsInstruction.AllOmitted } & ParsedAllOmittedInstruction) | ({ instructionType: InstructionsInstruction.SomeOmitted } & ParsedSomeOmittedInstruction) | ({ instructionType: InstructionsInstruction.ResolvedExtras } & ParsedResolvedExtrasInstruction) @@ -197,6 +205,7 @@ export type ParsedInstructionsInstruction, config?: { programAddress?: Address | HasAddress }, ) => ReturnType & SelfPlanAndSendFunctions; + linkVault: ( + input: LinkVaultAsyncInput, + config?: { programAddress?: Address | HasAddress }, + ) => ReturnType & SelfPlanAndSendFunctions; configure: ( input: ConfigureAsyncInput, config?: { programAddress?: Address | HasAddress }, @@ -479,6 +496,13 @@ export function instructionsProgram(config: { programAddress?: Address | HasAddr { programAddress: instructionConfig?.programAddress ?? config.programAddress }, ), ), + linkVault: (input, instructionConfig) => + addSelfPlanAndSendFunctions( + client, + getLinkVaultInstructionAsync(input, { + programAddress: instructionConfig?.programAddress ?? config.programAddress, + }), + ), configure: (input, instructionConfig) => addSelfPlanAndSendFunctions( client, diff --git a/test/e2e/instructions/test/instructions.test.ts b/test/e2e/instructions/test/instructions.test.ts index 5fd5d8e..0e56fc9 100644 --- a/test/e2e/instructions/test/instructions.test.ts +++ b/test/e2e/instructions/test/instructions.test.ts @@ -1,6 +1,7 @@ import { address, BASE_ACCOUNT_SIZE, createNoopSigner } from '@solana/kit'; import { expect, test } from 'vitest'; +import { findSecretCounterPda } from '../src/generated/pdas/secret-counter.js'; import { findSettingsPda, getAllOmittedInstruction, @@ -15,6 +16,8 @@ import { getGetBalanceInstructionReturnDataEncoder, getGetStatsInstructionReturnDataDecoder, getInstructionsErrorMessage, + getLinkVaultInstructionAsync, + getLinkVaultInstructionDataDecoder, getResolvedExtrasInstruction, getSetDelegateInstruction, getSetDelegateInstructionDataDecoder, @@ -141,3 +144,17 @@ test('it derives pinned PDAs from the program address and picks conditional defa expect(strict.accounts[2].address).toBe(owner); expect(relaxed.accounts[2].address).toBe(settings); }); + +test('it fills in omitted data fields named like an account from their PDA', async () => { + // Given a signer and the vault account. + const ownerSigner = createNoopSigner(owner); + const vault = address('Vau1t11111111111111111111111111111111111111'); + + // When we build the instruction without the `vault` data field, which is omitted from the input. + const instruction = await getLinkVaultInstructionAsync({ owner: ownerSigner, vault }); + + // Then the data field holds the address of the PDA, not the vault account given as input. + const [expected] = await findSecretCounterPda({ owner }); + expect(getLinkVaultInstructionDataDecoder().decode(instruction.data).vault).toBe(expected); + expect(instruction.accounts[1].address).toBe(vault); +}); diff --git a/test/eventsPage.test.ts b/test/eventsPage.test.ts index beca2a6..3546d01 100644 --- a/test/eventsPage.test.ts +++ b/test/eventsPage.test.ts @@ -315,7 +315,7 @@ test('it applies custom name transformations to the event APIs', async () => { await renderMapContains(renderMap, 'events/renamed.ts', [ 'export const RENAMED_PAYLOAD_DISCRIMINATOR', 'export function bytesRenamedPayloadDiscriminator(): ReadonlyUint8Array', - 'export type RenamedPayload', + 'export type RenamedPayload = {', 'export function read_renamed(', ]); }); diff --git a/test/fragments/programPlugin.test.ts b/test/fragments/programPlugin.test.ts index 00bb130..cd385a4 100644 --- a/test/fragments/programPlugin.test.ts +++ b/test/fragments/programPlugin.test.ts @@ -456,10 +456,7 @@ test('it renders a plugin with only PDAs', async () => { // When we get the program plugin fragment. const fragment = getProgramPluginFragment({ ...getDefaultScope(), programNode: node, programPath: [node] }); - // Then we expect the fragment to be defined. - expect(fragment).toBeDefined(); - - // And we expect the plugin type to have only the pdas field. + // Then we expect the plugin type to have only the pdas field. await fragmentContains(fragment, ['export type SplTokenPlugin = { pdas: SplTokenPluginPdas }']); await fragmentContains(fragment, [ 'export type SplTokenPluginPdas = { associatedTokenAccount: typeof findAssociatedTokenAccountPda; }', diff --git a/test/instructionsPage.test.ts b/test/instructionsPage.test.ts index 0f9caee..114b1b7 100644 --- a/test/instructionsPage.test.ts +++ b/test/instructionsPage.test.ts @@ -4,8 +4,6 @@ import { CODAMA_ERROR__RENDERERS__UNSUPPORTED_NODE, CODAMA_ERROR__VISITORS__INVALID_PDA_SEED_VALUES, CodamaError, - type CodamaErrorCode, - isCodamaError, } from '@codama/errors'; import { getFromRenderMap } from '@codama/fragments'; import { @@ -17,6 +15,7 @@ import { booleanTypeNode, booleanValueNode, conditionalValueNode, + type ConditionalValueNode, constantDiscriminatorNode, constantPdaSeedNodeFromString, constantValueNode, @@ -67,6 +66,7 @@ import { getResolvedInstructionInputs } from '../src/utils'; import { codeContains, codeDoesNotContain, + getCodamaError, renderMapContains, renderMapContainsImports, renderMapDoesNotContain, @@ -491,9 +491,9 @@ test('it renders instruction arguments with linked PDA default values that forwa // When we render it. const renderMap = visit(node, getRenderMapVisitor()); - // Then we expect the argument default to use the program address of the instruction. + // Then the argument defaults to the address of the PDA derived from the program address of the instruction. await renderMapContains(renderMap, 'instructions/increment.ts', [ - 'if (args.counterAddress === undefined) { args.counterAddress = await findCounterPda({ programAddress }); }', + 'if (args.counterAddress === undefined) { args.counterAddress = (await findCounterPda({ programAddress }))[0]; }', ]); }); @@ -562,6 +562,45 @@ test('it forwards the program address to PDAs pinned to the address of their own ]); }); +test('it renders instruction arguments with inlined PDA default values as addresses', async () => { + // Given an instruction argument defaulting to an inlined PDA. + const node = programNode({ + identifier: 'counter', + instructions: [ + instructionNode({ + data: structTypeNode([ + structFieldTypeNode({ + defaultValue: injectedValueNode({ key: 'counterAddress' }), + identifier: 'counterAddress', + type: publicKeyTypeNode(), + }), + ]), + identifier: 'increment', + provides: [ + providedNode( + 'counterAddress', + pdaValueNode( + pdaNode({ + identifier: 'counter', + seeds: [constantPdaSeedNodeFromString('utf8', 'counter')], + }), + ), + ), + ], + }), + ], + publicKey: '1111', + }); + + // When we render it. + const renderMap = visit(node, getRenderMapVisitor()); + + // Then the argument holds the address of the PDA rather than the address and bump pair. + await renderMapContains(renderMap, 'instructions/increment.ts', [ + "args.counterAddress = ( await getProgramDerivedAddress({ programAddress, seeds: [getUtf8Encoder().encode('counter')] }) )[0];", + ]); +}); + test('it renders instruction accounts with inlined PDAs as default value', async () => { // Given the following instruction with an inlined PDA default value. const node = programNode({ @@ -1509,17 +1548,6 @@ test('it fails on nested data paths that do not exist', () => { expect(error.context.pathString).toBe('mint.typo'); }); -/** The Codama error thrown by the given function, failing if it does not throw one with that code. */ -function getCodamaError(code: TCode, fn: () => unknown) { - try { - fn(); - } catch (error) { - if (isCodamaError(error, code)) return error; - throw error; - } - throw new Error(`Expected a Codama error with code ${code} to be thrown.`); -} - test('it fails on inline PDA defaults missing a seed value', () => { // Given an account defaulting to an inline PDA without a value for its variable seed. const node = programNode({ @@ -1836,6 +1864,18 @@ test('it renders parents whose sub-instructions are all archived as leaves', () expect(renderMap.has('instructions/transfer-v1.ts')).toBe(false); }); +/** A `transfer` instruction whose `target` account defaults to the given conditional value. */ +function transferWithConditionalTarget(defaultValue: ConditionalValueNode) { + return instructionNode({ + accounts: [ + instructionAccountNode({ identifier: 'authority', isSigner: 'either', isWritable: false }), + instructionAccountNode({ identifier: 'fallback', isSigner: false, isWritable: false }), + instructionAccountNode({ defaultValue, identifier: 'target', isSigner: false, isWritable: false }), + ], + identifier: 'transfer', + }); +} + test('it compares integer conditions of default values as bigints', async () => { // Given an account defaulting to another one when a u64 argument equals 5. const node = programNode({ @@ -1876,7 +1916,7 @@ test('it compares account conditions of default values by address', async () => const node = programNode({ identifier: 'myProgram', instructions: [ - instructionInputAccounts( + transferWithConditionalTarget( conditionalValueNode({ condition: accountValueNode('authority'), ifTrue: accountValueNode('fallback'), @@ -1906,7 +1946,7 @@ test('it fails on conditions of default values that cannot be compared', () => { }); const node = programNode({ identifier: 'myProgram', - instructions: [instructionInputAccounts(conditional)], + instructions: [transferWithConditionalTarget(conditional)], publicKey: '1111', }); @@ -1915,18 +1955,6 @@ test('it fails on conditions of default values that cannot be compared', () => { expect(error.context.path.at(-1)).toBe(conditional); }); -/** A `transfer` instruction whose `target` account defaults to the given conditional value. */ -function instructionInputAccounts(defaultValue: ReturnType) { - return instructionNode({ - accounts: [ - instructionAccountNode({ identifier: 'authority', isSigner: 'either', isWritable: false }), - instructionAccountNode({ identifier: 'fallback', isSigner: false, isWritable: false }), - instructionAccountNode({ defaultValue, identifier: 'target', isSigner: false, isWritable: false }), - ], - identifier: 'transfer', - }); -} - test('it compares scalar enum conditions of default values as native enum members', async () => { // Given an account defaulting to another one when a scalar enum argument holds a given variant. const node = programNode({ @@ -2112,3 +2140,42 @@ test('it requires omitted data fields defaulting to the payer in instruction bui ]); await renderMapDoesNotContain(renderMap, 'instructions/claim.ts', ['owner?:']); }); + +test('it renames arguments named like an account in the builder whose input includes them only', async () => { + // Given an omitted `vault` data field, filled in from a PDA asynchronously, next to a `vault` account. + const node = programNode({ + identifier: 'myProgram', + instructions: [ + instructionNode({ + accounts: [instructionAccountNode({ identifier: 'vault', isSigner: false, isWritable: true })], + data: structTypeNode([ + structFieldTypeNode({ + defaultValue: injectedValueNode({ key: 'vault' }), + defaultValueStrategy: 'omitted', + identifier: 'vault', + type: publicKeyTypeNode(), + }), + ]), + identifier: 'transfer', + provides: [providedNode('vault', pdaValueNode('vault'))], + }), + ], + pdas: [pdaNode({ identifier: 'vault', seeds: [] })], + publicKey: '1111', + }); + + // When we render it. + const renderMap = visit(node, getRenderMapVisitor()); + const [asyncFunction, syncFunction] = (renderMap.get('instructions/transfer.ts')?.content ?? '').split( + 'export type TransferInput<', + ); + + // Then the synchronous builder, which requires the field, renames it, whilst the asynchronous + // builder, which fills it in, leaves its input alone and keeps the account out of the args. + await codeContains(syncFunction, ['vaultArg: TransferInstructionDataArgs["vault"];', 'vault: input.vaultArg']); + await codeDoesNotContain(asyncFunction, ['vaultArg']); + await codeContains(asyncFunction, [ + 'const { vault: _vault, ...originalArgs } = { ...input };', + 'args.vault = (await findVaultPda({ programAddress }))[0];', + ]); +}); diff --git a/test/links/pda.test.ts b/test/links/pda.test.ts index e863cc4..588262b 100644 --- a/test/links/pda.test.ts +++ b/test/links/pda.test.ts @@ -45,7 +45,7 @@ test('it imports functions from the linked pda', async () => { }); }); -test('it can override the import of a linked account', async () => { +test('it can override the import of a linked PDA', async () => { // Given the following node. const node = programNode({ identifier: 'myProgram', diff --git a/test/links/program.test.ts b/test/links/program.test.ts index c4c2c68..f9990e2 100644 --- a/test/links/program.test.ts +++ b/test/links/program.test.ts @@ -48,7 +48,7 @@ test('it imports constants from the linked program', async () => { }); }); -test('it can override the import of a linked account', async () => { +test('it can override the import of a linked program', async () => { // Given the following node. const node = rootNode( programNode({ diff --git a/test/utils/importMap.test.ts b/test/utils/importMap.test.ts index e0cedac..1114822 100644 --- a/test/utils/importMap.test.ts +++ b/test/utils/importMap.test.ts @@ -244,7 +244,7 @@ describe('addToImportMap', () => { }); describe('removeFromImportMap', () => { - test('it removes type-only imports from an existing import map', () => { + test('it removes imports from an existing import map', () => { const importMap = addToImportMap(createImportMap(), 'module-a', ['import1', 'type import2']); expect(removeFromImportMap(importMap, 'module-a', ['import1'])).toStrictEqual( new Map([['module-a', new Map([['import2', parseImportInput('type import2')]])]]), diff --git a/test/utils/instructionInputs.test.ts b/test/utils/instructionInputs.test.ts index 391ada1..4672386 100644 --- a/test/utils/instructionInputs.test.ts +++ b/test/utils/instructionInputs.test.ts @@ -4,8 +4,6 @@ import { CODAMA_ERROR__VISITORS__CANNOT_USE_OPTIONAL_ACCOUNT_AS_PDA_SEED_VALUE, CODAMA_ERROR__VISITORS__CYCLIC_DEPENDENCY_DETECTED_WHEN_RESOLVING_INSTRUCTION_DEFAULT_VALUES, CODAMA_ERROR__VISITORS__INVALID_INSTRUCTION_DEFAULT_VALUE_DEPENDENCY, - type CodamaErrorCode, - isCodamaError, } from '@codama/errors'; import { accountBumpValueNode, @@ -55,6 +53,7 @@ import { isInstructionResolver, isRemainingAccountsBackedByArgument, } from '../../src/utils'; +import { getCodamaError } from '../_setup'; const amount = structFieldTypeNode({ identifier: 'amount', type: integerTypeNode('u64') }); const useAta = { identifier: 'useAta', type: integerTypeNode('u8') }; @@ -70,7 +69,7 @@ test('it exposes the data fields and extra arguments of an instruction', () => { expect(getInstructionDataFields(instruction)).toStrictEqual([amount]); expect(getInstructionExtraArguments(instruction)).toStrictEqual([useAta]); expect(getAllInstructionDataFields(instruction)).toStrictEqual([amount, useAta]); - expect(hasInstructionData(instruction)).toBe(true); + expect(hasInstructionData(instruction, new Map())).toBe(true); expect(getInstructionDataNode(instruction)).toStrictEqual(structTypeNode([amount])); expect(getInstructionExtraArgumentsNode(instruction)).toStrictEqual(structTypeNode([structFieldTypeNode(useAta)])); }); @@ -78,7 +77,7 @@ test('it exposes the data fields and extra arguments of an instruction', () => { test('it reports instructions without data', () => { const instruction = instructionNode({ identifier: 'noop', plugins: [useAtaPlugin] }); - expect(hasInstructionData(instruction)).toBe(false); + expect(hasInstructionData(instruction, new Map())).toBe(false); expect(getInstructionDataNode(instruction)).toStrictEqual(structTypeNode([])); }); @@ -86,7 +85,7 @@ test('it exposes instruction data linked to a defined type', () => { const data = definedTypeLinkNode('transferArgs'); const instruction = instructionNode({ data, identifier: 'transfer' }); - expect(hasInstructionData(instruction)).toBe(true); + expect(hasInstructionData(instruction, new Map())).toBe(true); expect(getInstructionDataNode(instruction)).toBe(data); expect(getInstructionDataFields(instruction)).toStrictEqual([]); }); @@ -206,17 +205,6 @@ function resolve( return getResolvedInstructionInputs(path, getLinkablesFromNode(root)); } -/** The Codama error thrown by the given function, failing if it does not throw one with that code. */ -function getCodamaError(code: TCode, fn: () => unknown) { - try { - fn(); - } catch (error) { - if (isCodamaError(error, code)) return error; - throw error; - } - throw new Error(`Expected a Codama error with code ${code} to be thrown.`); -} - const account = (identifier: string, options: Partial[0]> = {}) => instructionAccountNode({ identifier, isSigner: false, isWritable: false, ...options }); const resolverPlugin = (name: string, dependsOn: string[] = []) => pluginNode('codama.resolver', { dependsOn, name });