@jsm-mit/rabbit-motoko-package 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ import type {
2
+ ActorSubclass,
3
+ HttpAgentOptions,
4
+ ActorConfig,
5
+ Agent,
6
+ } from "@icp-sdk/core/agent";
7
+ import type { Principal } from "@icp-sdk/core/principal";
8
+ import type { IDL } from "@icp-sdk/core/candid";
9
+
10
+ import { _SERVICE } from './rabbit-motoko-backend.did';
11
+
12
+ export declare const idlFactory: IDL.InterfaceFactory;
13
+ export declare const canisterId: string;
14
+
15
+ export declare interface CreateActorOptions {
16
+ /**
17
+ * @see {@link Agent}
18
+ */
19
+ agent?: Agent;
20
+ /**
21
+ * @see {@link HttpAgentOptions}
22
+ */
23
+ agentOptions?: HttpAgentOptions;
24
+ /**
25
+ * @see {@link ActorConfig}
26
+ */
27
+ actorOptions?: ActorConfig;
28
+ }
29
+
30
+ /**
31
+ * Intializes an {@link ActorSubclass}, configured with the provided SERVICE interface of a canister.
32
+ * @constructs {@link ActorSubClass}
33
+ * @param {string | Principal} canisterId - ID of the canister the {@link Actor} will talk to
34
+ * @param {CreateActorOptions} options - see {@link CreateActorOptions}
35
+ * @param {CreateActorOptions["agent"]} options.agent - a pre-configured agent you'd like to use. Supercedes agentOptions
36
+ * @param {CreateActorOptions["agentOptions"]} options.agentOptions - options to set up a new agent
37
+ * @see {@link HttpAgentOptions}
38
+ * @param {CreateActorOptions["actorOptions"]} options.actorOptions - options for the Actor
39
+ * @see {@link ActorConfig}
40
+ */
41
+ export declare const createActor: (
42
+ canisterId: string | Principal,
43
+ options?: CreateActorOptions
44
+ ) => ActorSubclass<_SERVICE>;
45
+
46
+ /**
47
+ * Intialized Actor using default settings, ready to talk to a canister using its candid interface
48
+ * @constructs {@link ActorSubClass}
49
+ */
50
+ export declare const rabbit_motoko_backend: ActorSubclass<_SERVICE>;
@@ -0,0 +1,42 @@
1
+ import { Actor, HttpAgent } from "@icp-sdk/core/agent";
2
+
3
+ // Imports and re-exports candid interface
4
+ import { idlFactory } from "./rabbit-motoko-backend.did.js";
5
+ export { idlFactory } from "./rabbit-motoko-backend.did.js";
6
+
7
+ /* CANISTER_ID is replaced by webpack based on node environment
8
+ * Note: canister environment variable will be standardized as
9
+ * process.env.CANISTER_ID_<CANISTER_NAME_UPPERCASE>
10
+ * beginning in dfx 0.15.0
11
+ */
12
+ export const canisterId =
13
+ process.env.CANISTER_ID_RABBIT_MOTOKO_BACKEND;
14
+
15
+ export const createActor = (canisterId, options = {}) => {
16
+ const agent = options.agent || new HttpAgent({ ...options.agentOptions });
17
+
18
+ if (options.agent && options.agentOptions) {
19
+ console.warn(
20
+ "Detected both agent and agentOptions passed to createActor. Ignoring agentOptions and proceeding with the provided agent."
21
+ );
22
+ }
23
+
24
+ // Fetch root key for certificate validation during development
25
+ if (process.env.DFX_NETWORK !== "ic") {
26
+ agent.fetchRootKey().catch((err) => {
27
+ console.warn(
28
+ "Unable to fetch root key. Check to ensure that your local replica is running"
29
+ );
30
+ console.error(err);
31
+ });
32
+ }
33
+
34
+ // Creates an actor with using the candid interface and the HttpAgent
35
+ return Actor.createActor(idlFactory, {
36
+ agent,
37
+ canisterId,
38
+ ...options.actorOptions,
39
+ });
40
+ };
41
+
42
+ export const rabbit_motoko_backend = canisterId ? createActor(canisterId) : undefined;
@@ -0,0 +1,39 @@
1
+ type Task =
2
+ record {
3
+ channel: text;
4
+ completedAt: int;
5
+ createdAt: int;
6
+ expiresAt: int;
7
+ id: nat;
8
+ parentIds: opt vec nat;
9
+ payload: text;
10
+ resultMessage: text;
11
+ status: nat;
12
+ timesOutAt: int;
13
+ worker: principal;
14
+ };
15
+ type CompleteTaskArgs =
16
+ record {
17
+ id: nat;
18
+ message: text;
19
+ };
20
+ type ClaimTaskArgs =
21
+ record {
22
+ id: nat;
23
+ timeoutNanos: int;
24
+ };
25
+ type AddTaskArgs =
26
+ record {
27
+ channel: text;
28
+ parentIds: opt vec nat;
29
+ payload: text;
30
+ };
31
+ service : {
32
+ addTask: (args: AddTaskArgs) -> (nat);
33
+ claimTask: (args: ClaimTaskArgs) -> (opt Task);
34
+ completeTask: (args: CompleteTaskArgs) -> (bool);
35
+ getAvailableTaskIds: (channel: text) -> (vec nat) query;
36
+ getTask: (id: nat) -> (opt Task) query;
37
+ getTasks: () -> (vec Task) query;
38
+ getTasksLast24h: () -> (vec Task) query;
39
+ }
@@ -0,0 +1,35 @@
1
+ import type { Principal } from '@icp-sdk/core/principal';
2
+ import type { ActorMethod } from '@icp-sdk/core/agent';
3
+ import type { IDL } from '@icp-sdk/core/candid';
4
+
5
+ export interface AddTaskArgs {
6
+ 'parentIds' : [] | [Array<bigint>],
7
+ 'channel' : string,
8
+ 'payload' : string,
9
+ }
10
+ export interface ClaimTaskArgs { 'id' : bigint, 'timeoutNanos' : bigint }
11
+ export interface CompleteTaskArgs { 'id' : bigint, 'message' : string }
12
+ export interface Task {
13
+ 'id' : bigint,
14
+ 'status' : bigint,
15
+ 'completedAt' : bigint,
16
+ 'resultMessage' : string,
17
+ 'expiresAt' : bigint,
18
+ 'timesOutAt' : bigint,
19
+ 'createdAt' : bigint,
20
+ 'parentIds' : [] | [Array<bigint>],
21
+ 'worker' : Principal,
22
+ 'channel' : string,
23
+ 'payload' : string,
24
+ }
25
+ export interface _SERVICE {
26
+ 'addTask' : ActorMethod<[AddTaskArgs], bigint>,
27
+ 'claimTask' : ActorMethod<[ClaimTaskArgs], [] | [Task]>,
28
+ 'completeTask' : ActorMethod<[CompleteTaskArgs], boolean>,
29
+ 'getAvailableTaskIds' : ActorMethod<[string], Array<bigint>>,
30
+ 'getTask' : ActorMethod<[bigint], [] | [Task]>,
31
+ 'getTasks' : ActorMethod<[], Array<Task>>,
32
+ 'getTasksLast24h' : ActorMethod<[], Array<Task>>,
33
+ }
34
+ export declare const idlFactory: IDL.InterfaceFactory;
35
+ export declare const init: (args: { IDL: typeof IDL }) => IDL.Type[];
@@ -0,0 +1,35 @@
1
+ export const idlFactory = ({ IDL }) => {
2
+ const AddTaskArgs = IDL.Record({
3
+ 'parentIds' : IDL.Opt(IDL.Vec(IDL.Nat)),
4
+ 'channel' : IDL.Text,
5
+ 'payload' : IDL.Text,
6
+ });
7
+ const ClaimTaskArgs = IDL.Record({
8
+ 'id' : IDL.Nat,
9
+ 'timeoutNanos' : IDL.Int,
10
+ });
11
+ const Task = IDL.Record({
12
+ 'id' : IDL.Nat,
13
+ 'status' : IDL.Nat,
14
+ 'completedAt' : IDL.Int,
15
+ 'resultMessage' : IDL.Text,
16
+ 'expiresAt' : IDL.Int,
17
+ 'timesOutAt' : IDL.Int,
18
+ 'createdAt' : IDL.Int,
19
+ 'parentIds' : IDL.Opt(IDL.Vec(IDL.Nat)),
20
+ 'worker' : IDL.Principal,
21
+ 'channel' : IDL.Text,
22
+ 'payload' : IDL.Text,
23
+ });
24
+ const CompleteTaskArgs = IDL.Record({ 'id' : IDL.Nat, 'message' : IDL.Text });
25
+ return IDL.Service({
26
+ 'addTask' : IDL.Func([AddTaskArgs], [IDL.Nat], []),
27
+ 'claimTask' : IDL.Func([ClaimTaskArgs], [IDL.Opt(Task)], []),
28
+ 'completeTask' : IDL.Func([CompleteTaskArgs], [IDL.Bool], []),
29
+ 'getAvailableTaskIds' : IDL.Func([IDL.Text], [IDL.Vec(IDL.Nat)], ['query']),
30
+ 'getTask' : IDL.Func([IDL.Nat], [IDL.Opt(Task)], ['query']),
31
+ 'getTasks' : IDL.Func([], [IDL.Vec(Task)], ['query']),
32
+ 'getTasksLast24h' : IDL.Func([], [IDL.Vec(Task)], ['query']),
33
+ });
34
+ };
35
+ export const init = ({ IDL }) => { return []; };
@@ -0,0 +1,2 @@
1
+ export { RabbitMotokoActor } from "./rabbit-motoko-actor.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { RabbitMotokoActor } from "./rabbit-motoko-actor.js";
@@ -0,0 +1,33 @@
1
+ import type { AddTaskArgs, ClaimTaskArgs, CompleteTaskArgs, Task } from "../declarations/rabbit-motoko-backend/rabbit-motoko-backend.did.js";
2
+ export declare class RabbitMotokoActor {
3
+ private readonly canisterId;
4
+ private readonly host;
5
+ private actor;
6
+ private agent;
7
+ constructor(canisterId: string);
8
+ private initActor;
9
+ private setupAgent;
10
+ private checkError;
11
+ sync(): Promise<void>;
12
+ /**
13
+ * Adds a new task to the queue.
14
+ */
15
+ addTask(args: AddTaskArgs): Promise<bigint>;
16
+ /**
17
+ * Claims a task for a specific worker.
18
+ */
19
+ claimTask(args: ClaimTaskArgs): Promise<[] | [Task]>;
20
+ /**
21
+ * Completes a previously claimed task.
22
+ */
23
+ completeTask(args: CompleteTaskArgs): Promise<boolean>;
24
+ /**
25
+ * Fetches IDs of tasks available in a specific channel.
26
+ */
27
+ getAvailableTaskIds(channel: string): Promise<bigint[]>;
28
+ /**
29
+ * Returns a list of all tasks.
30
+ */
31
+ getTasks(): Promise<Task[]>;
32
+ }
33
+ //# sourceMappingURL=rabbit-motoko-actor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rabbit-motoko-actor.d.ts","sourceRoot":"","sources":["../src/rabbit-motoko-actor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAER,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,IAAI,EACP,MAAM,oEAAoE,CAAC;AAE5E,qBAAa,iBAAiB;IAKd,OAAO,CAAC,QAAQ,CAAC,UAAU;IAJvC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,OAAO,CAAC,KAAK,CAA2B;IACxC,OAAO,CAAC,KAAK,CAAY;gBAEI,UAAU,EAAE,MAAM;IAe/C,OAAO,CAAC,SAAS;YAOH,UAAU;YAWV,UAAU;IAQX,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IASlC;;OAEG;IACU,OAAO,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC;IAUxD;;OAEG;IACU,SAAS,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IAUjE;;OAEG;IACU,YAAY,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;IAUnE;;OAEG;IACU,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAUpE;;OAEG;IACU,QAAQ,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;CAS3C"}
@@ -0,0 +1,115 @@
1
+ import { Actor, HttpAgent } from "@dfinity/agent";
2
+ import { idlFactory } from "../declarations/rabbit-motoko-backend/index.js";
3
+ export class RabbitMotokoActor {
4
+ constructor(canisterId) {
5
+ this.canisterId = canisterId;
6
+ this.host = "https://icp0.io";
7
+ // 1. Tworzymy agenta
8
+ this.agent = new HttpAgent({
9
+ host: this.host,
10
+ // Opcjonalnie: można zwiększyć margines akceptacji czasu (retryDelay),
11
+ // ale syncTime() jest skuteczniejszym rozwiązaniem.
12
+ });
13
+ // 2. Inicjalizujemy aktora
14
+ this.initActor();
15
+ // 3. Odpalamy asynchroniczną synchronizację
16
+ this.setupAgent();
17
+ }
18
+ initActor() {
19
+ this.actor = Actor.createActor(idlFactory, {
20
+ agent: this.agent,
21
+ canisterId: this.canisterId,
22
+ });
23
+ }
24
+ async setupAgent() {
25
+ try {
26
+ // Synchronizacja czasu z siecią IC - rozwiązuje błąd "certificate is still too far in the future"
27
+ await this.agent.syncTime();
28
+ console.log("✅ Agent IC zsynchronizowany pomyślnie.");
29
+ }
30
+ catch (err) {
31
+ console.error("❌ Błąd podczas konfiguracji Agenta:", err);
32
+ }
33
+ }
34
+ async checkError(error) {
35
+ const errorMsg = error?.toString() || "";
36
+ if (errorMsg.includes("certificate") || errorMsg.includes("TrustError")) {
37
+ console.warn("⚠️ Wykryto problem z zaufaniem/czasem. Próbuję synchronizacji...");
38
+ await this.sync();
39
+ }
40
+ }
41
+ async sync() {
42
+ try {
43
+ await this.agent.syncTime();
44
+ console.log("🔄 Czas agenta został zsynchronizowany ponownie.");
45
+ }
46
+ catch (err) {
47
+ console.error("❌ Nie udało się zsynchronizować czasu:", err);
48
+ }
49
+ }
50
+ /**
51
+ * Adds a new task to the queue.
52
+ */
53
+ async addTask(args) {
54
+ try {
55
+ return await this.actor.addTask(args);
56
+ }
57
+ catch (error) {
58
+ await this.checkError(error);
59
+ console.error(`❌ Błąd podczas dodawania zadania:`, error);
60
+ throw error;
61
+ }
62
+ }
63
+ /**
64
+ * Claims a task for a specific worker.
65
+ */
66
+ async claimTask(args) {
67
+ try {
68
+ return await this.actor.claimTask(args);
69
+ }
70
+ catch (error) {
71
+ await this.checkError(error);
72
+ console.error(`❌ Błąd podczas pobierania zadania (claimTask):`, error);
73
+ throw error;
74
+ }
75
+ }
76
+ /**
77
+ * Completes a previously claimed task.
78
+ */
79
+ async completeTask(args) {
80
+ try {
81
+ return await this.actor.completeTask(args);
82
+ }
83
+ catch (error) {
84
+ await this.checkError(error);
85
+ console.error(`❌ Błąd podczas zakończenia zadania:`, error);
86
+ throw error;
87
+ }
88
+ }
89
+ /**
90
+ * Fetches IDs of tasks available in a specific channel.
91
+ */
92
+ async getAvailableTaskIds(channel) {
93
+ try {
94
+ return await this.actor.getAvailableTaskIds(channel);
95
+ }
96
+ catch (error) {
97
+ await this.checkError(error);
98
+ console.error(`❌ Błąd podczas pobierania ID zadań (Kanał: ${channel}):`, error);
99
+ throw error;
100
+ }
101
+ }
102
+ /**
103
+ * Returns a list of all tasks.
104
+ */
105
+ async getTasks() {
106
+ try {
107
+ return await this.actor.getTasks();
108
+ }
109
+ catch (error) {
110
+ await this.checkError(error);
111
+ console.error(`❌ Błąd podczas pobierania wszystkich zadań (getTasks):`, error);
112
+ throw error;
113
+ }
114
+ }
115
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@jsm-mit/rabbit-motoko-package",
3
+ "version": "0.1.0",
4
+ "description": "Wrapper TypeScript package for Rabbit Motoko IC actor using @dfinity/agent.",
5
+ "license": "ISC",
6
+ "author": "",
7
+ "type": "module",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/index.js",
13
+ "types": "./dist/index.d.ts"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist/",
18
+ "declarations/"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc --build",
22
+ "clean": "rm -rf dist",
23
+ "prepare": "npm run build",
24
+ "test": "echo \"Error: no test specified\" && exit 1"
25
+ },
26
+ "devDependencies": {
27
+ "typescript": "^5.5.4"
28
+ },
29
+ "dependencies": {
30
+ "@dfinity/agent": "^3.4.3"
31
+ }
32
+ }