Skip to content

Commit

Permalink
Add createFromPem helper function (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
hpeebles authored Feb 19, 2024
1 parent 6ceffdf commit 33b05db
Show file tree
Hide file tree
Showing 5 changed files with 275 additions and 9 deletions.
252 changes: 251 additions & 1 deletion ts/consumer/package-lock.json

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

5 changes: 4 additions & 1 deletion ts/consumer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@
},
"dependencies": {
"@dfinity/agent": "^1.0.0",
"@dfinity/principal": "^1.0.0"
"@dfinity/identity-secp256k1": "^1.0.0",
"@dfinity/principal": "^1.0.0",
"pem-file": "^1.0.1"
},
"devDependencies": {
"@types/node": "^20.11.19",
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^3.2.4"
}
Expand Down
16 changes: 14 additions & 2 deletions ts/consumer/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import { Principal } from "@dfinity/principal";
import { Actor, HttpAgent } from "@dfinity/agent";
import { Principal } from "@dfinity/principal";
import { Secp256k1KeyIdentity } from "@dfinity/identity-secp256k1";
import pemfile from "pem-file";
import { EventSinkCanister, idlFactory } from "./candid/idl";
import type { EventsResponse, RemoveEventsResponse } from "./types";
import { candidEventsResponse, candidRemoveEventsResponse } from "./mappers";

export class Client {
private readonly canister: EventSinkCanister;

public constructor(canisterId: Principal, agent: HttpAgent) {
public constructor(canisterId: string | Principal, agent: HttpAgent) {
this.canister = Actor.createActor(idlFactory, {
agent,
canisterId,
});
}

public static createFromPem(canisterId: string | Principal, pem: string): Client {
const buf = pemfile.decode(pem);
if (buf.length != 118) {
throw 'expecting byte length 118 but got ' + buf.length;
}
const identity = Secp256k1KeyIdentity.fromSecretKey(buf.subarray(7, 39));
const httpAgent = new HttpAgent({ identity });
return new Client(canisterId, httpAgent);
}

public async events(start: bigint, length: bigint): Promise<EventsResponse> {
const candid = await this.canister.events({
start,
Expand Down
3 changes: 3 additions & 0 deletions ts/consumer/src/external-types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
declare module "pem-file" {
export function decode(pem: string | Buffer): Buffer;
}
Loading

0 comments on commit 33b05db

Please sign in to comment.