Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update SubAccount.formID to handle bigger numbers #526

Merged
merged 5 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 11 additions & 2 deletions packages/ledger-icp/src/account_identifier.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ describe("SubAccount", () => {
expect(SubAccount.fromID(1)).toEqual(SubAccount.fromBytes(bytes));
bytes[31] = 255;
expect(SubAccount.fromID(255)).toEqual(SubAccount.fromBytes(bytes));

// Number 18791 in big endian 32 bytes
const numberInBytes = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 73, 103,
];
expect(SubAccount.fromID(18791)).toEqual(
SubAccount.fromBytes(new Uint8Array(numberInBytes)),
);
});

it("throws an exception if initialized with an ID < 0", () => {
Expand All @@ -68,9 +77,9 @@ describe("SubAccount", () => {
}).toThrow();
});

it("throws an exception if initialized with an ID > 255", () => {
it("throws an exception if initialized with an ID > max int", () => {
expect(() => {
SubAccount.fromID(256);
SubAccount.fromID(Number.MAX_SAFE_INTEGER + 1);
}).toThrow();
});
});
Expand Down
14 changes: 10 additions & 4 deletions packages/ledger-icp/src/account_identifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,18 @@ export class SubAccount {
}

public static fromID(id: number): SubAccount {
if (id < 0 || id > 255) {
throw "Subaccount ID must be >= 0 and <= 255";
if (id < 0) throw new Error("Number cannot be negative");

if (id > Number.MAX_SAFE_INTEGER) {
throw new Error("Number is too large to fit in 32 bytes.");
}

const bytes: Uint8Array = new Uint8Array(32).fill(0);
bytes[31] = id;
const buffer = Buffer.alloc(32);
peterpeterparker marked this conversation as resolved.
Show resolved Hide resolved

// Using 24 as the offset since BigInt64BE uses 8 bytes
buffer.writeBigInt64BE(BigInt(id), 24);

const bytes = new Uint8Array(buffer);
return new SubAccount(bytes);
}

Expand Down