From 253501aa898e6cac05a98b60225e32969f6f665c Mon Sep 17 00:00:00 2001 From: Jayden Park Date: Tue, 20 Feb 2024 06:59:48 +1100 Subject: [PATCH] ts: Correctly construct field layout for type aliases (#2821) --- CHANGELOG.md | 1 + ts/packages/anchor/src/coder/borsh/idl.ts | 5 +- .../anchor/tests/coder-instructions.spec.ts | 49 +++++++++++++++++++ 3 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 ts/packages/anchor/tests/coder-instructions.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fbedd5bd2d..ae3f3bab5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ The minor version will be incremented upon a breaking change and the patch versi - ts: Fix formatting enums ([#2763](https://github.com/coral-xyz/anchor/pull/2763)). - cli: Fix `migrate` command not working without global `ts-node` installation ([#2767](https://github.com/coral-xyz/anchor/pull/2767)). - client, lang, spl, syn: Enable all features for docs.rs build ([#2774](https://github.com/coral-xyz/anchor/pull/2774)). +- ts: Fix construction of field layouts for type aliased instruction arguments ([#2821](https://github.com/coral-xyz/anchor/pull/2821)) ### Breaking diff --git a/ts/packages/anchor/src/coder/borsh/idl.ts b/ts/packages/anchor/src/coder/borsh/idl.ts index 08d40d9bbe..2f33de082d 100644 --- a/ts/packages/anchor/src/coder/borsh/idl.ts +++ b/ts/packages/anchor/src/coder/borsh/idl.ts @@ -164,10 +164,7 @@ export class IdlCoder { } case "alias": { - return IdlCoder.fieldLayout( - { type: typeDef.type.value, name: typeDef.name }, - types - ); + return IdlCoder.fieldLayout({ type: typeDef.type.value, name }, types); } } } diff --git a/ts/packages/anchor/tests/coder-instructions.spec.ts b/ts/packages/anchor/tests/coder-instructions.spec.ts new file mode 100644 index 0000000000..a49bd13071 --- /dev/null +++ b/ts/packages/anchor/tests/coder-instructions.spec.ts @@ -0,0 +1,49 @@ +import * as assert from "assert"; +import { BorshCoder } from "../src"; +import { IdlType } from "../src/idl"; +import { toInstruction } from "../src/program/common"; + +describe("coder.instructions", () => { + test("Can encode and decode type aliased instruction arguments (byte array)", () => { + const idl = { + version: "0.1.0", + name: "test", + instructions: [ + { + name: "initialize", + accounts: [], + args: [ + { + name: "arg", + type: { + defined: "AliasTest", + }, + }, + ], + }, + ], + types: [ + { + name: "AliasTest", + type: { + kind: "alias" as const, + value: { + array: ["u8", 3] as [IdlType, number], + }, + }, + }, + ], + }; + + const idlIx = idl.instructions[0]; + const expected = [1, 2, 3]; + + const coder = new BorshCoder(idl); + const ix = toInstruction(idlIx, expected); + + const encoded = coder.instruction.encode(idlIx.name, ix); + const decoded = coder.instruction.decode(encoded, "hex", idlIx.name); + + assert.deepStrictEqual(decoded?.data[idlIx.args[0].name], expected); + }); +});