@novasamatech/host-api 0.5.0-18 → 0.5.0-19

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.
Files changed (76) hide show
  1. package/README.md +103 -1
  2. package/dist/constants.d.ts +2 -0
  3. package/dist/constants.js +2 -0
  4. package/dist/helpers.d.ts +33 -0
  5. package/dist/helpers.js +46 -0
  6. package/dist/hostApi.d.ts +31 -0
  7. package/dist/hostApi.js +345 -0
  8. package/dist/index.d.ts +18 -7
  9. package/dist/index.js +14 -6
  10. package/dist/protocol/commonCodecs.d.ts +42 -0
  11. package/dist/protocol/commonCodecs.js +64 -0
  12. package/dist/protocol/commonCodecs.spec.js +72 -0
  13. package/dist/protocol/impl.d.ts +93 -0
  14. package/dist/protocol/impl.js +97 -0
  15. package/dist/protocol/messageCodec.d.ts +1245 -0
  16. package/dist/protocol/messageCodec.js +24 -0
  17. package/dist/protocol/types.js +1 -0
  18. package/dist/protocol/v1/accounts.d.ts +265 -0
  19. package/dist/{interactions → protocol}/v1/accounts.js +11 -11
  20. package/dist/{interactions → protocol}/v1/chat.d.ts +129 -83
  21. package/dist/{interactions → protocol}/v1/chat.js +12 -14
  22. package/dist/{interactions → protocol}/v1/createTransaction.d.ts +119 -78
  23. package/dist/protocol/v1/createTransaction.js +58 -0
  24. package/dist/{interactions → protocol}/v1/feature.d.ts +8 -4
  25. package/dist/protocol/v1/feature.js +7 -0
  26. package/dist/protocol/v1/handshake.d.ts +85 -0
  27. package/dist/protocol/v1/handshake.js +12 -0
  28. package/dist/{interactions → protocol}/v1/jsonRpc.d.ts +6 -2
  29. package/dist/{interactions → protocol}/v1/jsonRpc.js +2 -2
  30. package/dist/protocol/v1/permission.d.ts +90 -0
  31. package/dist/protocol/v1/permission.js +18 -0
  32. package/dist/protocol/v1/sign.d.ts +152 -0
  33. package/dist/{interactions → protocol}/v1/sign.js +6 -6
  34. package/dist/{interactions → protocol}/v1/statementStore.d.ts +77 -20
  35. package/dist/{interactions → protocol}/v1/statementStore.js +6 -6
  36. package/dist/protocol/v1/storage.d.ts +87 -0
  37. package/dist/{interactions → protocol}/v1/storage.js +5 -5
  38. package/dist/provider.d.ts +8 -0
  39. package/dist/provider.js +1 -0
  40. package/dist/transport.d.ts +3 -0
  41. package/dist/transport.js +248 -0
  42. package/dist/types.d.ts +15 -15
  43. package/package.json +2 -4
  44. package/dist/commonEncoders.d.ts +0 -2
  45. package/dist/commonEncoders.js +0 -8
  46. package/dist/createTransport.d.ts +0 -6
  47. package/dist/createTransport.js +0 -183
  48. package/dist/createTransportEncoder.d.ts +0 -7
  49. package/dist/createTransportEncoder.js +0 -5
  50. package/dist/interactions/accounts.d.ts +0 -12
  51. package/dist/interactions/accounts.js +0 -40
  52. package/dist/interactions/commonCodecs.d.ts +0 -7
  53. package/dist/interactions/commonCodecs.js +0 -8
  54. package/dist/interactions/features.d.ts +0 -13
  55. package/dist/interactions/features.js +0 -13
  56. package/dist/interactions/handshake.d.ts +0 -2
  57. package/dist/interactions/handshake.js +0 -3
  58. package/dist/interactions/message.d.ts +0 -1704
  59. package/dist/interactions/message.js +0 -60
  60. package/dist/interactions/papiProvider.d.ts +0 -8
  61. package/dist/interactions/papiProvider.js +0 -10
  62. package/dist/interactions/sign.d.ts +0 -118
  63. package/dist/interactions/sign.js +0 -127
  64. package/dist/interactions/v1/accounts.d.ts +0 -128
  65. package/dist/interactions/v1/createTransaction.js +0 -41
  66. package/dist/interactions/v1/feature.js +0 -7
  67. package/dist/interactions/v1/handshake.d.ts +0 -28
  68. package/dist/interactions/v1/handshake.js +0 -12
  69. package/dist/interactions/v1/permission.d.ts +0 -48
  70. package/dist/interactions/v1/permission.js +0 -18
  71. package/dist/interactions/v1/sign.d.ts +0 -92
  72. package/dist/interactions/v1/storage.d.ts +0 -41
  73. package/dist/messageEncoder.d.ts +0 -178
  74. package/dist/messageEncoder.js +0 -34
  75. /package/dist/{interactions/types.js → protocol/commonCodecs.spec.d.ts} +0 -0
  76. /package/dist/{interactions → protocol}/types.d.ts +0 -0
