From e42670968f28b99a4ac250c1eca1702d64334e49 Mon Sep 17 00:00:00 2001 From: ngundotra Date: Thu, 29 Sep 2022 11:57:56 -0400 Subject: [PATCH] feat: add support for tuple enum variants in ts Idl parsing --- ts/packages/anchor/src/coder/borsh/idl.ts | 9 +++- ts/packages/anchor/tests/coder-types.spec.ts | 47 +++++++++++++++++++- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/ts/packages/anchor/src/coder/borsh/idl.ts b/ts/packages/anchor/src/coder/borsh/idl.ts index b7ec0e8a3d..250cc0eada 100644 --- a/ts/packages/anchor/src/coder/borsh/idl.ts +++ b/ts/packages/anchor/src/coder/borsh/idl.ts @@ -129,9 +129,14 @@ export class IdlCoder { if (variant.fields === undefined) { return borsh.struct([], name); } - const fieldLayouts = variant.fields.map((f: IdlField | IdlType) => { + const fieldLayouts = variant.fields.map((f: IdlField | IdlType, index: number) => { if (!f.hasOwnProperty("name")) { - throw new Error("Tuple enum variants not yet implemented."); + // Name tuple variants by the argument index + // e.g. arg0, arg1, arg2, etc + return IdlCoder.fieldLayout({ + name: `arg${index}`, + type: f as IdlType + }, types); } // this typescript conversion is ok // because if f were of type IdlType diff --git a/ts/packages/anchor/tests/coder-types.spec.ts b/ts/packages/anchor/tests/coder-types.spec.ts index 4e2b93c8f7..dd9eb3934a 100644 --- a/ts/packages/anchor/tests/coder-types.spec.ts +++ b/ts/packages/anchor/tests/coder-types.spec.ts @@ -1,5 +1,8 @@ import * as assert from "assert"; -import { BorshCoder } from "../src"; +import { BorshCoder, Idl, BN } from "../src"; +// import {} + +import SplGov from '../idl.json'; describe("coder.types", () => { test("Can encode and decode user-defined types", () => { @@ -42,4 +45,46 @@ describe("coder.types", () => { assert.deepEqual(coder.types.decode("MintInfo", encoded), mintInfo); }); + it("Test tuple enum variant decoding", () => { + const idl = { + version: "0.0.0", + name: "basic_0", + instructions: [ + { + name: "initialize", + accounts: [], + args: [], + }, + ], + types: [ + { + name: "Vote", + type: { + kind: "enum" as const, + variants: [ + { + name: "VoteWithComment", + fields: [ + "bool" as const, + "string" as const, + ] + } + ] + } + }, + ], + }; + const coder = new BorshCoder(idl); + + let vote = { + voteWithComment: { + arg0: true, + arg1: "blessed" + } + }; + let encoded = coder.types.encode("Vote", vote); + + assert.deepEqual(coder.types.decode("Vote", encoded), vote); + }) }); +