Skip to content
Open
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
33 changes: 31 additions & 2 deletions ts/packages/anchor/src/coder/borsh/instruction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class BorshInstructionCoder implements InstructionCoder {
// Instruction args layout. Maps namespaced method
private ixLayouts: Map<
string,
{ discriminator: IdlDiscriminator; layout: Layout }
{ discriminator: IdlDiscriminator; layout: Layout; args: IdlField[] }
>;

public constructor(private idl: Idl) {
Expand All @@ -35,7 +35,10 @@ export class BorshInstructionCoder implements InstructionCoder {
IdlCoder.fieldLayout(arg, idl.types)
);
const layout = borsh.struct(fieldLayouts, name);
return [name, { discriminator: ix.discriminator, layout }] as const;
return [
name,
{ discriminator: ix.discriminator, layout, args: ix.args },
] as const;
});
this.ixLayouts = new Map(ixLayouts);
}
Expand All @@ -50,6 +53,32 @@ export class BorshInstructionCoder implements InstructionCoder {
throw new Error(`Unknown method: ${ixName}`);
}

// Validate arg shape so silent zero-encoding of typos / wrong-shape
// payloads can't slip through. The borsh struct encoder happily writes
// default-valued bytes for every `undefined` field it sees, which masks
// mistakes like `encode("foo", 1000)` instead of `encode("foo", { x: 1000 })`
// or a misspelled field name.
if (encoder.args.length > 0) {
if (ix === null || typeof ix !== "object" || Array.isArray(ix)) {
const expected = encoder.args.map((a) => a.name).join(", ");
throw new Error(
`Invalid arguments for instruction "${ixName}": expected an object with fields { ${expected} }, got ${
ix === null ? "null" : Array.isArray(ix) ? "array" : typeof ix
}.`
);
}
const missing = encoder.args
.map((a) => a.name)
.filter((name) => !(name in ix));
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not sure about using in here. I got this explanation from GPT

in returns true when the property exists anywhere in the prototype chain, not just as an own property. Every plain {} inherits a fixed set of property names from Object.prototype
e.g; "toString" in {} -> true

if (missing.length > 0) {
throw new Error(
`Invalid arguments for instruction "${ixName}": missing field${
missing.length > 1 ? "s" : ""
} ${missing.map((m) => `\`${m}\``).join(", ")}.`
);
}
}

const len = encoder.layout.encode(ix, buffer);
const data = buffer.slice(0, len);

Expand Down
79 changes: 79 additions & 0 deletions ts/packages/anchor/tests/coder-instructions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,83 @@ describe("coder.instructions", () => {

assert.deepStrictEqual(decoded?.data[idlIx.args[0].name], expected);
});

describe("encode arg validation", () => {
const idl: Idl = {
address: "Test111111111111111111111111111111111111111",
metadata: { name: "test", version: "0.0.0", spec: "0.1.0" },
instructions: [
{
name: "setPassThresholdBps",
discriminator: [0, 1, 2, 3, 4, 5, 6, 7],
accounts: [],
args: [{ name: "passThresholdBps", type: "u16" }],
},
{
name: "noArgs",
discriminator: [8, 9, 10, 11, 12, 13, 14, 15],
accounts: [],
args: [],
},
],
};
const coder = new BorshCoder(idl);

test("throws when caller passes a primitive instead of an object", () => {
assert.throws(
() =>
coder.instruction.encode(
"setPassThresholdBps",
1000 as unknown as object
),
/expected an object with fields \{ passThresholdBps \}, got number/
);
});

test("throws when caller passes null", () => {
assert.throws(
() =>
coder.instruction.encode(
"setPassThresholdBps",
null as unknown as object
),
/got null/
);
});

test("throws when caller passes an array", () => {
assert.throws(
() =>
coder.instruction.encode("setPassThresholdBps", [
1000,
] as unknown as object),
/got array/
);
});

test("throws when a required field is missing", () => {
assert.throws(
() =>
coder.instruction.encode("setPassThresholdBps", {
// typo: missing trailing `s`
passThresholdBp: 1000,
} as any),
/missing field `passThresholdBps`/
);
});

test("encodes successfully when all fields are present", () => {
const encoded = coder.instruction.encode("setPassThresholdBps", {
passThresholdBps: 1000,
});
const decoded = coder.instruction.decode(encoded);
assert.deepStrictEqual(decoded?.data, { passThresholdBps: 1000 });
});

test("instructions with no args skip validation", () => {
assert.doesNotThrow(() =>
coder.instruction.encode("noArgs", {} as object)
);
});
});
});
Loading