package/dist/types.d.ts CHANGED
@@ -1,23 +1,23 @@
1
- import type { MessagePayloadSchema, MessageType, PickMessagePayload, PickMessagePayloadValue } from './messageEncoder.js';
2
- export type HexString = `0x${string}`;
1
+ import type { ComposeMessageAction, MessageAction, MessagePayloadSchema, PickMessagePayload, PickMessagePayloadValue } from './protocol/messageCodec.js';
2
+ import type { Provider } from './provider.js';
3
3
  export type Logger = Record<'info' | 'warn' | 'error' | 'log', (...args: unknown[]) => void>;
4
- export type TransportProvider = {
5
- logger: Logger;
6
- isCorrectEnvironment(): boolean;
7
- postMessage(message: Uint8Array): void;
8
- subscribe(callback: (message: Uint8Array) => void): () => void;
9
- dispose(): void;
10
- };
11
4
  export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected';
5
+ export type RequestHandler<Method extends string> = (message: PickMessagePayloadValue<ComposeMessageAction<Method, 'request'>>) => PromiseLike<PickMessagePayloadValue<ComposeMessageAction<Method, 'response'>>>;
6
+ export type SubscriptionHandler<Method extends string> = (params: PickMessagePayloadValue<ComposeMessageAction<Method, 'start'>>, send: (value: PickMessagePayloadValue<ComposeMessageAction<Method, 'receive'>>) => void, interrupt: () => void) => VoidFunction;
7
+ export type Subscription = {
8
+ unsubscribe: VoidFunction;
9
+ onInterrupt(callback: VoidFunction): VoidFunction;
10
+ };
12
11
  export type Transport = {
13
- readonly provider: TransportProvider;
12
+ readonly provider: Provider;
14
13
  isCorrectEnvironment(): boolean;
15
14
  isReady(): Promise<boolean>;
16
- subscribeAny(callback: (id: string, payload: MessagePayloadSchema) => void): VoidFunction;
17
- subscribe<const Type extends MessageType>(type: Type, callback: (id: string, payload: PickMessagePayloadValue<Type>) => void): VoidFunction;
18
- postMessage(id: string, payload: MessagePayloadSchema): string;
19
- request<Response extends MessageType>(payload: MessagePayloadSchema, response: Response, abortSignal?: AbortSignal): Promise<PickMessagePayloadValue<Response>>;
20
- handleMessage<Request extends MessageType, Response extends MessageType>(type: Request, handler: (message: PickMessagePayloadValue<Request>) => Promise<PickMessagePayload<Response> | void>): VoidFunction;
21
15
  onConnectionStatusChange(callback: (status: ConnectionStatus) => void): VoidFunction;
22
16
  dispose(): void;
17
+ request<const Method extends string>(method: Method, payload: PickMessagePayloadValue<ComposeMessageAction<Method, 'request'>>, signal?: AbortSignal): Promise<PickMessagePayloadValue<ComposeMessageAction<Method, 'response'>>>;
18
+ handleRequest<const Method extends string>(method: Method, handler: RequestHandler<Method>): VoidFunction;
19
+ subscribe<const Method extends string>(method: Method, payload: PickMessagePayloadValue<ComposeMessageAction<Method, 'start'>>, callback: (payload: PickMessagePayloadValue<ComposeMessageAction<Method, 'receive'>>) => void): Subscription;
20
+ handleSubscription<const Method extends string>(method: Method, handler: SubscriptionHandler<Method>): VoidFunction;
21
+ postMessage(requestId: string, payload: MessagePayloadSchema): void;
22
+ listenMessages<const Action extends MessageAction>(action: Action, callback: (requestId: string, data: PickMessagePayload<Action>) => void, onError?: (error: unknown) => void): VoidFunction;
23
23
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@novasamatech/host-api",
3
3
  "type": "module",
4
- "version": "0.5.0-18",
4
+ "version": "0.5.0-19",
5
5
  "description": "Host API: transport implementation for host - product integration.",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -24,11 +24,9 @@
24
24
  "@polkadot-api/utils": "^0.2.0",
25
25
  "nanoevents": "9.1.0",
26
26
  "nanoid": "5.1.6",
27
+ "neverthrow": "^8.2.0",
27
28
  "scale-ts": "1.6.1"
28
29
  },
