@ic-reactor/core 0.0.1

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.
package/LICENSE.md ADDED
@@ -0,0 +1,8 @@
1
+ The MIT License (MIT)
2
+ Copyright © 2023 B3Pay
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # IC-ReActor - Core
2
+
3
+ ReActor is a JavaScript utility designed to streamline state management and interaction with actors in the Internet Computer (IC) blockchain environment. It provides a simple and effective way to handle asynchronous calls, state updates, and subscriptions, making it easier to build responsive and data-driven applications.
4
+
5
+ ## Features
6
+
7
+ - **State Management**: Efficiently manage the state of your application with actor-based interactions.
8
+ - **Asynchronous Handling**: Simplify asynchronous calls and data handling with built-in methods.
9
+ - **Subscription Mechanism**: Subscribe to state changes and update your UI in real-time.
10
+ - **Auto-Refresh Capability**: Automatically refresh data at specified intervals.
11
+ - **Customizable**: Easily adaptable to various use cases within the IC ecosystem.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @ic-reactor/core
17
+ ```
18
+
19
+ or
20
+
21
+ ```bash
22
+ yarn add @ic-reactor/core
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ To get started with ReActor, you'll need to initialize it with your actor configurations. Here's a basic example:
28
+
29
+ ```javascript
30
+ import createReActor from "@ic-reactor/core"
31
+
32
+ const { store, actions, initializeActor, queryCall, updateCall } =
33
+ createReActor(
34
+ (agent) =>
35
+ createActor("bd3sg-teaaa-aaaaa-qaaba-cai", {
36
+ agent,
37
+ }),
38
+ {
39
+ host: "https://localhost:4943",
40
+ }
41
+ )
42
+ ```
43
+
44
+ ### Querying Data
45
+
46
+ ```javascript
47
+ const { recall, subscribe, getState } = queryCall({
48
+ functionName: "yourFunctionName",
49
+ args: ["arg1", "arg2"],
50
+ autoRefresh: true,
51
+ refreshInterval: 3000,
52
+ })
53
+
54
+ // Subscribe to changes
55
+ const unsubscribe = subscribe((newState) => {
56
+ // Handle new state
57
+ })
58
+
59
+ // Fetch data
60
+ recall().then((data) => {
61
+ // Handle initial data
62
+ })
63
+ ```
64
+
65
+ ### Updating Data
66
+
67
+ ```javascript
68
+ const { call } = updateCall({
69
+ functionName: "yourUpdateFunction",
70
+ args: ["arg1", "arg2"],
71
+ })
72
+
73
+ call().then((result) => {
74
+ // Handle result
75
+ })
76
+ ```
77
+
78
+ ## API Reference
79
+
80
+ - `queryCall`: Fetches and subscribes to data from an actor method.
81
+ - `updateCall`: Updates data and handles state changes for an actor method.
82
+ - `getState`: Retrieves the current state based on the request hash.
83
+ - `subscribe`: Allows subscription to state changes.
84
+
85
+ For more detailed API usage and options, please refer to the [documentation](#).
86
+
87
+ ## Contributing
88
+
89
+ Contributions are welcome! Please read our [contributing guidelines](#) to get started.
90
+
91
+ ## License
92
+
93
+ This project is licensed under [MIT License](LICENSE).
@@ -0,0 +1,15 @@
1
+ import type { HttpAgent, HttpAgentOptions } from "@dfinity/agent";
2
+ import type { ActorSubclass, ReActorStore } from "@ic-reactor/store";
3
+ import { ReActorQuery, ReActorUpdate } from "./types";
4
+ export type ReActorContextType<A = ActorSubclass<any>> = ReActorStore<A>;
5
+ export interface CreateReActorOptions extends HttpAgentOptions {
6
+ initializeOnMount?: boolean;
7
+ }
8
+ declare const createReActor: <A extends unknown>(actorInitializer: (agent: HttpAgent) => A, options?: CreateReActorOptions) => {
9
+ store: ReActorStore<A>;
10
+ actions: import("@ic-reactor/store").ReActorStoreActions<A>;
11
+ initializeActor: (agentOptions?: HttpAgentOptions | undefined, identity?: import("@dfinity/agent").Identity | undefined) => void;
12
+ queryCall: ReActorQuery<A>;
13
+ updateCall: ReActorUpdate<A>;
14
+ };
15
+ export default createReActor;
package/dist/index.js ADDED
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __rest = (this && this.__rest) || function (s, e) {
35
+ var t = {};
36
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
+ t[p] = s[p];
38
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
+ t[p[i]] = s[p[i]];
42
+ }
43
+ return t;
44
+ };
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ const store_1 = __importStar(require("@ic-reactor/store"));
47
+ const defaultCreateReActorOptions = {
48
+ initializeOnMount: true,
49
+ host: process.env.NODE_ENV === "production"
50
+ ? "https://icp-api.io"
51
+ : "http://localhost:4943",
52
+ };
53
+ const createReActor = (actorInitializer, options = {}) => {
54
+ const optionsWithDefaults = Object.assign(Object.assign({}, defaultCreateReActorOptions), options);
55
+ const { actions, initializeActor, store } = (0, store_1.default)((agent) => actorInitializer(agent), optionsWithDefaults);
56
+ if (optionsWithDefaults.initializeOnMount) {
57
+ try {
58
+ initializeActor();
59
+ }
60
+ catch (e) {
61
+ console.error(e);
62
+ }
63
+ }
64
+ const updateMethodState = (method, args = [], newState) => {
65
+ const hash = (0, store_1.generateRequestHash)(args);
66
+ store.setState((state) => {
67
+ if (!state.actorState) {
68
+ console.error("Actor not initialized");
69
+ return state;
70
+ }
71
+ const methodState = state.actorState[method] || { states: {} };
72
+ const currentMethodState = methodState.states[hash] || {};
73
+ const updatedStates = Object.assign(Object.assign({}, methodState.states), { [hash]: Object.assign(Object.assign({}, currentMethodState), newState) });
74
+ return Object.assign(Object.assign({}, state), { actorState: Object.assign(Object.assign({}, state.actorState), { [method]: Object.assign(Object.assign({}, methodState), { states: updatedStates }) }) });
75
+ });
76
+ return hash;
77
+ };
78
+ const reActorMethod = (functionName, ...args) => {
79
+ try {
80
+ const requestHash = updateMethodState(functionName, args);
81
+ const getState = (key) => {
82
+ const state = store.getState().actorState[functionName].states[requestHash];
83
+ if (key === "data") {
84
+ return state.data;
85
+ }
86
+ else if (key === "loading") {
87
+ return state.loading;
88
+ }
89
+ else if (key === "error") {
90
+ return state.error;
91
+ }
92
+ else {
93
+ return state;
94
+ }
95
+ };
96
+ const subscribe = (callback) => {
97
+ const unsubscribe = store.subscribe((state) => {
98
+ const methodState = state.actorState[functionName];
99
+ const methodStateHash = methodState.states[requestHash];
100
+ if (methodStateHash) {
101
+ callback(methodStateHash);
102
+ }
103
+ });
104
+ return unsubscribe;
105
+ };
106
+ const call = (replaceArgs) => __awaiter(void 0, void 0, void 0, function* () {
107
+ updateMethodState(functionName, args, {
108
+ loading: true,
109
+ error: undefined,
110
+ });
111
+ const data = yield actions.callMethod(functionName, ...(replaceArgs !== null && replaceArgs !== void 0 ? replaceArgs : args));
112
+ updateMethodState(functionName, args, { data, loading: false });
113
+ return data;
114
+ });
115
+ return {
116
+ requestHash,
117
+ subscribe,
118
+ getState,
119
+ call,
120
+ };
121
+ }
122
+ catch (error) {
123
+ updateMethodState(functionName, args, {
124
+ error: error,
125
+ loading: false,
126
+ });
127
+ throw error;
128
+ }
129
+ };
130
+ const queryCall = ({ functionName, args = [], disableInitialCall = false, autoRefresh = false, refreshInterval = 5000, }) => {
131
+ let intervalId = null;
132
+ const _a = reActorMethod(functionName, ...args), { call } = _a, rest = __rest(_a, ["call"]);
133
+ if (autoRefresh) {
134
+ intervalId = setInterval(() => {
135
+ call();
136
+ }, refreshInterval);
137
+ }
138
+ let initialData = Promise.resolve();
139
+ if (!disableInitialCall)
140
+ initialData = call();
141
+ return Object.assign(Object.assign({}, rest), { recall: call, initialData, intervalId });
142
+ };
143
+ const updateCall = ({ functionName, args = [] }) => {
144
+ return reActorMethod(functionName, ...args);
145
+ };
146
+ return {
147
+ store,
148
+ actions,
149
+ initializeActor,
150
+ queryCall,
151
+ updateCall,
152
+ };
153
+ };
154
+ exports.default = createReActor;
@@ -0,0 +1,37 @@
1
+ /// <reference types="node" />
2
+ import { ActorMethod, ActorSubclass, ExtractReActorMethodArgs, ExtractReActorMethodReturnType, ReActorMethodState } from "@ic-reactor/store";
3
+ export type ReActorGetStateFunction<A, M extends keyof A> = (key?: keyof ReActorMethodState<A, M>["states"][string]) => ReActorMethodState<A, M>["states"][string] | ExtractReActorMethodReturnType<A[M]> | boolean | Error | undefined;
4
+ export type ReActorSubscribeFunction<A, M extends keyof A> = (callback: (state: ReActorMethodState<A, M>["states"][string]) => void) => () => void;
5
+ export type ReActorCallFunction<A, M extends keyof A> = (replaceArgs?: ExtractReActorMethodArgs<A[M]>) => Promise<ExtractReActorMethodReturnType<A[M]>>;
6
+ export type ReActorQueryReturn<A, M extends keyof A> = {
7
+ intervalId: NodeJS.Timeout | null;
8
+ requestHash: string;
9
+ getState: ReActorGetStateFunction<A, M>;
10
+ subscribe: ReActorSubscribeFunction<A, M>;
11
+ recall: ReActorCallFunction<A, M>;
12
+ initialData: Promise<ExtractReActorMethodReturnType<A[M]>>;
13
+ };
14
+ export type ReActorUpdateReturn<A, M extends keyof A> = {
15
+ requestHash: string;
16
+ getState: ReActorGetStateFunction<A, M>;
17
+ subscribe: ReActorSubscribeFunction<A, M>;
18
+ call: ReActorCallFunction<A, M>;
19
+ };
20
+ export type ReActorQueryArgs<A, M extends keyof A> = {
21
+ functionName: M;
22
+ args?: ExtractReActorMethodArgs<A[M]>;
23
+ disableInitialCall?: boolean;
24
+ autoRefresh?: boolean;
25
+ refreshInterval?: number;
26
+ };
27
+ export type ReActorUpdateArgs<A, M extends keyof A> = {
28
+ functionName: M;
29
+ args?: ExtractReActorMethodArgs<A[M]>;
30
+ };
31
+ export type ReActorMethod<A = Record<string, ActorMethod>> = <M extends keyof A>(functionName: M, ...args: ExtractReActorMethodArgs<A[M]>) => ReActorUpdateReturn<A, M>;
32
+ export type ReActorQuery<A = Record<string, ActorMethod>> = <M extends keyof A>(options: ReActorQueryArgs<A, M>) => ReActorQueryReturn<A, M>;
33
+ export type ReActorUpdate<A = Record<string, ActorMethod>> = <M extends keyof A>(options: ReActorUpdateArgs<A, M>) => ReActorUpdateReturn<A, M>;
34
+ export interface ReActorCoreActions<A extends ActorSubclass<any>> {
35
+ queryCall: ReActorQuery<A>;
36
+ updateCall: ReActorUpdate<A>;
37
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@ic-reactor/core",
3
+ "version": "0.0.1",
4
+ "description": "A React library for interacting with Dfinity actors",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.esm.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist/*"
10
+ ],
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git@github.com:b3hr4d/ic-reactor.git"
14
+ },
15
+ "keywords": [
16
+ "actor",
17
+ "react",
18
+ "candid",
19
+ "dfinity",
20
+ "web3",
21
+ "dapp"
22
+ ],
23
+ "author": "b3hr4d",
24
+ "license": "MIT",
25
+ "bugs": {
26
+ "url": "https://github.com/b3hr4d/ic-reactor/issues"
27
+ },
28
+ "homepage": "https://github.com/b3hr4d/ic-reactor/tree/main/packages/core#readme",
29
+ "scripts": {
30
+ "test": "npx jest",
31
+ "start": "tsc watch",
32
+ "build": "npx tsc",
33
+ "clean": "rimraf dist"
34
+ },
35
+ "engines": {
36
+ "node": ">=10"
37
+ },
38
+ "dependencies": {
39
+ "@dfinity/agent": "^0.20",
40
+ "@dfinity/auth-client": "^0.20",
41
+ "@dfinity/candid": "0.20",
42
+ "@dfinity/identity": "^0.20",
43
+ "@dfinity/principal": "^0.20",
44
+ "@ic-reactor/store": "^0.0.1",
45
+ "zustand": "4.4"
46
+ },
47
+ "peerDependencies": {
48
+ "@peculiar/webcrypto": "1.4"
49
+ },
50
+ "gitHead": "b1f673a150b591ad3cfbb8964794e4ea9b0ff1c2"
51
+ }