Skip to content
Closed
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
9 changes: 7 additions & 2 deletions ts/packages/anchor/src/coder/borsh/idl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 46 additions & 1 deletion ts/packages/anchor/tests/coder-types.spec.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand Down Expand Up @@ -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);
})
});