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
25 changes: 25 additions & 0 deletions src/__tests__/protobuf.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { encodeMessage } from "../protobuf.js";

const validSend = {
fromAddress: "11".repeat(20),
toAddress: "22".repeat(20),
amount: 1,
};

describe("encodeMessage", () => {
it("encodes a valid send amount", () => {
const { typeUrl, msgBytes } = encodeMessage("send", validSend);

expect(typeUrl).toBe("type.googleapis.com/types.MessageSend");
expect(msgBytes.length).toBeGreaterThan(0);
});

it("rejects send amounts that cannot be encoded as uint64 values", () => {
for (const amount of [-1, 1.5, Number.NaN]) {
expect(() => encodeMessage("send", { ...validSend, amount })).toThrow(
"amount must be a non-negative safe integer",
);
}
});
});
9 changes: 8 additions & 1 deletion src/protobuf.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import protobuf from "protobufjs";
import { hexToBytes } from "@noble/hashes/utils.js";

function assertUint64Field(name: string, value: unknown): number {
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
throw new Error(`${name} must be a non-negative safe integer`);
}
return value;
}

function shouldOmit(value: any): boolean {
if (value === undefined || value === null) return true;
if (typeof value === "string" && value === "") return true;
Expand Down Expand Up @@ -74,7 +81,7 @@ const MESSAGE_REGISTRY: Record<
MsgSend.create({
from_address: hexToBytes(msg.fromAddress),
to_address: hexToBytes(msg.toAddress),
amount: msg.amount,
amount: assertUint64Field("amount", msg.amount),
})
).finish(),
},
Expand Down