29
- "peerDependencies": {
30
- "@polkadot-api/pjs-signer": "^0.6.17"
31
- },
32
30
  "publishConfig": {
33
31
  "access": "public"
34
32
  }
@@ -1,2 +0,0 @@
1
- import type { Codec } from 'scale-ts';
2
- export declare const hexCodec: Codec<`0x${string}`>;
@@ -1,8 +0,0 @@
1
- import { fromHex, toHex } from '@polkadot-api/utils';
2
- import { Bytes } from 'scale-ts';
3
- import { createTransportEncoder } from './createTransportEncoder.js';
4
- export const hexCodec = createTransportEncoder({
5
- codec: Bytes(),
6
- from: v => toHex(v),
7
- to: fromHex,
8
- });
@@ -1,6 +0,0 @@
1
- import type { Transport, TransportProvider } from './types.js';
2
- type TransportParams = Partial<{
3
- handshakeTimeout: number;
4
- }>;
5
- export declare function createTransport(provider: TransportProvider, params?: TransportParams): Transport;
6
- export {};
@@ -1,183 +0,0 @@
1
- import { createNanoEvents } from 'nanoevents';
2
- import { nanoid } from 'nanoid';
3
- import { HANDSHAKE_INTERVAL } from './constants.js';
4
- import { delay, promiseWithResolvers } from './helpers.js';
5
- import { messageEncoder } from './messageEncoder.js';
6
- export function createTransport(provider, params) {
7
- const handshakeTimeout = params?.handshakeTimeout ?? Number.POSITIVE_INFINITY;
8
- const handshakeAbortController = new AbortController();
9
- let handshakePromise = null;
10
- let connectionStatusResolved = false;
11
- let connectionStatus = 'disconnected';
12
- let disposed = false;
13
- const events = createNanoEvents();
14
- events.on('connectionStatus', value => {
15
- connectionStatus = value;
16
- });
17
- function changeConnectionStatus(status) {
18
- events.emit('connectionStatus', status);
19
- }
20
- function throwIfDisposed() {
21
- if (disposed) {
22
- throw new Error('Transport is disposed');
23
- }
24
- }
25
- function throwIfIncorrectEnvironment() {
26
- if (!provider.isCorrectEnvironment()) {
27
- throw new Error('Environment is not correct');
28
- }
29
- }
30
- function connectionStatusToBoolean(connectionStatus) {
31
- switch (connectionStatus) {
32
- case 'disconnected':
33
- case 'connecting':
34
- return false;
35
- case 'connected':
36
- return true;
37
- }
38
- }
39
- const transportInstance = {
40
- provider,
41
- isCorrectEnvironment() {
42
- return provider.isCorrectEnvironment();
43
- },
44
- isReady() {
45
- throwIfIncorrectEnvironment();
46
- throwIfDisposed();
47
- if (connectionStatusResolved) {
48
- return Promise.resolve(connectionStatusToBoolean(connectionStatus));
49
- }
50
- if (handshakePromise) {
51
- return handshakePromise;
52
- }
53
- changeConnectionStatus('connecting');
54
- let resolved = false;
55
- const request = new Promise(resolve => {
56
- const id = nanoid();
57
- const unsubscribe = transportInstance.subscribe('handshakeResponseV1', responseId => {
58
- if (responseId !== id)
59
- return;
60
- clearInterval(interval);
61
- unsubscribe();
62
- handshakeAbortController.signal.removeEventListener('abort', unsubscribe);
63
- resolved = true;
64
- resolve(true);
65
- });
66
- handshakeAbortController.signal.addEventListener('abort', unsubscribe, { once: true });
67
- const interval = setInterval(() => {
68
- if (handshakeAbortController.signal.aborted) {
69
- clearInterval(interval);
70
- resolve(false);
71
- return;
72
- }
73
- transportInstance.postMessage(id, { tag: 'handshakeRequestV1', value: undefined });
74
- }, HANDSHAKE_INTERVAL);
75
- });
76
- const promise = handshakeTimeout === Number.POSITIVE_INFINITY
77
- ? request
78
- : Promise.race([
79
- request,
80
- delay(handshakeTimeout).then(() => {
81
- if (!resolved) {
82
- handshakeAbortController.abort('Timeout');
83
- }
84
- return false;
85
- }),
86
- ]);
87
- handshakePromise = promise.then(result => {
88
- handshakePromise = null;
89
- connectionStatusResolved = true;
90
- changeConnectionStatus(result ? 'connected' : 'disconnected');
91
- return result;
92
- });
93
- return handshakePromise;
94
- },
95
- subscribeAny(callback) {
96
- throwIfIncorrectEnvironment();
97
- throwIfDisposed();
98
- return provider.subscribe(message => {
99
- let result;
100
- try {
101
- result = messageEncoder.dec(message);
102
- }
103
- catch {
104
- return;
105
- }
106
- callback(result.id, result.payload);
107
- });
108
- },
109
- subscribe(type, callback) {
110
- throwIfIncorrectEnvironment();
111
- throwIfDisposed();
112
- return transportInstance.subscribeAny((id, message) => {
113
- if (message.tag == type) {
114
- callback(id, message.value);
115
- }
116
- });
117
- },
118
- postMessage(id, payload) {
119
- throwIfIncorrectEnvironment();
120
- throwIfDisposed();
121
- const encoded = messageEncoder.enc({ id, payload });
122
- provider.postMessage(encoded);
123
- return id;
124
- },
125
- async request(payload, response, abortSignal) {
126
- throwIfIncorrectEnvironment();
127
- throwIfDisposed();
128
- const ready = await transportInstance.isReady();
129
- if (!ready) {
130
- throw new Error('Polkadot host is not ready');
131
- }
132
- abortSignal?.throwIfAborted();
133
- const requestId = nanoid();
134
- const { resolve, reject, promise } = promiseWithResolvers();
135
- const unsubscribe = transportInstance.subscribe(response, (receivedId, payload) => {
136
- if (receivedId === requestId) {
137
- abortSignal?.removeEventListener('abort', stop);
138
- unsubscribe();
139
- resolve(payload);
140
- }
141
- });
142
- const stop = () => {
143
- unsubscribe();
144
- reject(abortSignal?.reason ?? new Error('Request aborted'));
145
- };
146
- abortSignal?.addEventListener('abort', stop, { once: true });
147
- transportInstance.postMessage(requestId, payload);
148
- return promise;
149
- },
150
- handleMessage(type, handler) {
151
- throwIfIncorrectEnvironment();
152
- throwIfDisposed();
153
- return transportInstance.subscribe(type, (id, payload) => {
154
- handler(payload).then(result => {
155
- if (!result)
156
- return;
157
- transportInstance.postMessage(id, result);
158
- });
159
- });
160
- },
161
- onConnectionStatusChange(callback) {
162
- callback(connectionStatus);
163
- return events.on('connectionStatus', callback);
164
- },
165
- dispose() {
166
- disposed = true;
167
- provider.dispose();
168
- changeConnectionStatus('disconnected');
169
- events.events = {};
170
- handshakeAbortController.abort('Transport disposed');
171
- },
172
- };
173
- if (provider.isCorrectEnvironment()) {
174
- transportInstance.handleMessage('handshakeRequestV1', async () => ({
175
- tag: 'handshakeResponseV1',
176
- value: {
177
- success: true,
178
- value: undefined,
179
- },
180
- }));
181
- }
182
- return transportInstance;
183
- }
@@ -1,7 +0,0 @@
1
- import type { Codec, CodecType } from 'scale-ts';
2
- export type TransportEncoder<Public, Transported extends Codec<any>> = {
3
- codec: Transported;
4
- from: (decoded: CodecType<Transported>) => Public;
5
- to: (value: Public) => CodecType<Transported>;
6
- };
7
- export declare function createTransportEncoder<Public, Transported extends Codec<any>>(encoder: TransportEncoder<Public, Transported>): Codec<Public>;
@@ -1,5 +0,0 @@
1
- import { enhanceCodec } from 'scale-ts';
2
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3
- export function createTransportEncoder(encoder) {
4
- return enhanceCodec(encoder.codec, encoder.to, encoder.from);
5
- }
@@ -1,12 +0,0 @@
1
- import type { InjectedAccount } from '@polkadot-api/pjs-signer';
2
- import type { Codec, CodecType } from 'scale-ts';
3
- /**
4
- * @see {import('@polkadot/extension-inject/types').InjectedAccount}
5
- */
6
- export type InjectedAccountSchema = CodecType<typeof injectedAccountEncoder>;
7
- declare const injectedAccountEncoder: Codec<InjectedAccount>;
8
- export declare const getAccountsRequestV1Encoder: Codec<undefined>;
9
- export declare const getAccountsResponseV1Encoder: Codec<InjectedAccount[]>;
10
- export declare const accountSubscriptionV1Encoder: Codec<undefined>;
11
- export declare const accountUnsubscriptionV1Encoder: Codec<undefined>;
12
- export {};
@@ -1,40 +0,0 @@
1
- import { Enum, Option, Struct, Vector, _void, str } from 'scale-ts';
2
- import { hexCodec } from '../commonEncoders.js';
3
- import { createTransportEncoder } from '../createTransportEncoder.js';
4
- const keypairCodec = Enum({
5
- ed25519: _void,
6
- sr25519: _void,
7
- ecdsa: _void,
8
- });
9
- const keypairEncoder = createTransportEncoder({
10
- codec: keypairCodec,
11
- from: v => v.tag,
12
- to: keypair => ({
13
- tag: keypair,
14
- value: undefined,
15
- }),
16
- });
17
- const injectedAccountCodec = Struct({
18
- address: str,
19
- genesisHash: Option(hexCodec),
20
- name: Option(str),
21
- type: Option(keypairEncoder),
22
- });
23
- const injectedAccountEncoder = createTransportEncoder({
24
- codec: injectedAccountCodec,
25
- from(decoded) {
26
- return decoded;
27
- },
28
- to(value) {
29
- return {
30
- address: value.address,
31
- genesisHash: value.genesisHash ? value.genesisHash : undefined,
32
- name: value.name,
33
- type: value.type,
34
- };
35
- },
36
- });
37
- export const getAccountsRequestV1Encoder = _void;
38
- export const getAccountsResponseV1Encoder = Vector(injectedAccountEncoder);
39
- export const accountSubscriptionV1Encoder = _void;
40
- export const accountUnsubscriptionV1Encoder = _void;
@@ -1,7 +0,0 @@
1
- import type { Codec } from 'scale-ts';
2
- export declare const Nullable: <T>(inner: Codec<T>) => Codec<T | null>;
3
- export declare const Hex: (length?: number) => Codec<`0x${string}`>;
4
- export declare const GenericErr: Codec<{
5
- reason: string;
6
- }>;
7
- export declare const GenesisHash: Codec<`0x${string}`>;
@@ -1,8 +0,0 @@
1
- import { fromHex, toHex } from '@polkadot-api/utils';
2
- import { Bytes, Option, Struct, enhanceCodec, str } from 'scale-ts';
3
- export const Nullable = (inner) => enhanceCodec(Option(inner), v => v ?? undefined, v => v ?? null);
4
- export const Hex = (length) => enhanceCodec(Bytes(length), fromHex, v => toHex(v));
5
- export const GenericErr = Struct({
6
- reason: str,
7
- });
8
- export const GenesisHash = Hex();
@@ -1,13 +0,0 @@
1
- export declare const supportFeatureRequestV1Encoder: import("scale-ts").Codec<{
2
- tag: "chain";
3
- value: {
4
- genesisHash: `0x${string}`;
5
- };
6
- }>;
7
- export declare const supportFeatureResponseV1: import("scale-ts").Codec<{
8
- tag: "chain";
9
- value: {
10
- genesisHash: `0x${string}`;
11
- result: boolean;
12
- };
13
- }>;
@@ -1,13 +0,0 @@
1
- import { Enum, Struct, bool } from 'scale-ts';
2
- import { hexCodec } from '../commonEncoders.js';
3
- export const supportFeatureRequestV1Encoder = Enum({
4
- chain: Struct({
5
- genesisHash: hexCodec,
6
- }),
7
- });
8
- export const supportFeatureResponseV1 = Enum({
9
- chain: Struct({
10
- genesisHash: hexCodec,
11
- result: bool,
12
- }),
13
- });
@@ -1,2 +0,0 @@
1
- export declare const handshakeRequestV1Encoder: import("scale-ts").Codec<undefined>;
2
- export declare const handshakeResponseV1Encoder: import("scale-ts").Codec<undefined>;
@@ -1,3 +0,0 @@
1
- import { _void } from 'scale-ts';
2
- export const handshakeRequestV1Encoder = _void;
3
- export const handshakeResponseV1Encoder = _void;