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

fix: Principal JSON is compatible with @dfinity/utils jsonReviver helper #770

Merged
merged 3 commits into from
Sep 25, 2023
Merged
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
1 change: 1 addition & 0 deletions docs/generated/changelog.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ <h1>Agent-JS Changelog</h1>
<section>
<h2>Version x.x.x</h2>
<ul>
<li>fix: Principal JSON is compatible with @dfinity/utils jsonReviver helper</li>
<li>chore: npm audit</li>
<li>feat: Principal class serializes to JSON</li>
<li>
Expand Down
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"simple-cbor": "^0.4.1"
},
"devDependencies": {
"@dfinity/utils": "^0.0.22",
"@peculiar/webcrypto": "^1.4.3",
"@trust/webcrypto": "^0.9.2",
"@types/jest": "^28.1.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

exports[`Canister Status utility should query canister controllers 1`] = `
Array [
"rwlgt-iiaaa-aaaaa-aaaaa-cai",
Object {
"__principal__": "rwlgt-iiaaa-aaaaa-aaaaa-cai",
},
]
`;

Expand All @@ -22,7 +24,9 @@ exports[`Canister Status utility should support multiple requests 1`] = `2022-05

exports[`Canister Status utility should support multiple requests 2`] = `
Array [
"rwlgt-iiaaa-aaaaa-aaaaa-cai",
Object {
"__principal__": "rwlgt-iiaaa-aaaaa-aaaaa-cai",
},
]
`;

Expand Down
17 changes: 16 additions & 1 deletion packages/principal/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Principal } from '.';
import { jsonReviver } from '@dfinity/utils';

describe('Principal', () => {
it('encodes properly', () => {
Expand Down Expand Up @@ -50,6 +51,20 @@ describe('Principal', () => {

it('serializes to JSON', () => {
const principal = Principal.fromText('ryjl3-tyaaa-aaaaa-aaaba-cai');
expect(JSON.stringify(principal)).toBe('"ryjl3-tyaaa-aaaaa-aaaba-cai"');

const json = principal.toJSON();
expect(json).toEqual({ __principal__: 'ryjl3-tyaaa-aaaaa-aaaba-cai' });

const stringified = JSON.stringify(principal);
expect(stringified).toEqual('{"__principal__":"ryjl3-tyaaa-aaaaa-aaaba-cai"}');

expect(JSON.parse(stringified, jsonReviver)).toEqual(principal);
});

it('serializes from JSON string', () => {
const principal = Principal.fromText('ryjl3-tyaaa-aaaaa-aaaba-cai');
const json = JSON.stringify(principal);
json;
expect(Principal.from(json)).toEqual(principal);
});
});
26 changes: 20 additions & 6 deletions packages/principal/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { decode, encode } from './utils/base32';
import { getCrc32 } from './utils/getCrc';
import { sha224 } from './utils/sha224';

export const JSON_KEY_PRINCIPAL = '__principal__';
const SELF_AUTHENTICATING_SUFFIX = 2;
const ANONYMOUS_SUFFIX = 4;

Expand All @@ -13,6 +14,10 @@ const fromHexString = (hexString: string) =>
const toHexString = (bytes: Uint8Array) =>
bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');

export type JsonnablePrincipal = {
[JSON_KEY_PRINCIPAL]: string;
};

export class Principal {
public static anonymous(): Principal {
return new this(new Uint8Array([ANONYMOUS_SUFFIX]));
Expand Down Expand Up @@ -50,15 +55,24 @@ export class Principal {
}

public static fromText(text: string): Principal {
const canisterIdNoDash = text.toLowerCase().replace(/-/g, '');
let maybePrincipal = text;
// If formatted as JSON string, parse it first
if (text.includes(JSON_KEY_PRINCIPAL)) {
const obj = JSON.parse(text);
if (JSON_KEY_PRINCIPAL in obj) {
maybePrincipal = obj[JSON_KEY_PRINCIPAL];
}
}

const canisterIdNoDash = maybePrincipal.toLowerCase().replace(/-/g, '');

let arr = decode(canisterIdNoDash);
arr = arr.slice(4, arr.length);

const principal = new this(arr);
if (principal.toText() !== text) {
if (principal.toText() !== maybePrincipal) {
throw new Error(
`Principal "${principal.toText()}" does not have a valid checksum (original value "${text}" may not be a valid Principal ID).`,
`Principal "${principal.toText()}" does not have a valid checksum (original value "${maybePrincipal}" may not be a valid Principal ID).`,
);
}

Expand Down Expand Up @@ -109,10 +123,10 @@ export class Principal {

/**
* Serializes to JSON
* @returns {string} string
* @returns {JsonnablePrincipal} a JSON object with a single key, {@link JSON_KEY_PRINCIPAL}, whose value is the principal as a string
*/
public toJSON(): string {
return this.toText();
public toJSON(): JsonnablePrincipal {
return { [JSON_KEY_PRINCIPAL]: this.toText() };
}

/**
Expand Down
Loading